Skip to content

pep8 test #323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 15, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ before_install:
- conda update --yes --all
- travis_retry conda create --yes -n test python=$PYTHON --file requirements.txt
- source activate test
- travis_retry conda install --yes pytest pandas vincent
- conda install --yes --file requirements-dev.txt
- travis_retry conda install --yes pytest pandas vincent flake8
- if [[ "$PYTHON" != "3.5" ]]; then
travis_retry conda install --yes mock ;
fi
- travis_retry pip install

script:
- python setup.py test
- find ./folium -type f -name "*.py" | xargs flake8 --max-line-length=100
- find ./tests -type f -name "*.py" | xargs flake8 --max-line-length=100
4 changes: 2 additions & 2 deletions folium/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from __future__ import absolute_import

__version__ = '0.2.0.dev'

from folium.folium import Map, initialize_notebook, CircleMarker

from folium.map import (FeatureGroup, FitBounds, Icon, LayerControl, Marker,
Expand All @@ -14,6 +12,8 @@
MarkerCluster, MultiPolyLine, PolyLine, Vega,
RegularPolygonMarker, TopoJson, WmsTileLayer)

__version__ = '0.2.0.dev'

__all__ = ['Map',
'initialize_notebook',
'CircleMarker',
Expand Down
308 changes: 173 additions & 135 deletions folium/colormap.py

Large diffs are not rendered by default.

15 changes: 9 additions & 6 deletions folium/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def _get_self_bounds(self):
"""Computes the bounds of the object itself (not including it's children)
in the form [[lat_min, lon_min], [lat_max, lon_max]]
"""
return [[None,None],[None,None]]
return [[None, None], [None, None]]

def get_bounds(self):
"""Computes the bounds of the object and all it's children
Expand Down Expand Up @@ -480,8 +480,10 @@ def _repr_html_(self, **kwargs):
out = self._parent._repr_html_(**kwargs)
return out


class IFrame(Element):
def __init__(self, html=None, width="100%", height=None, ratio="60%", figsize=None):
def __init__(self, html=None, width="100%", height=None, ratio="60%",
figsize=None):
"""Create a Figure object, to plot things into it.

Parameters
Expand Down Expand Up @@ -525,16 +527,16 @@ def render(self, **kwargs):
----------

"""
html = super(IFrame,self).render(**kwargs)
html = super(IFrame, self).render(**kwargs)
html = "data:text/html;base64," + base64.b64encode(html.encode('utf8')).decode('utf8') # noqa

if self.height is None:
iframe = (
'<div style="width:{width};">'
'<div style="position:relative;width:100%;height:0;padding-bottom:{ratio};">'
'<iframe src="{html}" style="position:absolute;width:100%;height:100%;left:0;top:0;">'
'<div style="position:relative;width:100%;height:0;padding-bottom:{ratio};">' # noqa
'<iframe src="{html}" style="position:absolute;width:100%;height:100%;left:0;top:0;">' # noqa
'</iframe>'
'</div></div>').format # noqa
'</div></div>').format
iframe = iframe(html=html,
width=self.width,
ratio=self.ratio)
Expand All @@ -544,6 +546,7 @@ def render(self, **kwargs):
iframe = iframe(html=html, width=self.width, height=self.height)
return iframe


class MacroElement(Element):
"""This is a parent class for Elements defined by a macro template.
To compute your own element, all you have to do is:
Expand Down
83 changes: 49 additions & 34 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from .element import Element, Figure, JavascriptLink, CssLink, MacroElement
from .map import Layer, Icon, Marker, Popup


class WmsTileLayer(Layer):
def __init__(self, url, name=None,
format=None, layers=None, transparent=True,
Expand Down Expand Up @@ -49,6 +50,7 @@ def __init__(self, url, name=None,
{% endmacro %}
""") # noqa


class RegularPolygonMarker(Marker):
def __init__(self, location, color='black', opacity=1, weight=2,
fill_color='blue', fill_opacity=1,
Expand Down Expand Up @@ -128,6 +130,7 @@ def render(self, **kwargs):
JavascriptLink("https://cdnjs.cloudflare.com/ajax/libs/leaflet-dvf/0.2/leaflet-dvf.markers.min.js"), # noqa
name='dvf_js')


class Vega(Element):
def __init__(self, data, width=None, height=None,
left="0%", top="0%", position='relative'):
Expand All @@ -137,13 +140,16 @@ def __init__(self, data, width=None, height=None,
"""
super(Vega, self).__init__()
self._name = 'Vega'
self.data = data.to_json() if hasattr(data,'to_json') else data
if isinstance(self.data,text_type) or isinstance(data,binary_type):
self.data = data.to_json() if hasattr(data, 'to_json') else data
# FIXME:
if isinstance(self.data, text_type) or isinstance(data, binary_type):
self.data = json.loads(self.data)

# Size Parameters.
self.width = _parse_size(self.data.get('width','100%') if width is None else width)
self.height = _parse_size(self.data.get('height','100%') if height is None else height)
self.width = _parse_size(self.data.get('width', '100%') if
width is None else width)
self.height = _parse_size(self.data.get('height', '100%') if
height is None else height)
self.left = _parse_size(left)
self.top = _parse_size(top)
self.position = position
Expand Down Expand Up @@ -191,6 +197,7 @@ def render(self, **kwargs):
vg.parse.spec(spec, function(chart) { chart({el:div}).update(); });}"""), # noqa
name='vega_parse')


class GeoJson(MacroElement):
def __init__(self, data, style_function=None):
"""
Expand Down Expand Up @@ -220,20 +227,22 @@ def __init__(self, data, style_function=None):
>>> # Providing string.
>>> GeoJson(open('foo.json').read())

>>> # Providing a style_function that put all states in green, but Alabama in blue.
>>> style_function=lambda x: {'fillColor': '#0000ff' if x['properties']['name']=='Alabama' else '#00ff00'}
>>> # Provide a style_function that color all states green but Alabama.
>>> style_function = lambda x: {'fillColor': '#0000ff' if
... x['properties']['name']=='Alabama' else
... '#00ff00'}
>>> GeoJson(geojson, style_function=style_function)
"""
super(GeoJson, self).__init__()
self._name = 'GeoJson'
if hasattr(data,'read'):
if hasattr(data, 'read'):
self.embed = True
self.data = json.load(data)
elif isinstance(data,dict):
elif isinstance(data, dict):
self.embed = True
self.data = data
elif isinstance(data, text_type) or isinstance(data, binary_type):
if data.lstrip()[0] in '[{': # This is a GeoJSON inline string
if data.lstrip()[0] in '[{': # This is a GeoJSON inline string
self.embed = True
self.data = json.loads(data)
else: # This is a filename
Expand All @@ -242,18 +251,19 @@ def __init__(self, data, style_function=None):
elif data.__class__.__name__ in ['GeoDataFrame', 'GeoSeries']:
self.embed = True
if hasattr(data, '__geo_interface__'):
# We have a GeoPandas 0.2 object
self.data = json.loads(json.dumps(data.to_crs(epsg='4326').__geo_interface__))
# We have a GeoPandas 0.2 object.
self.data = json.loads(json.dumps(data.to_crs(epsg='4326').__geo_interface__)) # noqa
elif hasattr(data, 'columns'):
# We have a GeoDataFrame 0.1
self.data = json.loads(data.to_crs(epsg='4326').to_json())
else:
raise ValueError('Unable to transform this object to a GeoJSON.')
msg = 'Unable to transform this object to a GeoJSON.'
raise ValueError(msg)
else:
raise ValueError('Unhandled object {!r}.'.format(data))

if style_function is None:
style_function = lambda x: {}
def style_function(x): return {}
self.style_function = style_function

self._template = Template(u"""
Expand All @@ -268,14 +278,13 @@ def __init__(self, data, style_function=None):
def style_data(self):
if 'features' not in self.data.keys():
# Catch case when GeoJSON is just a single Feature or a geometry.
if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()):
if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa
# Catch case when GeoJSON is just a geometry.
self.data = {'type' : 'Feature', 'geometry' : self.data}
self.data = {'type' : 'FeatureCollection', 'features' : [self.data]}
self.data = {'type': 'Feature', 'geometry': self.data}
self.data = {'type': 'FeatureCollection', 'features': [self.data]}

for feature in self.data['features']:
feature.setdefault('properties',{}).setdefault('style',{}).update(
self.style_function(feature))
feature.setdefault('properties', {}).setdefault('style', {}).update(self.style_function(feature)) # noqa
return json.dumps(self.data, sort_keys=True)

def _get_self_bounds(self):
Expand All @@ -287,14 +296,14 @@ def _get_self_bounds(self):

if 'features' not in self.data.keys():
# Catch case when GeoJSON is just a single Feature or a geometry.
if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()):
if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa
# Catch case when GeoJSON is just a geometry.
self.data = {'type' : 'Feature', 'geometry' : self.data}
self.data = {'type' : 'FeatureCollection', 'features' : [self.data]}
self.data = {'type': 'Feature', 'geometry': self.data}
self.data = {'type': 'FeatureCollection', 'features': [self.data]}

bounds = [[None,None],[None,None]]
bounds = [[None, None], [None, None]]
for feature in self.data['features']:
for point in iter_points(feature.get('geometry',{}).get('coordinates',{})):
for point in iter_points(feature.get('geometry', {}).get('coordinates', {})): # noqa
bounds = [
[
none_min(bounds[0][0], point[1]),
Expand All @@ -307,6 +316,7 @@ def _get_self_bounds(self):
]
return bounds


class TopoJson(MacroElement):
def __init__(self, data, object_path, style_function=None):
"""
Expand All @@ -328,7 +338,7 @@ def __init__(self, data, object_path, style_function=None):
self.object_path = object_path

if style_function is None:
style_function = lambda x: {}
def style_function(x): return {}
self.style_function = style_function

self._template = Template(u"""
Expand All @@ -341,18 +351,17 @@ def __init__(self, data, object_path, style_function=None):
{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});

{% endmacro %}
""")
""") # noqa

def style_data(self):
def recursive_get(data, keys):
if len(keys):
return recursive_get(data.get(keys[0]), keys[1:])
else:
return data
geometries = recursive_get(self.data, self.object_path.split('.'))['geometries']
geometries = recursive_get(self.data, self.object_path.split('.'))['geometries'] # noqa
for feature in geometries:
feature.setdefault('properties',{}).setdefault('style',{}).update(
self.style_function(feature))
feature.setdefault('properties', {}).setdefault('style', {}).update(self.style_function(feature)) # noqa
return json.dumps(self.data, sort_keys=True)

def render(self, **kwargs):
Expand All @@ -373,10 +382,10 @@ def _get_self_bounds(self):
if not self.embed:
raise ValueError('Cannot compute bounds of non-embedded TopoJSON.')

xmin,xmax,ymin,ymax = None, None, None, None
xmin, xmax, ymin, ymax = None, None, None, None

for arc in self.data['arcs']:
x,y = 0,0
x, y = 0, 0
for dx, dy in arc:
x += dx
y += dy
Expand All @@ -386,16 +395,17 @@ def _get_self_bounds(self):
ymax = none_max(y, ymax)
return [
[
self.data['transform']['translate'][0] + self.data['transform']['scale'][0] * xmin,
self.data['transform']['translate'][1] + self.data['transform']['scale'][1] * ymin,
self.data['transform']['translate'][0] + self.data['transform']['scale'][0] * xmin, # noqa
self.data['transform']['translate'][1] + self.data['transform']['scale'][1] * ymin, # noqa
],
[
self.data['transform']['translate'][0] + self.data['transform']['scale'][0] * xmax,
self.data['transform']['translate'][1] + self.data['transform']['scale'][1] * ymax,
self.data['transform']['translate'][0] + self.data['transform']['scale'][0] * xmax, # noqa
self.data['transform']['translate'][1] + self.data['transform']['scale'][1] * ymax, # noqa
]

]


class ColorScale(MacroElement):
def __init__(self, color_domain, color_code, caption=""):
"""
Expand Down Expand Up @@ -425,6 +435,7 @@ def render(self, **kwargs):
JavascriptLink("https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"), # noqa
name='d3')


class MarkerCluster(Layer):
"""Adds a MarkerCluster layer on the map."""
def __init__(self, overlay=True, control=True):
Expand Down Expand Up @@ -549,6 +560,7 @@ def __init__(self, location, radius=500, color='black',
{% endmacro %}
""")


class LatLngPopup(MacroElement):
def __init__(self):
"""
Expand Down Expand Up @@ -667,6 +679,7 @@ def _get_self_bounds(self):
]
return bounds


class MultiPolyLine(MacroElement):
def __init__(self, locations, color=None, weight=None,
opacity=None, latlon=True, popup=None):
Expand Down Expand Up @@ -713,6 +726,7 @@ def __init__(self, locations, color=None, weight=None,
{{this._parent.get_name()}}.addLayer({{this.get_name()}});
{% endmacro %}
""") # noqa

def _get_self_bounds(self):
"""Computes the bounds of the object itself (not including it's children)
in the form [[lat_min, lon_min], [lat_max, lon_max]]
Expand All @@ -731,6 +745,7 @@ def _get_self_bounds(self):
]
return bounds


class CustomIcon(Icon):
def __init__(self, icon_image, icon_size=None, icon_anchor=None,
shadow_image=None, shadow_size=None, shadow_anchor=None,
Expand Down
Loading