desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Args: address: A string or integer representing the IP \'192.168.1.1\' Additionally, an integer can be passed, so IPv4Address(\'192.168.1.1\') == IPv4Address(3232235777). or, more generally IPv4Address(int(IPv4Address(\'192.168.1.1\'))) == IPv4Address(\'192.168.1.1\') Raises: AddressValueError: If ipaddr isn\'t a vali...
def __init__(self, address):
_BaseV4.__init__(self, address) if isinstance(address, (int, long)): self._ip = address if ((address < 0) or (address > self._ALL_ONES)): raise AddressValueError(address) return if isinstance(address, Bytes): try: (self._ip,) = struct.unpack('!I', addr...
'Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. \'192.168.1.1/24\' \'192.168.1.1/255.255.255.0\' \'192.168.1.1/0.0.0.255\' are all functionally the same in IPv4. Similarly, \'192.168.1.1\' \'192.168.1.1/255.255.255.255\' \'192.168.1.1/32\' are also functionaly...
def __init__(self, address, strict=False):
_BaseNet.__init__(self, address) _BaseV4.__init__(self, address) if isinstance(address, (int, long, Bytes)): self.ip = IPv4Address(address) self._ip = self.ip._ip self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) return addr = str(ad...
'Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask.'
def _is_hostmask(self, ip_str):
bits = ip_str.split('.') try: parts = [int(x) for x in bits if (int(x) in self._valid_mask_octets)] except ValueError: return False if (len(parts) != len(bits)): return False if (parts[0] < parts[(-1)]): return True return False
'Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask.'
def _is_valid_netmask(self, netmask):
mask = netmask.split('.') if (len(mask) == 4): if [x for x in mask if (int(x) not in self._valid_mask_octets)]: return False if [y for (idx, y) in enumerate(mask) if ((idx > 0) and (y > mask[(idx - 1)]))]: return False return True try: netmask = int(ne...
'Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: A long, the IPv6 ip_str. Raises: AddressValueError: if ip_str isn\'t a valid IPv6 Address.'
def _ip_int_from_string(self, ip_str):
parts = ip_str.split(':') if (len(parts) < 3): raise AddressValueError(ip_str) if ('.' in parts[(-1)]): ipv4_int = IPv4Address(parts.pop())._ip parts.append(('%x' % ((ipv4_int >> 16) & 65535))) parts.append(('%x' % (ipv4_int & 65535))) if (len(parts) > (self._HEXTET_COUNT...
'Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn\'t strictly a hex number from [0..FFFF].'
def _parse_hextet(self, hextet_str):
if (not self._HEX_DIGITS.issuperset(hextet_str)): raise ValueError hextet_int = int(hextet_str, 16) if (hextet_int > 65535): raise ValueError return hextet_int
'Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets:...
def _compress_hextets(self, hextets):
best_doublecolon_start = (-1) best_doublecolon_len = 0 doublecolon_start = (-1) doublecolon_len = 0 for index in range(len(hextets)): if (hextets[index] == '0'): doublecolon_len += 1 if (doublecolon_start == (-1)): doublecolon_start = index ...
'Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones.'
def _string_from_ip_int(self, ip_int=None):
if ((not ip_int) and (ip_int != 0)): ip_int = int(self._ip) if (ip_int > self._ALL_ONES): raise ValueError('IPv6 address is too large') hex_str = ('%032x' % ip_int) hextets = [] for x in range(0, 32, 4): hextets.append(('%x' % int(hex_str[x:(x + 4)], 16))) hex...
'Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address.'
def _explode_shorthand_ip_string(self):
if isinstance(self, _BaseNet): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) parts = [] for i in xrange(self._HEXTET_COUNT): parts.append(('%04x' % (ip_int & 65535))) ip_int >>= 16 parts.reverse() if isinstance(self, ...
'The binary representation of this address.'
@property def packed(self):
return v6_int_to_packed(self._ip)
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details.'
@property def is_multicast(self):
return (self in IPv6Network('ff00::/8'))
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.'
@property def is_reserved(self):
return ((self in IPv6Network('::/8')) or (self in IPv6Network('100::/8')) or (self in IPv6Network('200::/7')) or (self in IPv6Network('400::/6')) or (self in IPv6Network('800::/5')) or (self in IPv6Network('1000::/4')) or (self in IPv6Network('4000::/3')) or (self in IPv6Network('6000::/3')) or (self in IPv6Network...
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2.'
@property def is_unspecified(self):
return ((self._ip == 0) and (getattr(self, '_prefixlen', 128) == 128))
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3.'
@property def is_loopback(self):
return ((self._ip == 1) and (getattr(self, '_prefixlen', 128) == 128))
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291.'
@property def is_link_local(self):
return (self in IPv6Network('fe80::/10'))
'Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6.'
@property def is_site_local(self):
return (self in IPv6Network('fec0::/10'))
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 4193.'
@property def is_private(self):
return (self in IPv6Network('fc00::/7'))
'Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise.'
@property def ipv4_mapped(self):
if ((self._ip >> 32) != 65535): return None return IPv4Address((self._ip & 4294967295))
'Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn\'t appear to be a teredo address (doesn\'t start with 2001::/32)'
@property def teredo(self):
if ((self._ip >> 96) != 536936448): return None return (IPv4Address(((self._ip >> 64) & 4294967295)), IPv4Address(((~ self._ip) & 4294967295)))
'Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn\'t appear to contain a 6to4 embedded address.'
@property def sixtofour(self):
if ((self._ip >> 112) != 8194): return None return IPv4Address(((self._ip >> 80) & 4294967295))
'Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address(\'2001:4860::\') == IPv6Address(42541956101370907050197289607612071936L). or, more generally IPv6Address(IPv6Address(\'2001:4860::\')._ip) == IPv6Address(\'2001:4860::\')...
def __init__(self, address):
_BaseV6.__init__(self, address) if isinstance(address, (int, long)): self._ip = address if ((address < 0) or (address > self._ALL_ONES)): raise AddressValueError(address) return if isinstance(address, Bytes): try: (hi, lo) = struct.unpack('!QQ', addres...
'Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. \'2001:4860::/128\' \'2001:4860:0000:0000:0000:0000:0000:0000/128\' \'2001:4860::\' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create a...
def __init__(self, address, strict=False):
_BaseNet.__init__(self, address) _BaseV6.__init__(self, address) if isinstance(address, (int, long, Bytes)): self.ip = IPv6Address(address) self._ip = self.ip._ip self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return addr = str(ad...
'Verify that the netmask/prefixlen is valid. Args: prefixlen: A string, the netmask in prefix length format. Returns: A boolean, True if the prefix represents a valid IPv6 netmask.'
def _is_valid_netmask(self, prefixlen):
try: prefixlen = int(prefixlen) except ValueError: return False return (0 <= prefixlen <= self._max_prefixlen)
'Reverse find needle from start'
def rfind(self, needle, start):
pos = self._read(((self._size - start) - 1), start).rfind(needle) if (pos == (-1)): return pos return (start + pos)
'Size of file'
def size(self):
return self._size
'Close file'
def close(self):
self._handle.close()
'Created a Decoder for a MaxMind DB Arguments: database_buffer -- an mmap\'d MaxMind DB file. pointer_base -- the base number to use when decoding a pointer pointer_test -- used for internal unit testing of pointer code'
def __init__(self, database_buffer, pointer_base=0, pointer_test=False):
self._pointer_test = pointer_test self._buffer = database_buffer self._pointer_base = pointer_base
'Decode a section of the data section starting at offset Arguments: offset -- the location of the data structure to decode'
def decode(self, offset):
new_offset = (offset + 1) (ctrl_byte,) = struct.unpack('!B', self._buffer[offset:new_offset]) type_num = (ctrl_byte >> 5) if (not type_num): (type_num, new_offset) = self._read_extended(new_offset) if (not (type_num in self._type_decoder)): raise InvalidDatabaseError(u'Unexpected ...
'Reader for the MaxMind DB file format Arguments: database -- A path to a valid MaxMind DB file such as a GeoIP2 database file. mode -- mode to open the database with. Valid mode are: * MODE_MMAP - read from memory map. * MODE_FILE - read database as standard file. * MODE_MEMORY - load database into memory. * MODE_AUTO...
def __init__(self, database, mode=MODE_AUTO):
if (((mode == MODE_AUTO) and mmap) or (mode == MODE_MMAP)): with open(database, u'rb') as db_file: self._buffer = mmap.mmap(db_file.fileno(), 0, access=mmap.ACCESS_READ) self._buffer_size = self._buffer.size() elif (mode in (MODE_AUTO, MODE_FILE)): self._buffer = FileBuff...
'Return the metadata associated with the MaxMind DB file'
def metadata(self):
return self._metadata
'Return the record for the ip_address in the MaxMind DB Arguments: ip_address -- an IP address in the standard string notation'
def get(self, ip_address):
address = ipaddress.ip_address(ip_address) if ((address.version == 6) and (self._metadata.ip_version == 4)): raise ValueError(u'Error looking up {0}. You attempted to look up an IPv6 address in an IPv4-only database.'.format(ip_address)) pointer = self._f...
'Closes the MaxMind DB file and returns the resources to the system'
def close(self):
if (type(self._buffer) not in (str, bytes)): self._buffer.close()
'Creates new Metadata object. kwargs are key/value pairs from spec'
def __init__(self, **kwargs):
self.node_count = kwargs[u'node_count'] self.record_size = kwargs[u'record_size'] self.ip_version = kwargs[u'ip_version'] self.database_type = kwargs[u'database_type'] self.languages = kwargs[u'languages'] self.binary_format_major_version = kwargs[u'binary_format_major_version'] self.binary_...
'The size of a node in bytes'
@property def node_byte_size(self):
return (self.record_size // 4)
'The size of the search tree'
@property def search_tree_size(self):
return (self.node_count * self.node_byte_size)
''
def __init__(self, layer, tileset):
sethref = urljoin(layer.config.dirpath, tileset) (scheme, h, path, q, p, f) = urlparse(sethref) if (scheme not in ('file', '')): raise Exception(('Bad scheme in MBTiles provider, must be local file: "%s"' % scheme)) self.tileset = path self.layer = layer
'Convert configured parameters to keyword args for __init__().'
@staticmethod def prepareKeywordArgs(config_dict):
return {'tileset': config_dict['tileset']}
'Retrieve a single tile, return a TileResponse instance.'
def renderTile(self, width, height, srs, coord):
(mime_type, content) = get_tile(self.tileset, coord) formats = {'image/png': 'PNG', 'image/jpeg': 'JPEG', 'application/json': 'JSON', None: None} return TileResponse(formats[mime_type], content)
'Get mime-type and format by file extension. This only accepts "png" or "jpg" or "json".'
def getTypeByExtension(self, extension):
if (extension.lower() == 'json'): return ('application/json', 'JSON') elif (extension.lower() == 'png'): return ('image/png', 'PNG') elif (extension.lower() == 'jpg'): return ('image/jpg', 'JPEG') else: raise KnownUnknown(('MBTiles only makes .png and .jpg ...
''
def __init__(self, filename, format, name):
self.filename = filename if (not tileset_exists(filename)): create_tileset(filename, name, 'baselayer', '0', '', format.lower())
'Remove a cached tile.'
def remove(self, layer, coord, format):
delete_tile(self.filename, coord)
'Return raw tile content from tileset.'
def read(self, layer, coord, format):
return get_tile(self.filename, coord)[1]
'Write raw tile content to tileset.'
def save(self, body, layer, coord, format):
put_tile(self.filename, coord, body)
'Acquire a cache lock for this tile. Returns nothing, but blocks until the lock has been acquired.'
def lock(self, layer, coord, format):
key = (tile_key(layer, coord, format, self.key_prefix) + '-lock') due = (_time() + layer.stale_lock_timeout) while (_time() < due): if self.conn.setnx(key, 'locked.'): return _sleep(0.2) self.conn.set(key, 'locked.') return
'Release a cache lock for this tile.'
def unlock(self, layer, coord, format):
key = tile_key(layer, coord, format, self.key_prefix) self.conn.delete((key + '-lock'))
'Remove a cached tile.'
def remove(self, layer, coord, format):
key = tile_key(layer, coord, format, self.key_prefix) self.conn.delete(key)
'Read a cached tile.'
def read(self, layer, coord, format):
key = tile_key(layer, coord, format, self.key_prefix) value = self.conn.get(key) return value
'Save a cached tile.'
def save(self, body, layer, coord, format):
key = tile_key(layer, coord, format, self.key_prefix) cache_lifespan = layer.cache_lifespan if (cache_lifespan == 0): cache_lifespan = None self.conn.set(key, body, ex=cache_lifespan)
'Handle a request, using PATH_INFO and QUERY_STRING from environ. There are six required query string parameters: width, height, xmin, ymin, xmax and ymax. Layer name must be supplied in PATH_INFO.'
def __call__(self, environ, start_response):
try: for var in 'QUERY_STRING PATH_INFO'.split(): if (var not in environ): raise KnownUnknown(('Missing "%s" environment variable' % var)) query = dict(parse_qsl(environ['QUERY_STRING'])) for param in 'width height xmin ymin xmax ymax'.s...
''
def _filepath(self, layer, coord, format):
l = layer.name() z = ('%d' % coord.zoom) e = format.lower() x = ('%06d' % coord.column) y = ('%06d' % coord.row) (x1, x2) = (x[:3], x[3:]) (y1, y2) = (y[:3], y[3:]) filepath = os.sep.join((l, z, x1, x2, y1, ((y2 + '.') + e))) return filepath
'Acquire a cache lock for this tile. Returns nothing, but (TODO) blocks until the lock has been acquired. Lock is implemented as a row in the "locks" table.'
def lock(self, layer, coord, format):
sys.stderr.write(('lock %d/%d/%d, %s' % (coord.zoom, coord.column, coord.row, format))) due = (time.time() + layer.stale_lock_timeout) while True: if (time.time() > due): sys.stderr.write(('...force %d/%d/%d, %s' % (coord.zoom, coord.column, coord.row, format))) s...
'Release a cache lock for this tile. Lock is implemented as a row in the "locks" table.'
def unlock(self, layer, coord, format):
sys.stderr.write(('unlock %d/%d/%d, %s' % (coord.zoom, coord.column, coord.row, format))) db = connect(self.dbpath, isolation_level='EXCLUSIVE').cursor() db.execute('DELETE FROM locks\n WHERE row=? AND ...
'Remove a cached tile.'
def remove(self, layer, coord, format):
raise NotImplementedError('LimitedDisk Cache does not yet implement the .remove() method.')
'Read a cached tile. If found, update the used column in the tiles table with current time.'
def read(self, layer, coord, format):
sys.stderr.write(('read %d/%d/%d, %s' % (coord.zoom, coord.column, coord.row, format))) path = self._filepath(layer, coord, format) fullpath = pathjoin(self.cachepath, path) if exists(fullpath): body = open(fullpath, 'r').read() sys.stderr.write(('...hit %s, set used=%d' %...
'Actually write the file to the cache directory, return its size. If filesystem block size is known, try to return actual disk space used.'
def _write(self, body, path, format):
fullpath = pathjoin(self.cachepath, path) try: umask_old = os.umask(self.umask) os.makedirs(dirname(fullpath), (511 & (~ self.umask))) except OSError as e: if (e.errno != 17): raise finally: os.umask(umask_old) (fh, tmp_path) = mkstemp(dir=self.cachepath, ...
''
def _remove(self, path):
fullpath = pathjoin(self.cachepath, path) os.unlink(fullpath)
''
def save(self, body, layer, coord, format):
sys.stderr.write(('save %d/%d/%d, %s' % (coord.zoom, coord.column, coord.row, format))) path = self._filepath(layer, coord, format) size = self._write(body, path, format) db = connect(self.dbpath).cursor() try: db.execute('INSERT INTO tiles\n ...
'Acquire a cache lock for this tile. Returns nothing, but blocks until the lock has been acquired.'
def lock(self, layer, coord, format):
key_name = tile_key(layer, coord, format) due = (time() + layer.stale_lock_timeout) while (time() < due): if (not self.bucket.get_key((key_name + '-lock'))): break _sleep(0.2) key = self.bucket.new_key((key_name + '-lock')) key.set_contents_from_string('locked.', {'Conten...
'Release a cache lock for this tile.'
def unlock(self, layer, coord, format):
key_name = tile_key(layer, coord, format) try: self.bucket.delete_key((key_name + '-lock')) except: pass
'Remove a cached tile.'
def remove(self, layer, coord, format):
key_name = tile_key(layer, coord, format) self.bucket.delete_key(key_name)
'Read a cached tile.'
def read(self, layer, coord, format):
key_name = tile_key(layer, coord, format) key = self.bucket.get_key(key_name) if (key is None): return None if layer.cache_lifespan: t = timegm(strptime(key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')) if ((time() - t) > layer.cache_lifespan): return Non...
'Save a cached tile.'
def save(self, body, layer, coord, format):
key_name = tile_key(layer, coord, format) key = self.bucket.new_key(key_name) (content_type, encoding) = guess_type(('example.' + format)) headers = ((content_type and {'Content-Type': content_type}) or {}) key.set_contents_from_string(body, headers, policy='public-read')
'Creates a new instance with the projection specified in srs, which is in Proj4 format.'
def __init__(self, srs, resolutions, tile_size=256, transformation=Transformation(1, 0, 0, 0, 1, 0)):
self.resolutions = resolutions self.tile_size = tile_size self.proj = Proj(srs) self.srs = srs self.tile_dimensions = [(self.tile_size * r) for r in self.resolutions] try: self.base_zoom = self.resolutions.index(1.0) except ValueError: raise TileStache.Core.KnownUnknown('No ...
'TODO: write me.'
def coordinateLocation(self, coord):
raise NotImplementedError('Missing Proj4Projection.coordinateLocation(), see https://github.com/migurski/TileStache/pull/127')
'Convert from Coordinate object to a Point object in the defined projection'
def coordinateProj(self, coord):
if (coord.zoom >= len(self.tile_dimensions)): raise TileStache.Core.KnownUnknown(('Requested zoom level %d outside defined resolutions.' % coord.zoom)) p = self.unproject(Point(coord.column, coord.row), (1.0 / self.tile_dimensions[coord.zoom])) return p
'Convert from Location object to a Point object in the defined projection'
def locationProj(self, location):
(x, y) = self.proj(location.lon, location.lat) return Point(x, y)
'Convert from Point object in the defined projection to a Coordinate object'
def projCoordinate(self, point, zoom=None):
if (zoom == None): zoom = self.base_zoom if (zoom >= len(self.tile_dimensions)): raise TileStache.Core.KnownUnknown(('Requested zoom level %d outside defined resolutions.' % zoom)) td = self.tile_dimensions[zoom] p = self.project(point, (1.0 / td)) row = round(p.y) ...
'Convert from Point object in the defined projection to a Location object'
def projLocation(self, point):
(x, y) = self.proj(point.x, point.y, inverse=True) return Location(y, x)
''
def __init__(self, layer, dbinfo, queries, clip=True, srid=900913, simplify=1.0, simplify_until=16, padding=0):
self.layer = layer keys = ('host', 'user', 'password', 'database', 'port', 'dbname') self.dbinfo = dict([(k, v) for (k, v) in dbinfo.items() if (k in keys)]) self.clip = bool(clip) self.srid = int(srid) self.simplify = float(simplify) self.simplify_until = int(simplify_until) self.paddin...
'Render a single tile, return a Response instance.'
def renderTile(self, width, height, srs, coord):
try: query = self.queries[coord.zoom] except IndexError: query = self.queries[(-1)] ll = self.layer.projection.coordinateProj(coord.down()) ur = self.layer.projection.coordinateProj(coord.right()) bounds = (ll.x, ll.y, ur.x, ur.y) if (not query): return EmptyResponse(boun...
'Get mime-type and format by file extension, one of "mvt", "json", "topojson" or "pbf".'
def getTypeByExtension(self, extension):
if (extension.lower() == 'mvt'): return ('application/octet-stream+mvt', 'MVT') elif (extension.lower() == 'json'): return ('application/json', 'JSON') elif (extension.lower() == 'topojson'): return ('application/json', 'TopoJSON') elif (extension.lower() == 'pbf'): retur...
'Render a single tile, return a Response instance.'
def renderTile(self, width, height, srs, coord):
return MultiResponse(self.layer.config, self.names, coord)
'Get mime-type and format by file extension, "json", "topojson" or "pbf" only.'
def getTypeByExtension(self, extension):
if (extension.lower() == 'json'): return ('application/json', 'JSON') elif (extension.lower() == 'topojson'): return ('application/json', 'TopoJSON') elif (extension.lower() == 'pbf'): return ('application/x-protobuf', 'PBF') else: raise ValueError(extension)
'Create a new response object with Postgres connection info and a query. bounds argument is a 4-tuple with (xmin, ymin, xmax, ymax).'
def __init__(self, dbinfo, srid, subquery, columns, bounds, tolerance, zoom, clip, coord, layer_name='', padding=0):
self.dbinfo = dbinfo self.bounds = bounds self.zoom = zoom self.clip = clip self.coord = coord self.layer_name = layer_name self.padding = padding tol_idx = (coord.zoom if (0 <= coord.zoom < len(tolerances)) else (-1)) tol_val = tolerances[tol_idx] self.padding = (self.padding * ...
''
def save(self, out, format):
with Connection(self.dbinfo) as db: db.execute(self.query[format]) features = [] for row in db.fetchall(): if (row['__geometry__'] is None): continue wkb = bytes(row['__geometry__']) prop = dict([(k, v) for (k, v) in row.items() if (k not i...
''
def save(self, out, format):
if (format == 'MVT'): mvt.encode(out, []) elif (format == 'JSON'): geojson.encode(out, [], 0, False) elif (format == 'TopoJSON'): ll = SphericalMercator().projLocation(Point(*self.bounds[0:2])) ur = SphericalMercator().projLocation(Point(*self.bounds[2:4])) topojson.e...
'Create a new response object with TileStache config and layer names.'
def __init__(self, config, names, coord):
self.config = config self.names = names self.coord = coord
''
def save(self, out, format):
if (format == 'TopoJSON'): topojson.merge(out, self.names, self.config, self.coord) elif (format == 'JSON'): geojson.merge(out, self.names, self.config, self.coord) elif (format == 'PBF'): feature_layers = [] layers = [self.config.layers[name] for name in self.names] ...
'Make a new Datasource. Parameters: template: Required URL template with placeholders for tile zoom, x and y, e.g. "http://example.com/layer/{z}/{x}/{y}.json". sort_key: Optional field name to use when sorting features for rendering. E.g. "name" or "name ascending" to sort ascending by name, "name descending" to sort d...
def __init__(self, template, sort_key=None, clipped='true', zoom_data='single'):
(scheme, host, path, p, query, f) = urlparse(template) self.host = host self.port = (443 if (scheme == 'https') else 80) if (':' in host): self.host = host.split(':', 1)[0] self.port = int(host.split(':', 1)[1]) self.path = ((path + ('?' if query else '')) + query) self.path = se...
''
def features(self, query):
logging.debug(('Rendering %s' % str(query.bbox))) tiles = list_tiles(query, self.zoom_adjust) features = [] seen = set() for (wkb, props) in load_features(8, self.host, self.port, self.path, tiles): if (not self.clipped): key = (wkb, tuple(sorted(props.items()))) i...
'Get mime-type and format by file extension. This only accepts "json".'
def getTypeByExtension(self, extension):
if (extension.lower() != 'json'): raise KnownUnknown(('PostGeoJSON only makes .json tiles, not "%s"' % extension)) return ('application/json', 'JSON')
'Render a single tile, return a SaveableResponse instance.'
def renderTile(self, width, height, srs, coord):
(minx, miny, maxx, maxy) = self.layer.envelope(coord) y = (miny + ((maxy - miny) / 2)) x = (minx + ((maxx - minx) / 2)) (sw_lat, sw_lon) = self.unproject(minx, miny) (ne_lat, ne_lon) = self.unproject(maxx, maxy) (center_lat, center_lon) = self.unproject(x, y) bbox = ('%s:[%s TO %s] ...
''
def __init__(self, layer, mapfile, fields, layer_index=0, wrapper=None, scale=4, buffer=0):
self.mapnik = None self.layer = layer maphref = urljoin(layer.config.dirpath, mapfile) (scheme, h, path, q, p, f) = urlparse(maphref) if (scheme in ('file', '')): self.mapfile = path else: self.mapfile = maphref self.layer_index = layer_index self.wrapper = wrapper se...
''
def renderTile(self, width, height, srs, coord):
if (self.mapnik is None): self.mapnik = get_mapnikMap(self.mapfile) buffer = (float(self.buffer) / 256) nw = self.layer.projection.coordinateLocation(coord.left(buffer).up(buffer)) se = self.layer.projection.coordinateLocation(coord.right((1 + buffer)).down((1 + buffer))) ul = self.mercator....
'Get mime-type and format by file extension. This only accepts "json".'
def getTypeByExtension(self, extension):
if (extension.lower() != 'json'): raise KnownUnknown(('MapnikGrid only makes .json tiles, not "%s"' % extension)) return ('application/json; charset=utf-8', 'JSON')
'Make a new Composite.Provider. Arguments: layer: The current TileStache.Core.Layer stack: A list or dictionary with configuration for the image stack, parsed by build_stack(). Also acceptable is a URL to a JSON file. stackfile: *Deprecated* filename for an XML representation of the image stack.'
def __init__(self, layer, stack=None, stackfile=None):
self.layer = layer if (type(stack) in (str, unicode)): stack = jsonload(urlopen(urljoin(layer.config.dirpath, stack)).read()) if (type(stack) in (list, dict)): self.stack = build_stack(stack) elif ((stack is None) and stackfile): stackfile = pathjoin(self.layer.config.dirpath, st...
'A new image layer. Arguments: layername: Name of the primary source image layer. colorname: Fill color, passed to make_color(). maskname: Name of the mask image layer.'
def __init__(self, layername=None, colorname=None, maskname=None, opacity=1.0, blendmode=None, adjustments=None, zoom=''):
self.layername = layername self.colorname = colorname self.maskname = maskname self.opacity = opacity self.blendmode = blendmode self.adjustments = adjustments zooms = (re.search('^(\\d+)-(\\d+)$|^(\\d+)$', zoom) if zoom else None) if zooms: (min_zoom, max_zoom, at_zoom) = zooms....
'Return true if the requested zoom level is valid for this layer.'
def in_zoom(self, zoom):
return ((self.min_zoom <= zoom) and (zoom <= self.max_zoom))
'Render this image layer. Given a configuration object, starting image, and coordinate, return an output image with the contents of this image layer.'
def render(self, config, input_rgba, coord):
(has_layer, has_color, has_mask) = (False, False, False) output_rgba = [chan.copy() for chan in input_rgba] if self.layername: layer = config.layers[self.layername] (mime, body) = TileStache.getTile(layer, coord, 'png') layer_img = Image.open(StringIO(body)).convert('RGBA') l...
'A new image stack. Argument: layers: List of Layer instances.'
def __init__(self, layers):
self.layers = layers
''
def in_zoom(self, level):
return True
'Render this image stack. Given a configuration object, starting image, and coordinate, return an output image with the results of all the layers in this stack pasted on in turn.'
def render(self, config, input_rgba, coord):
stack_rgba = [numpy.zeros(chan.shape, chan.dtype) for chan in input_rgba] for layer in self.layers: try: if layer.in_zoom(coord.zoom): stack_rgba = layer.render(config, stack_rgba, coord) except IOError: pass return blend_images(input_rgba, stack_rgba[...
'Get mime-type and format by file extension. This only accepts "json".'
def getTypeByExtension(self, extension):
if (extension.lower() != 'json'): raise KnownUnknown(('PostGeoJSON only makes .json tiles, not "%s"' % extension)) return ('application/json', 'JSON')
'Render a single tile, return a SaveableResponse instance.'
def renderTile(self, width, height, srs, coord):
nw = self.layer.projection.coordinateLocation(coord) se = self.layer.projection.coordinateLocation(coord.right().down()) ul = self.mercator.locationProj(nw) lr = self.mercator.locationProj(se) bbox = ('ST_SetSRID(ST_MakeBox2D(ST_MakePoint(%.6f, %.6f), ST_MakePoint(%.6f, %.6f)), 900913)' ...
'Return a little thumbs-up / thumbs-down image with text in it.'
def do_I_have_to_draw_you_a_picture(self):
if self.success: (bytes, color) = (_thumbs_up_bytes, _thumbs_up_color) else: (bytes, color) = (_thumbs_down_bytes, _thumbs_down_color) thumb = Image.open(StringIO(bytes)) image = Image.new('RGB', (256, 256), color) image.paste(thumb.resize((128, 128)), (64, 80)) mapnik_url = ('ht...
''
def __init__(self, layer, database, username, password=None, hostname=None, table_prefix='mirrorosm', api_base='http://open.mapquestapi.com/xapi/', osm2pgsql='osm2pgsql --utf8-sanitize'):
self.layer = layer self.dbkwargs = {'database': database} self.api_base = api_base self.prefix = table_prefix self.osm2pgsql = osm2pgsql if hostname: self.dbkwargs['host'] = hostname if username: self.dbkwargs['user'] = username if password: self.dbkwargs['passwor...
'Get mime-type and format by file extension. This only accepts "txt".'
def getTypeByExtension(self, extension):
if (extension.lower() == 'txt'): return ('text/plain', 'TXT') elif (extension.lower() == 'png'): return ('image/png', 'PNG') else: raise KnownUnknown(('MirrorOSM only makes .txt and .png tiles, not "%s"' % extension))
'Render a single tile, return a ConfirmationResponse instance.'
def renderTile(self, width, height, srs, coord):
if (coord.zoom < 12): raise KnownUnknown(('MirrorOSM provider only handles data at zoom 12 or higher, not %d.' % coord.zoom)) start = time() garbage = [] (handle, filename) = mkstemp(prefix='mirrorosm-', suffix='.tablename') tmp_prefix = ('mirrorosm_' + b16en...
'Get mime-type and format by file extension. This only accepts "json".'
def getTypeByExtension(self, extension):
if (extension.lower() != 'json'): raise KnownUnknown(('UtfGridComposite only makes .json tiles, not "%s"' % extension)) return ('text/json', 'JSON')
''
def __init__(self, layer, database=None, username=None, password=None, hostname=None):
self.layer = layer self.dbkwargs = {} if hostname: self.dbkwargs['host'] = hostname if username: self.dbkwargs['user'] = username if database: self.dbkwargs['database'] = database if password: self.dbkwargs['password'] = password