prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
<|fim_middle|>
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | return None |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
<|fim_middle|>
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
<|fim_middle|>
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
<|fim_middle|>
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
<|fim_middle|>
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
<|fim_middle|>
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
<|fim_middle|>
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
<|fim_middle|>
<|fim▁end|> | self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
<|fim_middle|>
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | return None |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
<|fim_middle|>
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | return self.cache[key] |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
<|fim_middle|>
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer)) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
<|fim_middle|>
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | layer = layer[layer.rindex(",") + 1:] |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
<|fim_middle|>
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | layer = self.legendlayer |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
<|fim_middle|>
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | x, y = latlon_to_custom(lat, lon, self.bounds) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
<|fim_middle|>
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | x, y = lon, lat |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
<|fim_middle|>
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | x, y = latlon_to_google (lat, lon) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
<|fim_middle|>
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | x, y = transform(pLatlon, self.projection, lon, lat) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
<|fim_middle|>
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
<|fim_middle|>
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | l, m = y, x |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
<|fim_middle|>
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | l, m = google_to_latlon (y, x) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
<|fim_middle|>
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | l, m = transform(self.projection, pLatlon, y, x) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
<|fim_middle|>
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name]) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
<|fim_middle|>
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name]) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
<|fim_middle|>
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
<|fim_middle|>
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | ET.dump(tree) |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
<|fim_middle|>
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | layer = sorted(data.keys())[index] |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
<|fim_middle|>
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | srs = sorted(data[layer])[0] |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
<|fim_middle|>
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | self.isPLatLon = True |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
<|fim_middle|>
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
<|fim_middle|>
<|fim▁end|> | try:
self.projection = Proj(init=srs)
except:
pass |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def <|fim_middle|>(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | __init__ |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def <|fim_middle|>(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | setProgressCallback |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def <|fim_middle|>(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | getInfo |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def <|fim_middle|>(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | get |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def <|fim_middle|>(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | getLegendGraphic |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def <|fim_middle|>(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | xy_to_co |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def <|fim_middle|>(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | co_to_ll |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def <|fim_middle|>(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | geturl |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def <|fim_middle|>(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | parseLayer |
<|file_name|>WMSOverlayServer.py<|end_file_name|><|fim▁begin|>from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import ElementTree as ET
except:
pass
class WMSOverlayServer(object):
cache = {}
available_maptype = dict(roadmap='Roadmap') # default
type = "wms"
'''Generic WMS server'''
def __init__(self, progress_callback=None):
self.progress_callback = progress_callback
def setProgressCallback(self, progress_callback):
self.progress_callback = progress_callback
def getInfo(self, lat, lon, epsilon):
return None
def get(self, parent, width, height):
self.bl = parent.bottom_left
self.tr = parent.top_right
self.zoom = parent.zoom
url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height)
if not url:
return None
key = hashlib.md5(url).hexdigest()
if key in self.cache:
return self.cache[key]
try:
image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback)
self.cache[key] = image
except Exception, e:
Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e))
image = None
def getLegendGraphic(self):
if self.legend is None and not self.triedlegend:
self.triedlegend = True
layer = self.layer
if "," in layer:
layer = layer[layer.rindex(",") + 1:]
if self.legendlayer:
layer = self.legendlayer
url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer)
try:
print 'http://' + self.provider_host + url
image = Loader.image('http://' + self.provider_host + url)
self.legend = image
except Exception, e:
Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer))
return self.legend
def xy_to_co(self, lat, lon):
if self.customBounds:
x, y = latlon_to_custom(lat, lon, self.bounds)
elif self.isPLatLon: # patch for android - does not require pyproj library
x, y = lon, lat
elif self.isPGoogle: # patch for android - does not require pyproj library
x, y = latlon_to_google (lat, lon)
else:
x, y = transform(pLatlon, self.projection, lon, lat)
return x, y
def co_to_ll(self, x, y):
if self.customBounds:
u, v = custom_to_unit(lat, lon, self.bounds)
l, m = unit_to_latlon(u, v)
elif self.isPLatLon: # patch for android - does not require pyproj library
l, m = y, x
elif self.isPGoogle: # patch for android - does not require pyproj library
l, m = google_to_latlon (y, x)
else:
l, m = transform(self.projection, pLatlon, y, x)
return l, m
def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h):
try:
x1, y1 = self.xy_to_co(lat1, lon1)
x2, y2 = self.xy_to_co(lat2, lon2)
return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h)
except RuntimeError, e:
return None
def parseLayer(self, layer, data):
try:
name = layer.find("Name").text
except:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def <|fim_middle|>(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or srs is None:
capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip()
try:
tree = ET.fromstring(capabilities)
if self.debug:
ET.dump(tree)
layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS
data = {}
for l in layers:
self.parseLayer(l, data)
# Choose Layer and SRS by (alphabetical) index
if layer is None:
layer = sorted(data.keys())[index]
if srs is None:
srs = sorted(data[layer])[0]
except:
pass
print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs)
# generate tile URL and init projection by EPSG code
self.layer = layer
self.baseurl = baseurl
self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs)
self.isPGoogle = False
self.isPLatLon = False
self.legend = None
self.legendlayer = None
self.triedlegend = False
if srs == "EPSG:4326":
self.isPLatLon = True
elif srs == "EPSG:900913" or srs == "EPSG:3857":
self.isPGoogle = True
try:
self.projection = pGoogle
except:
pass
else:
try:
self.projection = Proj(init=srs)
except:
pass
<|fim▁end|> | initFromGetCapabilities |
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-<|fim▁hole|>
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sites', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_pk', models.TextField(verbose_name='object ID')),
('user_name', models.CharField(max_length=50, verbose_name="user's name", blank=True)),
('user_email', models.EmailField(max_length=254, verbose_name="user's email address", blank=True)),
('user_url', models.URLField(verbose_name="user's URL", blank=True)),
('comment', models.TextField(max_length=3000, verbose_name='comment')),
('submit_date', models.DateTimeField(default=None, verbose_name='date/time submitted', db_index=True)),
('ip_address', models.GenericIPAddressField(unpack_ipv4=True, null=True, verbose_name='IP address', blank=True)),
('is_public', models.BooleanField(default=True, help_text='Uncheck this box to make the comment effectively disappear from the site.', verbose_name='is public')),
('is_removed', models.BooleanField(default=False, help_text='Check this box if the comment is inappropriate. A "This comment has been removed" message will be displayed instead.', verbose_name='is removed')),
('content_type', models.ForeignKey(related_name='content_type_set_for_comment', verbose_name='content type', to='contenttypes.ContentType', on_delete=models.CASCADE)),
('site', models.ForeignKey(to='sites.Site', on_delete=models.CASCADE)),
('user', models.ForeignKey(related_name='comment_comments', verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)),
],
options={
'ordering': ('submit_date',),
'abstract': False,
'verbose_name': 'comment',
'verbose_name_plural': 'comments',
'permissions': [('can_moderate', 'Can moderate comments')],
},
),
]<|fim▁end|> | from __future__ import unicode_literals |
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
<|fim_middle|>
<|fim▁end|> | dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sites', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_pk', models.TextField(verbose_name='object ID')),
('user_name', models.CharField(max_length=50, verbose_name="user's name", blank=True)),
('user_email', models.EmailField(max_length=254, verbose_name="user's email address", blank=True)),
('user_url', models.URLField(verbose_name="user's URL", blank=True)),
('comment', models.TextField(max_length=3000, verbose_name='comment')),
('submit_date', models.DateTimeField(default=None, verbose_name='date/time submitted', db_index=True)),
('ip_address', models.GenericIPAddressField(unpack_ipv4=True, null=True, verbose_name='IP address', blank=True)),
('is_public', models.BooleanField(default=True, help_text='Uncheck this box to make the comment effectively disappear from the site.', verbose_name='is public')),
('is_removed', models.BooleanField(default=False, help_text='Check this box if the comment is inappropriate. A "This comment has been removed" message will be displayed instead.', verbose_name='is removed')),
('content_type', models.ForeignKey(related_name='content_type_set_for_comment', verbose_name='content type', to='contenttypes.ContentType', on_delete=models.CASCADE)),
('site', models.ForeignKey(to='sites.Site', on_delete=models.CASCADE)),
('user', models.ForeignKey(related_name='comment_comments', verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)),
],
options={
'ordering': ('submit_date',),
'abstract': False,
'verbose_name': 'comment',
'verbose_name_plural': 'comments',
'permissions': [('can_moderate', 'Can moderate comments')],
},
),
] |
<|file_name|>bip.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
#################################################################################################
#
# Script Name: bip.py
# Script Usage: This script is the menu system and runs everything else. Do not use other
# files unless you are comfortable with the code.
#
# It has the following:
# 1.
# 2.
# 3.
# 4.
#
# You will probably want to do the following:
# 1. Make sure the info in bip_config.py is correct.
# 2. Make sure GAM (Google Apps Manager) is installed and the path is correct.
# 3. Make sure the AD scripts in toos/ are present on the DC running run.ps1.
#<|fim▁hole|>#################################################################################################
import os # os.system for clearing screen and simple gam calls
import subprocess # subprocess.Popen is to capture gam output (needed for user info in particular)
import MySQLdb # MySQLdb is to get data from relevant tables
import csv # CSV is used to read output of drive commands that supply data in CSV form
import bip_config # declare installation specific variables
# setup for MySQLdb connection
varMySQLHost = bip_config.mysqlconfig['host']
varMySQLUser = bip_config.mysqlconfig['user']
varMySQLPassword = bip_config.mysqlconfig['password']
varMySQLDB = bip_config.mysqlconfig['db']
# setup to find GAM
varCommandGam = bip_config.gamconfig['fullpath']
#################################################################################################
#
#################################################################################################<|fim▁end|> | # Script Updates:
# 201709191243 - [email protected] - copied boilerplate.
# |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy<|fim▁hole|>
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))<|fim▁end|> |
import pytest |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
<|fim_middle|>
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
<|fim_middle|>
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | @pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
<|fim_middle|>
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | assert expected == actual |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
<|fim_middle|>
<|fim▁end|> | def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'})) |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
<|fim_middle|>
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'})) |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
<|fim_middle|>
<|fim▁end|> | with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'})) |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
<|fim_middle|>
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | test_contents.update(updates) |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def <|fim_middle|>(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | get_updated_line_contents |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def <|fim_middle|>(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | test_retrieval |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def <|fim_middle|>(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def test_passing_non_parseable_status_throws_exception(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | test_passing_invalid_ip_address_throws_exception |
<|file_name|>test_line.py<|end_file_name|><|fim▁begin|>import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
'path': '/',
'status': '200',
'size': '193',
'referrer': '-',
'user_agent': 'Python'
}
def get_updated_line_contents(updates=None):
test_contents = copy.deepcopy(test_line_contents)
if updates is not None:
test_contents.update(updates)
return test_contents
test_line = Line(line_contents=test_line_contents)
class TestLineInstantiation:
@pytest.mark.parametrize('expected,actual', [
('127.0.0.1', test_line.ip_address),
(1, test_line.timestamp),
('GET', test_line.verb),
('/', test_line.path),
(200, test_line.status),
(193, test_line.byte_count),
('-', test_line.referrer),
('Python', test_line.user_agent)
])
def test_retrieval(self, expected, actual):
assert expected == actual
class TestLineExceptions:
def test_passing_invalid_ip_address_throws_exception(self):
with pytest.raises(InvalidIpAddressException):
line = Line(line_contents=get_updated_line_contents({'ip_address': 'foobar'}))
def <|fim_middle|>(self):
with pytest.raises(InvalidStatusException):
Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
<|fim▁end|> | test_passing_non_parseable_status_throws_exception |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):<|fim▁hole|> self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []<|fim▁end|> | def __init__(self, view):
super(NQueensController, self)
self._piece_data = None |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
<|fim_middle|>
<|fim▁end|> | def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return [] |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
<|fim_middle|>
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
<|fim_middle|>
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | return cls(view) |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
<|fim_middle|>
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | pass |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
<|fim_middle|>
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
}) |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
<|fim_middle|>
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
<|fim_middle|>
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
}) |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
<|fim_middle|>
<|fim▁end|> | candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return [] |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
<|fim_middle|>
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
}) |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
<|fim_middle|>
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
}) |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
<|fim_middle|>
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | return True |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
<|fim_middle|>
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
<|fim_middle|>
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx]) |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
<|fim_middle|>
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | return True |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
<|fim_middle|>
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | panel.remove_piece(pieces[idx]) |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
<|fim_middle|>
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | self._piece_cache = Meta.get_piece_definitions() |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
<|fim_middle|>
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | self._piece_data = self._piece_data[1] |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
<|fim_middle|>
else:
return []
<|fim▁end|> | return [candidate[0][attr] for candidate in candidates.values()] |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
<|fim_middle|>
<|fim▁end|> | return [] |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def <|fim_middle|>(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | __init__ |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def <|fim_middle|>(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | get_instance |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def <|fim_middle|>(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | pre_switch |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def <|fim_middle|>(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | start |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def <|fim_middle|>(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | run |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def <|fim_middle|>(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def get_pieces_attr(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | piece_selected |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|>import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod
def get_instance(cls, view):
return cls(view)
def pre_switch(self):
pass
def start(self):
dim = self.view.get_dimension()
# Cached factory, only 1 file read per list
pieces = [Piece.from_file(self._piece_data) for i in range(dim)]
panel = Panel(dim)
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = self.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
'data': {
'message': 'No solution found :(',
}
})
def run(self, panel, pieces, idx, ci):
dim = panel.dimension
# Base case
if idx == len(pieces):
return True
else:
# Ultra-fast because:
# 1. All the pieces are the same (less combinations and shit)
# 2. We start from the previous index, this makes the panel smaller
# each time
# 3. Instead of keeping track of the killing positions we do a
# check each time a piece is added in order to avoid a kill
# (which is faster)
# 4. Python dict operations are astonishingly fast
for i in range(ci, dim):
for j in range(dim):
if panel.add_piece(pieces[idx], (i, j)):
if self.run(panel, pieces, idx+1, i):
return True
else:
panel.remove_piece(pieces[idx])
return False
def piece_selected(self, piece_name):
if not self._piece_cache:
self._piece_cache = Meta.get_piece_definitions()
self._piece_data = self._piece_cache.get(piece_name)
if self._piece_data:
self._piece_data = self._piece_data[1]
self.view.notify({
'func': 'enable_run',
'data': {
'enable': bool(self._piece_data),
}
})
@staticmethod
def <|fim_middle|>(attr):
candidates = Meta.get_piece_definitions()
if all(attr in candidate[0].keys() for candidate in candidates.values()):
return [candidate[0][attr] for candidate in candidates.values()]
else:
return []
<|fim▁end|> | get_pieces_attr |
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):<|fim▁hole|>
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)<|fim▁end|> | self._set_fortune()
self._set_motion()
self._set_wanda() |
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
<|fim_middle|>
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | """
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
<|fim_middle|>
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
i<|fim_middle|>
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | f not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
f<|fim_middle|>
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | or k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
s<|fim_middle|>
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | elf.index += 1
if self.index >= self.wanda_length:
self.index = 0
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
s<|fim_middle|>
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | elf._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
s<|fim_middle|>
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | elf.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
i<|fim_middle|>
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | f not self.fortune_command:
return
self._set_fortune(not self.toggled)
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
t <|fim_middle|>
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | imeout = time() + self.fortune_timeout
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
r <|fim_middle|>
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | eturn
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
t <|fim_middle|>
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | ry:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
s <|fim_middle|>
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | elf.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
i <|fim_middle|>
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | f self.toggled and time() >= self.time:
self._set_fortune(new=True)
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
s <|fim_middle|>
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | elf._set_fortune(new=True)
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
s <|fim_middle|>
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | elf.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
s <|fim_middle|>
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | elf._set_fortune(new=True)
|
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
s <|fim_middle|>
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
<|fim▁end|> | elf.fortune = None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.