Skip to content

Commit

Permalink
Merge pull request #49 from ocefpaf/extra_req
Browse files Browse the repository at this point in the history
Extra tests...
  • Loading branch information
ocefpaf authored Nov 5, 2018
2 parents 38bdb9c + 2f06dbc commit 5ad162f
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 91 deletions.
6 changes: 5 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ install:
script:
- if [[ $TEST_TARGET == 'default' ]]; then
cp -r tests/ /tmp && cd /tmp ;
py.test -vv tests ;
pytest -vvv tests ;
fi

- if [[ $TEST_TARGET == 'coding_standards' ]]; then
Expand All @@ -63,6 +63,10 @@ script:
python -m doctr deploy --sync --built-docs docs/build/html . ;
fi

doctr:
require-master: true
sync: False

deploy:
skip_cleanup: true
provider: pypi
Expand Down
3 changes: 2 additions & 1 deletion branca/colormap.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@
import math

from branca.element import ENV, Figure, JavascriptLink, MacroElement
from branca.six import binary_type, text_type
from branca.utilities import legend_scaler

from jinja2 import Template

import pkg_resources

from six import binary_type, text_type


resource_package = __name__
resource_path_schemes = '/_schemes.json'
Expand Down
50 changes: 26 additions & 24 deletions branca/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,18 @@
"""

import base64
import json
import warnings
from collections import OrderedDict
from uuid import uuid4

from jinja2 import Environment, PackageLoader, Template
from collections import OrderedDict
import json
import base64

from .six import urlopen, text_type, binary_type
from .utilities import _camelify, _parse_size, none_min, none_max
from six import binary_type, text_type
from six.moves.urllib.request import urlopen

from .utilities import _camelify, _parse_size, none_max, none_min


ENV = Environment(loader=PackageLoader('branca', 'templates'))
Expand Down Expand Up @@ -43,9 +45,9 @@ class Element(object):
"""
_template = Template(
"{% for name, element in this._children.items() %}\n"
" {{element.render(**kwargs)}}"
"{% endfor %}"
'{% for name, element in this._children.items() %}\n'
' {{element.render(**kwargs)}}'
'{% endfor %}'
)

def __init__(self, template=None, template_name=None):
Expand Down Expand Up @@ -96,7 +98,7 @@ def get_bounds(self):

def add_children(self, child, name=None, index=None):
"""Add a child."""
warnings.warn("Method `add_children` is deprecated. Please use `add_child` instead.",
warnings.warn('Method `add_children` is deprecated. Please use `add_child` instead.',
FutureWarning, stacklevel=2)
return self.add_child(child, name=name, index=index)

Expand Down Expand Up @@ -187,7 +189,7 @@ def to_dict(self, depth=-1, **kwargs):

class JavascriptLink(Link):
"""Create a JavascriptLink object based on a url.
Parameters
----------
url : str
Expand Down Expand Up @@ -215,7 +217,7 @@ def __init__(self, url, download=False):

class CssLink(Link):
"""Create a CssLink object based on a url.
Parameters
----------
url : str
Expand Down Expand Up @@ -277,7 +279,7 @@ class Figure(Element):
'</script>\n'
)

def __init__(self, width="100%", height=None, ratio="60%", title=None, figsize=None):
def __init__(self, width='100%', height=None, ratio='60%', title=None, figsize=None):
super(Figure, self).__init__()
self._name = 'Figure'
self.header = Element()
Expand Down Expand Up @@ -374,10 +376,10 @@ def add_subplot(self, x, y, n, margin=0.05):
height = height*(1-2.*margin)

div = Div(position='absolute',
width="{}%".format(100.*width),
height="{}%".format(100.*height),
left="{}%".format(100.*left),
top="{}%".format(100.*top),
width='{}%'.format(100.*width),
height='{}%'.format(100.*height),
left='{}%'.format(100.*left),
top='{}%'.format(100.*top),
)
self.add_child(div)
return div
Expand Down Expand Up @@ -406,7 +408,7 @@ class Html(Element):
'{% if this.script %}{{this.data}}{% else %}{{this.data|e}}{% endif %}</div>'
) # noqa

def __init__(self, data, script=False, width="100%", height="100%"):
def __init__(self, data, script=False, width='100%', height='100%'):
super(Html, self).__init__()
self._name = 'Html'
self.script = script
Expand Down Expand Up @@ -449,7 +451,7 @@ class Div(Figure):
)

def __init__(self, width='100%', height='100%',
left="0%", top="0%", position='relative'):
left='0%', top='0%', position='relative'):
super(Figure, self).__init__()
self._name = 'Div'

Expand Down Expand Up @@ -479,8 +481,8 @@ def get_root(self):
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
figure = self._parent
assert isinstance(figure, Figure), ("You cannot render this Element "
"if it's not in a Figure.")
assert isinstance(figure, Figure), ('You cannot render this Element '
'if it is not in a Figure.')

for name, element in self._children.items():
element.render(**kwargs)
Expand Down Expand Up @@ -539,7 +541,7 @@ class IFrame(Element):
For example figsize=(10, 5) will result in
width="600px", height="300px".
"""
def __init__(self, html=None, width="100%", height=None, ratio="60%",
def __init__(self, html=None, width='100%', height=None, ratio='60%',
figsize=None):
super(IFrame, self).__init__()
self._name = 'IFrame'
Expand Down Expand Up @@ -600,7 +602,7 @@ class MacroElement(Element):
{% endmacro %}
"""
_template = Template(u"")
_template = Template(u'')

def __init__(self):
super(MacroElement, self).__init__()
Expand All @@ -609,8 +611,8 @@ def __init__(self):
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
figure = self.get_root()
assert isinstance(figure, Figure), ("You cannot render this Element "
"if it's not in a Figure.")
assert isinstance(figure, Figure), ('You cannot render this Element '
'if it is not in a Figure.')

header = self._template.module.__dict__.get('header', None)
if header is not None:
Expand Down
24 changes: 0 additions & 24 deletions branca/six.py

This file was deleted.

76 changes: 38 additions & 38 deletions branca/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,20 @@
"""

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import, division, print_function

import base64
import json
import math
import zlib
import struct
import json
import pkg_resources
import base64
import zlib

from jinja2 import Environment, PackageLoader

import pkg_resources

from six import binary_type, text_type

try:
import pandas as pd
except ImportError:
Expand All @@ -29,8 +31,6 @@
except ImportError:
np = None

from branca.six import text_type, binary_type


def get_templates():
"""Get Jinja templates."""
Expand Down Expand Up @@ -113,11 +113,11 @@ def color_brewer(color_code, n=6):

# Raise an error if the n requested is greater than the maximum.
if n > maximum_n:
raise ValueError("The maximum number of colors in a"
" ColorBrewer sequential color series is 253")
raise ValueError('The maximum number of colors in a'
' ColorBrewer sequential color series is 253')
if n < minimum_n:
raise ValueError("The minimum number of colors in a"
" ColorBrewer sequential color series is 3")
raise ValueError('The minimum number of colors in a'
' ColorBrewer sequential color series is 3')

if color_code[-2:] == '_r':
base_code = color_code[:-2]
Expand Down Expand Up @@ -146,7 +146,7 @@ def color_brewer(color_code, n=6):
core_schemes = json.loads(core_schemes_string)['codes']

if base_code not in core_schemes:
raise ValueError(base_code + " is not a valid ColorBrewer code")
raise ValueError(base_code + ' is not a valid ColorBrewer code')

try:
schemes[core_color_code]
Expand All @@ -163,11 +163,11 @@ def color_brewer(color_code, n=6):
if base_code + '_' in key:
matching_quals.append(int(key.split('_')[1]))

raise ValueError("Expanded color support is not available"
" for Qualitative schemes; restrict the"
" number of colors for the " + base_code +
" code to between " + str(min(matching_quals)) +
" and " + str(max(matching_quals))
raise ValueError('Expanded color support is not available'
' for Qualitative schemes; restrict the'
' number of colors for the ' + base_code +
' code to between ' + str(min(matching_quals)) +
' and ' + str(max(matching_quals))
)
else:
if not color_reverse:
Expand Down Expand Up @@ -198,11 +198,11 @@ def split_six(series=None):
"""
if pd is None:
raise ImportError("The Pandas package is required"
" for this functionality")
raise ImportError('The Pandas package is required'
' for this functionality')
if np is None:
raise ImportError("The NumPy package is required"
" for this functionality")
raise ImportError('The NumPy package is required'
' for this functionality')

def base(x):
if x > 0:
Expand Down Expand Up @@ -244,13 +244,13 @@ def image_to_url(image, colormap=None, origin='upper'):
fileformat = image.name.lower().split('.')[-1]
else:
fileformat = 'png'
url = "data:image/{};base64,{}".format(
url = 'data:image/{};base64,{}'.format(
fileformat, base64.b64encode(image.read()).decode('utf-8'))
elif (not (isinstance(image, text_type) or
isinstance(image, binary_type))) and hasattr(image, '__iter__'):
# We got an array-like object.
png = write_png(image, origin=origin, colormap=colormap)
url = "data:image/png;base64," + base64.b64encode(png).decode('utf-8')
url = 'data:image/png;base64,' + base64.b64encode(png).decode('utf-8')
else:
# We got an URL.
url = json.loads(json.dumps(image))
Expand All @@ -265,7 +265,7 @@ def write_png(data, origin='upper', colormap=None):
for an inline PNG like this:
>>> png_str = write_png(array)
>>> "data:image/png;base64,"+png_str.encode('base64')
>>> 'data:image/png;base64,'+png_str.encode('base64')
Inspired from
http://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image
Expand All @@ -290,8 +290,8 @@ def write_png(data, origin='upper', colormap=None):
PNG formatted byte string
"""
if np is None:
raise ImportError("The NumPy package is required"
" for this functionality")
raise ImportError('The NumPy package is required'
' for this functionality')

if colormap is None:
def colormap(x):
Expand All @@ -301,16 +301,16 @@ def colormap(x):
height, width, nblayers = array.shape

if nblayers not in [1, 3, 4]:
raise ValueError("Data must be NxM (mono), "
"NxMx3 (RGB), or NxMx4 (RGBA)")
raise ValueError('Data must be NxM (mono), '
'NxMx3 (RGB), or NxMx4 (RGBA)')
assert array.shape == (height, width, nblayers)

if nblayers == 1:
array = np.array(list(map(colormap, array.ravel())))
nblayers = array.shape[1]
if nblayers not in [3, 4]:
raise ValueError("colormap must provide colors of"
"length 3 (RGB) or 4 (RGBA)")
raise ValueError('colormap must provide colors of'
'length 3 (RGB) or 4 (RGBA)')
array = array.reshape((height, width, nblayers))
assert array.shape == (height, width, nblayers)

Expand All @@ -335,20 +335,20 @@ def colormap(x):

def png_pack(png_tag, data):
chunk_head = png_tag + data
return (struct.pack("!I", len(data)) +
return (struct.pack('!I', len(data)) +
chunk_head +
struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head)))
struct.pack('!I', 0xFFFFFFFF & zlib.crc32(chunk_head)))

return b''.join([
b'\x89PNG\r\n\x1a\n',
png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
png_pack(b'IHDR', struct.pack('!2I5B', width, height, 8, 6, 0, 0, 0)),
png_pack(b'IDAT', zlib.compress(raw_data, 9)),
png_pack(b'IEND', b'')])


def _camelify(out):
return (''.join(["_" + x.lower() if i < len(out)-1 and x.isupper() and out[i+1].islower() # noqa
else x.lower() + "_" if i < len(out)-1 and x.islower() and out[i+1].isupper() # noqa
return (''.join(['_' + x.lower() if i < len(out)-1 and x.isupper() and out[i+1].islower() # noqa
else x.lower() + '_' if i < len(out)-1 and x.islower() and out[i+1].isupper() # noqa
else x.lower() for i, x in enumerate(list(out))])).lstrip('_').replace('__', '_') # noqa


Expand All @@ -363,7 +363,7 @@ def _parse_size(value):
value = float(value.strip('%'))
assert 0 <= value <= 100
except Exception:
msg = "Cannot parse value {!r} as {!r}".format
msg = 'Cannot parse value {!r} as {!r}'.format
raise ValueError(msg(value, value_type))
return value, value_type

Expand Down
Loading

0 comments on commit 5ad162f

Please sign in to comment.