<commit_before>import pysal
import shapely.geometry
import shapely.ops
_basegeom = shapely.geometry.base.BaseGeometry
__all__ = ["to_wkb", "to_wkt", "area", "distance", "length", "boundary", "bounds", "centroid", "representative_point", "convex_hull", "envelope", "buffer", "simplify", "difference", "intersection", "symmetric_difference", "union", "cascaded_union", "has_z", "is_empty", "is_ring", "is_simple", "is_valid", "relate", "contains", "crosses", "disjoint", "equals", "intersects", "overlaps", "touches", "within", "equals_exact", "almost_equals", "project", "interpolate"]

def to_wkb(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.to_wkb()

def to_wkt(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.to_wkt()

# Real-valued properties and methods
# ----------------------------------
def area(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.area

def distance(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.distance(o2)

def length(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.length

# Topological properties
# ----------------------
def boundary(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.bondary
    return pysal.cg.shapes.asShape(res)

def bounds(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.bounds

def centroid(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.centroid
    return pysal.cg.shapes.asShape(res)

def representative_point(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.representative_point
    return pysal.cg.shapes.asShape(res)

def convex_hull(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.convex_hull
    return pysal.cg.shapes.asShape(res)

def envelope(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.envelope
    return pysal.cg.shapes.asShape(res)

def buffer(shape, radius, resolution=16):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.buffer(radius, resolution)
    return pysal.cg.shapes.asShape(res)

def simplify(shape, tolerance, preserve_topology=True):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.simplify(tolerance, preserve_topology)
    return pysal.cg.shapes.asShape(res)

# Binary operations
# -----------------
def difference(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    res = o.difference(o2)
    return pysal.cg.shapes.asShape(res)

def intersection(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    res = o.intersection(o2)
    return pysal.cg.shapes.asShape(res)

def symmetric_difference(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    res = o.symmetric_difference(o2)
    return pysal.cg.shapes.asShape(res)

def union(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    res = o.union(o2)
    return pysal.cg.shapes.asShape(res)

def cascaded_union(shapes):
    o = []
    for shape in shapes:
        if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
        o.append(shapely.geometry.asShape(shape))
    res = shapely.ops.cascaded_union(o)
    return pysal.cg.shapes.asShape(res)

# Unary predicates
# ----------------
def has_z(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.has_z

def is_empty(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.is_empty

def is_ring(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.is_ring

def is_simple(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.is_simple

def is_valid(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.is_valid

# Binary predicates
# -----------------
def relate(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.relate(o2)

def contains(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.contains(o2)

def crosses(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.crosses(o2)

def disjoint(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.disjoint(o2)

def equals(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.equals(o2)

def intersects(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.intersects(o2)

def overlaps(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.overlaps(o2)

def touches(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.touches(o2)

def within(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.within(o2)

def equals_exact(shape, other, tolerance):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.equals_exact(o2, tolerance)

def almost_equals(shape, other, decimal=6):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.almost_equals(o2, decimal)

# Linear referencing
# ------------------

def project(shape, other, normalized=False):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.project(o2, normalized)

def interpolate(shape, distance, normalized=False):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.interpolate(distance, normalized)
    return pysal.cg.shapes.asShape(res)

# Copy doc strings from shapely
for method in __all__:
    if hasattr(_basegeom, method):
        locals()[method].__doc__ = getattr(_basegeom,method).__doc__

if __name__=='__main__':
    #step 0, create 2 points
    pt1 = pysal.cg.shapes.Point((0,0))
    pt2 = pysal.cg.shapes.Point((10,10))
    o = pysal.open('step0.shp','w')
    o.write(pt1)
    o.write(pt2)
    o.close()

    #step 1, buffer 2 points
    b1 = buffer(pt1,10)
    b2 = buffer(pt2,10)
    o = pysal.open('step1.shp','w')
    o.write(b1)
    o.write(b2)
    o.close()

    #step 2, intersect 2 buffers
    i = intersection(b1,b2)
    o = pysal.open('step2.shp','w')
    o.write(i)
    o.close()

    #step 3, union 2 buffers
    u = union(b1, b2)
    o = pysal.open('step3.shp','w')
    o.write(u)
    o.close()

    #step 4, find convex_hull of union
    c = convex_hull(u)
    o = pysal.open('step4.shp','w')
    o.write(c)
    o.close()
<commit_msg>adding unary_union() to shapely contrib; note this only works with shapely version 1.2.16 or higher<commit_after>import shapely
import shapely.geometry
import shapely.ops
_basegeom = shapely.geometry.base.BaseGeometry
import pysal
__all__ = ["to_wkb", "to_wkt", "area", "distance", "length", "boundary", "bounds", "centroid", "representative_point", "convex_hull", "envelope", "buffer", "simplify", "difference", "intersection", "symmetric_difference", "union", "unary_union", "cascaded_union", "has_z", "is_empty", "is_ring", "is_simple", "is_valid", "relate", "contains", "crosses", "disjoint", "equals", "intersects", "overlaps", "touches", "within", "equals_exact", "almost_equals", "project", "interpolate"]

def to_wkb(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.to_wkb()

def to_wkt(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.to_wkt()

# Real-valued properties and methods
# ----------------------------------
def area(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.area

def distance(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.distance(o2)

def length(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.length

# Topological properties
# ----------------------
def boundary(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.bondary
    return pysal.cg.shapes.asShape(res)

def bounds(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.bounds

def centroid(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.centroid
    return pysal.cg.shapes.asShape(res)

def representative_point(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.representative_point
    return pysal.cg.shapes.asShape(res)

def convex_hull(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.convex_hull
    return pysal.cg.shapes.asShape(res)

def envelope(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.envelope
    return pysal.cg.shapes.asShape(res)

def buffer(shape, radius, resolution=16):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.buffer(radius, resolution)
    return pysal.cg.shapes.asShape(res)

def simplify(shape, tolerance, preserve_topology=True):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.simplify(tolerance, preserve_topology)
    return pysal.cg.shapes.asShape(res)

# Binary operations
# -----------------
def difference(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    res = o.difference(o2)
    return pysal.cg.shapes.asShape(res)

def intersection(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    res = o.intersection(o2)
    return pysal.cg.shapes.asShape(res)

def symmetric_difference(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    res = o.symmetric_difference(o2)
    return pysal.cg.shapes.asShape(res)

def union(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    res = o.union(o2)
    return pysal.cg.shapes.asShape(res)

def cascaded_union(shapes):
    o = []
    for shape in shapes:
        if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
        o.append(shapely.geometry.asShape(shape))
    res = shapely.ops.cascaded_union(o)
    return pysal.cg.shapes.asShape(res)

def unary_union(shapes):
    # seems to be the same as cascade_union except that it handles multipart polygons
    if shapely.__version__ < '1.2.16':
        raise Exception, "shapely 1.2.16 or higher needed for unary_union; upgrade shapely or try cascade_union instead"
    o = []
    for shape in shapes:
        if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
        o.append(shapely.geometry.asShape(shape))
    res = shapely.ops.unary_union(o)
    return pysal.cg.shapes.asShape(res)

# Unary predicates
# ----------------
def has_z(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.has_z

def is_empty(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.is_empty

def is_ring(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.is_ring

def is_simple(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.is_simple

def is_valid(shape):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    return o.is_valid

# Binary predicates
# -----------------
def relate(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.relate(o2)

def contains(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.contains(o2)

def crosses(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.crosses(o2)

def disjoint(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.disjoint(o2)

def equals(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.equals(o2)

def intersects(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.intersects(o2)

def overlaps(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.overlaps(o2)

def touches(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.touches(o2)

def within(shape, other):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.within(o2)

def equals_exact(shape, other, tolerance):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.equals_exact(o2, tolerance)

def almost_equals(shape, other, decimal=6):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.almost_equals(o2, decimal)

# Linear referencing
# ------------------

def project(shape, other, normalized=False):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    if not hasattr(other,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    o2 = shapely.geometry.asShape(other)
    return o.project(o2, normalized)

def interpolate(shape, distance, normalized=False):
    if not hasattr(shape,'__geo_interface__'): raise TypeError, "%r does not appear to be a shape"%shape
    o = shapely.geometry.asShape(shape)
    res = o.interpolate(distance, normalized)
    return pysal.cg.shapes.asShape(res)

# Copy doc strings from shapely
for method in __all__:
    if hasattr(_basegeom, method):
        locals()[method].__doc__ = getattr(_basegeom,method).__doc__

if __name__=='__main__':
    #step 0, create 2 points
    pt1 = pysal.cg.shapes.Point((0,0))
    pt2 = pysal.cg.shapes.Point((10,10))
    o = pysal.open('step0.shp','w')
    o.write(pt1)
    o.write(pt2)
    o.close()

    #step 1, buffer 2 points
    b1 = buffer(pt1,10)
    b2 = buffer(pt2,10)
    o = pysal.open('step1.shp','w')
    o.write(b1)
    o.write(b2)
    o.close()

    #step 2, intersect 2 buffers
    i = intersection(b1,b2)
    o = pysal.open('step2.shp','w')
    o.write(i)
    o.close()

    #step 3, union 2 buffers
    u = union(b1, b2)
    o = pysal.open('step3.shp','w')
    o.write(u)
    o.close()

    #step 4, find convex_hull of union
    c = convex_hull(u)
    o = pysal.open('step4.shp','w')
    o.write(c)
    o.close()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

from opps.core.cache import cache_page

from .views import PageDetail

urlpatterns = patterns(
    '',

    # FLATPAGEs
    url(r'^page/(?P<slug>[\w]+)$',
        cache_page(60 * 2)(PageDetail.as_view()), name='open'),
)
<commit_msg>fix flatpage url<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

from opps.core.cache import cache_page

from .views import PageDetail

urlpatterns = patterns(
    '',

    # FLATPAGEs
    url(r'^page/(?P<slug>[\w]+)/$',
        cache_page(60 * 2)(PageDetail.as_view()), name='open'),
)
<|endoftext|>


<commit_before>import os
from decouple import config, Csv
from dj_database_url import parse as dburl

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

DEBUG = config('DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv())

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # thirty apps
    'django_extensions',
    # 'debug_toolbar',
    'bootstrapform',
    'widget_tweaks',
    'daterange_filter',
    # my apps
    'orcamentos.core',
    'orcamentos.crm',
    'orcamentos.proposal',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'orcamentos.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'orcamentos.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')
DATABASES = {
    'default': config('DATABASE_URL', default=default_dburl, cast=dburl),
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_L10N = True

USE_TZ = True

USE_THOUSAND_SEPARATOR = True

DECIMAL_SEPARATOR = ','

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

LOGIN_URL = '/admin/login/'
<commit_msg>Test with settings<commit_after>import os
from decouple import config, Csv
from dj_database_url import parse as dburl

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

DEBUG = config('DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv())

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # thirty apps
    'django_extensions',
    # 'debug_toolbar',
    'bootstrapform',
    'widget_tweaks',
    'daterange_filter',
    # my apps
    'orcamentos.core',
    # 'orcamentos.crm',
    # 'orcamentos.proposal',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'orcamentos.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'orcamentos.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')
DATABASES = {
    'default': config('DATABASE_URL', default=default_dburl, cast=dburl),
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_L10N = True

USE_TZ = True

USE_THOUSAND_SEPARATOR = True

DECIMAL_SEPARATOR = ','

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

LOGIN_URL = '/admin/login/'
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from collections import defaultdict
import itertools
from operator import itemgetter

from ckeditor.widgets import CKEditorWidget

from django.contrib import admin

from django.db.models import Q, Count

from django.utils.encoding import smart_text

from django.utils.translation import ugettext_lazy as _

from . import models

DEFAULT_FILTER_ROLES = (models.Membership.Roles.ADMIN,
                        models.Membership.Roles.MANAGER)

def get_memberships_by_role(membership_queryset):
    memberships_by_role = defaultdict(lambda: [])
    qs = membership_queryset.order_by('membership__role') \
        .values_list('membership__role', 'pk')
    for role, group in itertools.groupby(qs, itemgetter(0)):
        memberships_by_role[role] = map(itemgetter(1), group)
    return memberships_by_role

def get_cached_memberships(user, roles=DEFAULT_FILTER_ROLES):
    user_memberships = getattr(user, '__memberships', None)
    if not user_memberships:
        user_memberships = {
            'organizations': get_memberships_by_role(user.account.facility_set),
            'facilities': get_memberships_by_role(
                user.account.organization_set),
        }
        setattr(user, '__memberships', user_memberships)

    user_orgs = list(itertools.chain.from_iterable(
        user_memberships['organizations'][role] for role in roles))

    user_facilities = list(itertools.chain.from_iterable(
        user_memberships['facilities'][role] for role in roles))

    return user_orgs, user_facilities

def filter_queryset_by_membership(qs, user,
                                  facility_filter_fk=None,
                                  organization_filter_fk=None,
                                  roles=DEFAULT_FILTER_ROLES):
    if facility_filter_fk and organization_filter_fk:
        raise Exception(
            'facility_filter_fk and organization_filter_fk are mutually exclusive.')

    if user.is_superuser:
        return qs

    user_orgs, user_facilities = get_cached_memberships(user, roles)

    if qs.model == models.Organization:
        qs = qs.filter(pk__in=user_facilities)
    elif qs.model == models.Facility:
        qs = qs.filter(
            Q(pk__in=user_facilities) |
            Q(organization_id__in=user_orgs)
        )
    else:
        if facility_filter_fk is None and organization_filter_fk is None:
            facility_filter_fk = 'facility'

        if organization_filter_fk:
            qs = qs.filter(**{organization_filter_fk + '_id__in': user_orgs})
        elif facility_filter_fk:
            qs = qs.filter(
                Q(**{facility_filter_fk + '_id__in': user_facilities}) |
                Q(**{facility_filter_fk + '__organization_id__in': user_orgs})
            )
    print qs
    return qs

class MembershipFilteredAdmin(admin.ModelAdmin):
    facility_filter_fk = 'facility'
    widgets = None

    def get_readonly_fields(self, request, obj=None):
        readonly = super(MembershipFilteredAdmin, self).get_readonly_fields(
            request=request, obj=obj)
        if request.user.is_superuser:
            return readonly
        else:
            if not ('facility' in readonly and 'organization' in readonly):
                user_orgs, user_facilities = get_cached_memberships(
                    request.user)
                if len(user_facilities) <= 1 and hasattr(obj, 'facility') \
                        and 'facility' not in readonly:
                    readonly += ('facility',)
                if len(user_orgs) <= 1 and hasattr(obj, 'organization') \
                        and 'organization' not in readonly:
                    readonly += ('organization',)
        return readonly

    def get_list_display(self, request):
        list_display = list(
            super(MembershipFilteredAdmin, self).get_list_display(request))
        if request.user.is_superuser:
            return list_display
        if 'facility' in list_display or 'organization' in list_display:
            user_orgs, user_facilities = get_cached_memberships(request.user)
            if len(user_facilities) <= 1 and 'facility' in list_display:
                list_display.remove('facility')
            if len(user_orgs) <= 1 and 'organization' in list_display:
                list_display.remove('organization')
        return list_display

    def get_list_display_links(self, request, list_display):
        list_display_links = list(
            super(MembershipFilteredAdmin, self).get_list_display_links(request,
                                                                        list_display))
        return filter(lambda i: i in list_display, list_display_links)

    def get_edit_link(self, obj):
        return _(u'edit')

    get_edit_link.short_description = _(u'edit')

    def get_form(self, request, obj=None, **kwargs):
        form = super(MembershipFilteredAdmin, self).get_form(
            request, obj, widgets=self.widgets, **kwargs)

        if 'facility' in form.base_fields:
            facilities = models.Facility.objects.all()
            user_facilities = filter_queryset_by_membership(facilities,
                                                            request.user)
            if len(user_facilities) == 1:
                form.base_fields['facility'].initial = user_facilities.get()

        return form

    def get_queryset(self, request):
        qs = super(MembershipFilteredAdmin, self).get_queryset(request)
        return filter_queryset_by_membership(
            qs, user=request.user, facility_filter_fk=self.facility_filter_fk)

    def get_field_queryset(self, db, db_field, request):
        qs = super(MembershipFilteredAdmin, self).get_field_queryset(
            db, db_field, request)
        if db_field.rel.to in (models.Facility,
                               models.Organization,
                               models.Task,
                               models.Workplace):
            qs = qs or db_field.rel.to.objects.all()
            qs = filter_queryset_by_membership(qs, request.user)
        return qs

class MembershipFilteredTabularInline(admin.TabularInline):
    facility_filter_fk = 'facility'
    widgets = None

    def get_formset(self, request, obj=None, **kwargs):
        return super(MembershipFilteredTabularInline, self).get_formset(
            request, obj, widgets=self.widgets, **kwargs)

    def get_queryset(self, request):
        qs = super(MembershipFilteredTabularInline, self).get_queryset(request)
        return filter_queryset_by_membership(
            qs, user=request.user, facility_filter_fk=self.facility_filter_fk)

    def get_field_queryset(self, db, db_field, request):
        qs = super(MembershipFilteredTabularInline, self).get_field_queryset(
            db, db_field, request)
        if db_field.rel.to in (models.Facility,
                               models.Organization,
                               models.Task,
                               models.Workplace):
            qs = qs or db_field.rel.to.objects.all()
            qs = filter_queryset_by_membership(qs, request.user)
        return qs

class MembershipFieldListFilter(admin.RelatedFieldListFilter):
    def field_choices(self, field, request, model_admin):
        query = field.rel.to.objects.all()
        query = query.annotate(usage_count=Count(field.related_query_name()))
        query = query.exclude(usage_count=0)
        qs = filter_queryset_by_membership(query, request.user)
        return [(x._get_pk_val(), smart_text(x)) for x in qs]

@admin.register(models.Organization)
class OrganizationAdmin(MembershipFilteredAdmin):
    list_display = (
        'name',
        'short_description',
        'description',
        'contact_info',
        'address',
    )
    raw_id_fields = ('members',)
    search_fields = ('name',)
    widgets = {
        'short_description': CKEditorWidget(),
        'description': CKEditorWidget(),
        'contact_info': CKEditorWidget(),
    }

@admin.register(models.Facility)
class FacilityAdmin(MembershipFilteredAdmin):
    list_display = (
        'organization',
        'name',
        'short_description',
        'description',
        'contact_info',
        'place',
        'address',
        'zip_code',
        'show_on_map',
        'latitude',
        'longitude',
    )
    list_filter = (
        ('organization', MembershipFieldListFilter),
    )
    raw_id_fields = ('members',)
    search_fields = ('name',)
    widgets = {
        'short_description': CKEditorWidget(),
        'description': CKEditorWidget(),
        'contact_info': CKEditorWidget(),
    }

@admin.register(models.OrganizationMembership)
class OrganizationMembershipAdmin(MembershipFilteredAdmin):
    list_display = (
        'user_account',
        'organization',
        'role',
    )
    list_filter = (
        ('organization', MembershipFieldListFilter),
    )
    raw_id_fields = ('user_account',)

@admin.register(models.FacilityMembership)
class FacilityMembershipAdmin(MembershipFilteredAdmin):
    list_display = (
        'role',
        'user_account',
        'facility'
    )
    list_filter = (
        ('facility', MembershipFieldListFilter),
    )
    raw_id_fields = ('user_account',)

@admin.register(models.Workplace)
class WorkplaceAdmin(MembershipFilteredAdmin):
    list_display = (
        'facility',
        'name',
        'description'
    )
    list_filter = (
        ('facility', MembershipFieldListFilter),
    )
    search_fields = ('name',)
    list_select_related = True
    radio_fields = {"facility": admin.VERTICAL}
    widgets = {
        'description': CKEditorWidget(),
    }

@admin.register(models.Task)
class TaskAdmin(MembershipFilteredAdmin):
    list_display = (
        'facility',
        'name',
        'description'
    )
    list_filter = (
        ('facility', MembershipFieldListFilter),
    )
    search_fields = ('name',)
    list_select_related = True
    radio_fields = {"facility": admin.VERTICAL}
    widgets = {
        'description': CKEditorWidget(),
    }
<commit_msg>Remove print statement<commit_after># -*- coding: utf-8 -*-
from collections import defaultdict
import itertools
from operator import itemgetter

from ckeditor.widgets import CKEditorWidget

from django.contrib import admin

from django.db.models import Q, Count

from django.utils.encoding import smart_text

from django.utils.translation import ugettext_lazy as _

from . import models

DEFAULT_FILTER_ROLES = (models.Membership.Roles.ADMIN,
                        models.Membership.Roles.MANAGER)

def get_memberships_by_role(membership_queryset):
    memberships_by_role = defaultdict(lambda: [])
    qs = membership_queryset.order_by('membership__role') \
        .values_list('membership__role', 'pk')
    for role, group in itertools.groupby(qs, itemgetter(0)):
        memberships_by_role[role] = map(itemgetter(1), group)
    return memberships_by_role

def get_cached_memberships(user, roles=DEFAULT_FILTER_ROLES):
    user_memberships = getattr(user, '__memberships', None)
    if not user_memberships:
        user_memberships = {
            'organizations': get_memberships_by_role(user.account.facility_set),
            'facilities': get_memberships_by_role(
                user.account.organization_set),
        }
        setattr(user, '__memberships', user_memberships)

    user_orgs = list(itertools.chain.from_iterable(
        user_memberships['organizations'][role] for role in roles))

    user_facilities = list(itertools.chain.from_iterable(
        user_memberships['facilities'][role] for role in roles))

    return user_orgs, user_facilities

def filter_queryset_by_membership(qs, user,
                                  facility_filter_fk=None,
                                  organization_filter_fk=None,
                                  roles=DEFAULT_FILTER_ROLES):
    if facility_filter_fk and organization_filter_fk:
        raise Exception(
            'facility_filter_fk and organization_filter_fk are mutually exclusive.')

    if user.is_superuser:
        return qs

    user_orgs, user_facilities = get_cached_memberships(user, roles)

    if qs.model == models.Organization:
        qs = qs.filter(pk__in=user_facilities)
    elif qs.model == models.Facility:
        qs = qs.filter(
            Q(pk__in=user_facilities) |
            Q(organization_id__in=user_orgs)
        )
    else:
        if facility_filter_fk is None and organization_filter_fk is None:
            facility_filter_fk = 'facility'

        if organization_filter_fk:
            qs = qs.filter(**{organization_filter_fk + '_id__in': user_orgs})
        elif facility_filter_fk:
            qs = qs.filter(
                Q(**{facility_filter_fk + '_id__in': user_facilities}) |
                Q(**{facility_filter_fk + '__organization_id__in': user_orgs})
            )
    return qs

class MembershipFilteredAdmin(admin.ModelAdmin):
    facility_filter_fk = 'facility'
    widgets = None

    def get_readonly_fields(self, request, obj=None):
        readonly = super(MembershipFilteredAdmin, self).get_readonly_fields(
            request=request, obj=obj)
        if request.user.is_superuser:
            return readonly
        else:
            if not ('facility' in readonly and 'organization' in readonly):
                user_orgs, user_facilities = get_cached_memberships(
                    request.user)
                if len(user_facilities) <= 1 and hasattr(obj, 'facility') \
                        and 'facility' not in readonly:
                    readonly += ('facility',)
                if len(user_orgs) <= 1 and hasattr(obj, 'organization') \
                        and 'organization' not in readonly:
                    readonly += ('organization',)
        return readonly

    def get_list_display(self, request):
        list_display = list(
            super(MembershipFilteredAdmin, self).get_list_display(request))
        if request.user.is_superuser:
            return list_display
        if 'facility' in list_display or 'organization' in list_display:
            user_orgs, user_facilities = get_cached_memberships(request.user)
            if len(user_facilities) <= 1 and 'facility' in list_display:
                list_display.remove('facility')
            if len(user_orgs) <= 1 and 'organization' in list_display:
                list_display.remove('organization')
        return list_display

    def get_list_display_links(self, request, list_display):
        list_display_links = list(
            super(MembershipFilteredAdmin, self).get_list_display_links(request,
                                                                        list_display))
        return filter(lambda i: i in list_display, list_display_links)

    def get_edit_link(self, obj):
        return _(u'edit')

    get_edit_link.short_description = _(u'edit')

    def get_form(self, request, obj=None, **kwargs):
        form = super(MembershipFilteredAdmin, self).get_form(
            request, obj, widgets=self.widgets, **kwargs)

        if 'facility' in form.base_fields:
            facilities = models.Facility.objects.all()
            user_facilities = filter_queryset_by_membership(facilities,
                                                            request.user)
            if len(user_facilities) == 1:
                form.base_fields['facility'].initial = user_facilities.get()

        return form

    def get_queryset(self, request):
        qs = super(MembershipFilteredAdmin, self).get_queryset(request)
        return filter_queryset_by_membership(
            qs, user=request.user, facility_filter_fk=self.facility_filter_fk)

    def get_field_queryset(self, db, db_field, request):
        qs = super(MembershipFilteredAdmin, self).get_field_queryset(
            db, db_field, request)
        if db_field.rel.to in (models.Facility,
                               models.Organization,
                               models.Task,
                               models.Workplace):
            qs = qs or db_field.rel.to.objects.all()
            qs = filter_queryset_by_membership(qs, request.user)
        return qs

class MembershipFilteredTabularInline(admin.TabularInline):
    facility_filter_fk = 'facility'
    widgets = None

    def get_formset(self, request, obj=None, **kwargs):
        return super(MembershipFilteredTabularInline, self).get_formset(
            request, obj, widgets=self.widgets, **kwargs)

    def get_queryset(self, request):
        qs = super(MembershipFilteredTabularInline, self).get_queryset(request)
        return filter_queryset_by_membership(
            qs, user=request.user, facility_filter_fk=self.facility_filter_fk)

    def get_field_queryset(self, db, db_field, request):
        qs = super(MembershipFilteredTabularInline, self).get_field_queryset(
            db, db_field, request)
        if db_field.rel.to in (models.Facility,
                               models.Organization,
                               models.Task,
                               models.Workplace):
            qs = qs or db_field.rel.to.objects.all()
            qs = filter_queryset_by_membership(qs, request.user)
        return qs

class MembershipFieldListFilter(admin.RelatedFieldListFilter):
    def field_choices(self, field, request, model_admin):
        query = field.rel.to.objects.all()
        query = query.annotate(usage_count=Count(field.related_query_name()))
        query = query.exclude(usage_count=0)
        qs = filter_queryset_by_membership(query, request.user)
        return [(x._get_pk_val(), smart_text(x)) for x in qs]

@admin.register(models.Organization)
class OrganizationAdmin(MembershipFilteredAdmin):
    list_display = (
        'name',
        'short_description',
        'description',
        'contact_info',
        'address',
    )
    raw_id_fields = ('members',)
    search_fields = ('name',)
    widgets = {
        'short_description': CKEditorWidget(),
        'description': CKEditorWidget(),
        'contact_info': CKEditorWidget(),
    }

@admin.register(models.Facility)
class FacilityAdmin(MembershipFilteredAdmin):
    list_display = (
        'organization',
        'name',
        'short_description',
        'description',
        'contact_info',
        'place',
        'address',
        'zip_code',
        'show_on_map',
        'latitude',
        'longitude',
    )
    list_filter = (
        ('organization', MembershipFieldListFilter),
    )
    raw_id_fields = ('members',)
    search_fields = ('name',)
    widgets = {
        'short_description': CKEditorWidget(),
        'description': CKEditorWidget(),
        'contact_info': CKEditorWidget(),
    }

@admin.register(models.OrganizationMembership)
class OrganizationMembershipAdmin(MembershipFilteredAdmin):
    list_display = (
        'user_account',
        'organization',
        'role',
    )
    list_filter = (
        ('organization', MembershipFieldListFilter),
    )
    raw_id_fields = ('user_account',)

@admin.register(models.FacilityMembership)
class FacilityMembershipAdmin(MembershipFilteredAdmin):
    list_display = (
        'role',
        'user_account',
        'facility'
    )
    list_filter = (
        ('facility', MembershipFieldListFilter),
    )
    raw_id_fields = ('user_account',)

@admin.register(models.Workplace)
class WorkplaceAdmin(MembershipFilteredAdmin):
    list_display = (
        'facility',
        'name',
        'description'
    )
    list_filter = (
        ('facility', MembershipFieldListFilter),
    )
    search_fields = ('name',)
    list_select_related = True
    radio_fields = {"facility": admin.VERTICAL}
    widgets = {
        'description': CKEditorWidget(),
    }

@admin.register(models.Task)
class TaskAdmin(MembershipFilteredAdmin):
    list_display = (
        'facility',
        'name',
        'description'
    )
    list_filter = (
        ('facility', MembershipFieldListFilter),
    )
    search_fields = ('name',)
    list_select_related = True
    radio_fields = {"facility": admin.VERTICAL}
    widgets = {
        'description': CKEditorWidget(),
    }
<|endoftext|>


<commit_before># Copyright 2014 Andrea Micheli and Marco Gario
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import

import os
import sys

from pysmt.cmd.installers.base import SolverInstaller

class CVC4Installer(SolverInstaller):

    SOLVER = "cvc4"

    def __init__(self, install_dir, bindings_dir, solver_version,
                 mirror_link=None, git_version='HEAD'):
        archive_name = "CVC4-%s.tar.gz" % git_version
        native_link = "https://codeload.github.com/CVC4/CVC4/tar.gz/%s" % (git_version)
        SolverInstaller.__init__(self, install_dir=install_dir,
                                 bindings_dir=bindings_dir,
                                 solver_version=solver_version,
                                 archive_name=archive_name,
                                 native_link=native_link,
                                 mirror_link=mirror_link)
        self.git_version = git_version
        self.build_path = os.path.join(self.extract_path, "build")
        self.bin_path = os.path.join(self.build_path, "src", "bindings", "python")

    def move(self):
        CVC4_py = os.path.join(self.bin_path, "CVC4.py")
        CVC4_so = os.path.join(self.bin_path, "_CVC4.so")
        SolverInstaller.mv(CVC4_py, self.bindings_dir)
        SolverInstaller.mv(CVC4_so, self.bindings_dir)

    def compile(self):
        # Build ANTLR

        SolverInstaller.run("bash %s" % os.path.join("contrib", "get-antlr-3.4"),
                            directory=self.extract_path)

        # Build ABC
        # SolverInstaller.run("bash get-abc",
        #                     directory=os.path.join(self.extract_path, "contrib"))
        # Build GLPK
        # We could configure with --gpl --best, but this takes forever to build

        # Inject Python library and include paths into CMake because CVC4 search
        # system can be fooled in some systems
        import distutils.sysconfig as sysconfig
        PYTHON_LIBRARY = os.environ.get('PYSMT_PYTHON_LIBDIR')
        if not PYTHON_LIBRARY:
            PYTHON_LIBRARY = sysconfig.get_config_var('LIBDIR')
        PYTHON_INCLUDE_DIR = sysconfig.get_python_inc()
        SolverInstaller.run(['sed', '-i',
                             's|cmake_opts=""|cmake_opts="-DPYTHON_LIBRARY=' + PYTHON_LIBRARY + ' -DPYTHON_INCLUDE_DIR=' + PYTHON_INCLUDE_DIR + '"|g',
                             './configure.sh'], directory=self.extract_path)

        # Configure and build CVC4
        config_cmd = "./configure.sh --language-bindings=python \
                                     --python%s" % self.python_version[0]

        if os.path.exists(sys.executable+"-config"):
            pyconfig = {"PYTHON_CONFIG": sys.executable+"-config"}
        else:
            pyconfig = {}

        SolverInstaller.run(config_cmd, directory=self.extract_path,
                            env_variables=pyconfig)
        SolverInstaller.run("make -j3", directory=self.build_path,
                            env_variables=pyconfig)
        # SolverInstaller.run("make install", directory=self.build_path,
        #                     env_variables=pyconfig)

    def get_installed_version(self):
        return self.get_installed_version_script(self.bindings_dir, "cvc4")
<commit_msg>Fix CVC4 installation on macOS<commit_after># Copyright 2014 Andrea Micheli and Marco Gario
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import

import os
import sys
import multiprocessing

from pysmt.cmd.installers.base import SolverInstaller

class CVC4Installer(SolverInstaller):

    SOLVER = "cvc4"

    def __init__(self, install_dir, bindings_dir, solver_version,
                 mirror_link=None, git_version='HEAD'):
        archive_name = "CVC4-%s.tar.gz" % git_version
        native_link = "https://codeload.github.com/CVC4/CVC4/tar.gz/%s" % (git_version)
        SolverInstaller.__init__(self, install_dir=install_dir,
                                 bindings_dir=bindings_dir,
                                 solver_version=solver_version,
                                 archive_name=archive_name,
                                 native_link=native_link,
                                 mirror_link=mirror_link)
        self.git_version = git_version
        self.build_path = os.path.join(self.extract_path, "build")
        self.bin_path = os.path.join(self.build_path, "src", "bindings", "python")

    def move(self):
        CVC4_py = os.path.join(self.bin_path, "CVC4.py")
        CVC4_so = os.path.join(self.bin_path, "_CVC4.so")
        SolverInstaller.mv(CVC4_py, self.bindings_dir)
        SolverInstaller.mv(CVC4_so, self.bindings_dir)

    def compile(self):
        # Build ANTLR

        SolverInstaller.run("bash %s" % os.path.join("contrib", "get-antlr-3.4"),
                            directory=self.extract_path)

        # Build ABC
        # SolverInstaller.run("bash get-abc",
        #                     directory=os.path.join(self.extract_path, "contrib"))
        # Build GLPK
        # We could configure with --gpl --best, but this takes forever to build

        # Inject Python library and include paths into CMake because CVC4 search
        # system can be fooled in some systems
        import distutils.sysconfig as sysconfig
        PYTHON_LIBRARY = os.environ.get('PYSMT_PYTHON_LIBDIR')
        PYTHON_INCLUDE_DIR = sysconfig.get_python_inc()
        PYTHON_EXECUTABLE = sys.executable

        CMAKE_OPTS = '-DPYTHON_INCLUDE_DIR=' + PYTHON_INCLUDE_DIR
        CMAKE_OPTS += ' -DPYTHON_EXECUTABLE=' + PYTHON_EXECUTABLE
        if PYTHON_LIBRARY:
            CMAKE_OPTS += ' -DPYTHON_LIBRARY=' + PYTHON_LIBRARY

        SolverInstaller.run(['sed', '-i',
                             's|cmake_opts=""|cmake_opts="' + CMAKE_OPTS + '"|g',
                             './configure.sh'], directory=self.extract_path)

        # Configure and build CVC4
        config_cmd = "./configure.sh --language-bindings=python \
                                     --python%s" % self.python_version[0]

        if os.path.exists(sys.executable+"-config"):
            pyconfig = {"PYTHON_CONFIG": sys.executable+"-config"}
        else:
            pyconfig = {}

        SolverInstaller.run(config_cmd, directory=self.extract_path,
                            env_variables=pyconfig)
        SolverInstaller.run(f"make -j{multiprocessing.cpu_count()}", directory=self.build_path,
                            env_variables=pyconfig)
        # SolverInstaller.run("make install", directory=self.build_path,
        #                     env_variables=pyconfig)

    def get_installed_version(self):
        return self.get_installed_version_script(self.bindings_dir, "cvc4")
<|endoftext|>


<commit_before>import re

from django import forms
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.loader import render_to_string
from django.utils.encoding import force_text, force_unicode
from django.utils.safestring import mark_safe

try:
    from django.utils.html import format_html
except ImportError:
    # Django 1.4 compatibility
    from oscar.core.compat import format_html

class ImageInput(FileInput):
    """
    Widget providing a input element for file uploads based on the
    Django ``FileInput`` element. It hides the actual browser-specific
    input element and shows the available image for images that have
    been previously uploaded. Selecting the image will open the file
    dialog and allow for selecting a new or replacing image file.
    """
    template_name = 'partials/image_input_widget.html'
    attrs = {'accept': 'image/*'}

    def render(self, name, value, attrs=None):
        """
        Render the ``input`` field based on the defined ``template_name``. The
        image URL is take from *value* and is provided to the template as
        ``image_url`` context variable relative to ``MEDIA_URL``. Further
        attributes for the ``input`` element are provide in ``input_attrs`` and
        contain parameters specified in *attrs* and *name*.
        If *value* contains no valid image URL an empty string will be provided
        in the context.
        """
        if value is None:
            value = ''

        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_unicode(self._format_value(value))

        image_url = final_attrs.get('value', '')

        return render_to_string(self.template_name, Context({
            'input_attrs': flatatt(final_attrs),
            'image_url': image_url,
            'image_id': "%s-image" % final_attrs['id'],
        }))

class WYSIWYGTextArea(forms.Textarea):

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('attrs', {})
        kwargs['attrs'].setdefault('class', '')
        kwargs['attrs']['class'] += ' wysiwyg'
        super(WYSIWYGTextArea, self).__init__(*args, **kwargs)

def datetime_format_to_js_date_format(format):
    """
    Convert a Python datetime format to a date format suitable for use with JS
    date pickers
    """
    converted = format
    replacements = {
        '%Y': 'yy',
        '%m': 'mm',
        '%d': 'dd',
        '%H:%M': '',
    }
    for search, replace in replacements.iteritems():
        converted = converted.replace(search, replace)
    return converted.strip()

def datetime_format_to_js_time_format(format):
    """
    Convert a Python datetime format to a time format suitable for use with JS
    date pickers
    """
    converted = format
    replacements = {
        '%Y': '',
        '%m': '',
        '%d': '',
        '%H': 'HH',
        '%M': 'mm',
    }
    for search, replace in replacements.iteritems():
        converted = converted.replace(search, replace)

    converted = re.sub('[-/][^%]', '', converted)

    return converted.strip()

def add_js_formats(widget):
    """
    Set data attributes for date and time format on a widget
    """
    attrs = {
        'data-dateFormat': datetime_format_to_js_date_format(
            widget.format),
        'data-timeFormat': datetime_format_to_js_time_format(
            widget.format)
    }
    widget.attrs.update(attrs)

class DatePickerInput(forms.DateInput):
    """
    DatePicker input that uses the jQuery UI datepicker.  Data attributes are
    used to pass the date format to the JS
    """
    def __init__(self, *args, **kwargs):
        super(DatePickerInput, self).__init__(*args, **kwargs)
        add_js_formats(self)

class DateTimePickerInput(forms.DateTimeInput):
    # Build a widget which uses the locale datetime format but without seconds.
    # We also use data attributes to pass these formats to the JS datepicker.

    def __init__(self, *args, **kwargs):
        include_seconds = kwargs.pop('include_seconds', False)
        super(DateTimePickerInput, self).__init__(*args, **kwargs)

        if not include_seconds:
            self.format = re.sub(':?%S', '', self.format)
        add_js_formats(self)

class AdvancedSelect(forms.Select):
    """
    Customised Select widget that allows a list of disabled values to be passed
    to the constructor.  Django's default Select widget doesn't allow this so
    we have to override the render_option method and add a section that checks
    for whether the widget is disabled.
    """

    def __init__(self, attrs=None, choices=(), disabled_values=()):
        self.disabled_values = set(force_text(v) for v in disabled_values)
        super(AdvancedSelect, self).__init__(attrs, choices)

    def render_option(self, selected_choices, option_value, option_label):
        option_value = force_text(option_value)
        if option_value in self.disabled_values:
            selected_html = mark_safe(' disabled="disabled"')
        elif option_value in selected_choices:
            selected_html = mark_safe(' selected="selected"')
            if not self.allow_multiple_selected:
                # Only allow for a single selection.
                selected_choices.remove(option_value)
        else:
            selected_html = ''
        return format_html('<option value="{0}"{1}>{2}</option>',
                           option_value,
                           selected_html,
                           force_text(option_label))
<commit_msg>[Backport] Use unicode for AdvanceSelect widget<commit_after>import re

from django import forms
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.loader import render_to_string
from django.utils.encoding import force_text, force_unicode
from django.utils.safestring import mark_safe

try:
    from django.utils.html import format_html
except ImportError:
    # Django 1.4 compatibility
    from oscar.core.compat import format_html

class ImageInput(FileInput):
    """
    Widget providing a input element for file uploads based on the
    Django ``FileInput`` element. It hides the actual browser-specific
    input element and shows the available image for images that have
    been previously uploaded. Selecting the image will open the file
    dialog and allow for selecting a new or replacing image file.
    """
    template_name = 'partials/image_input_widget.html'
    attrs = {'accept': 'image/*'}

    def render(self, name, value, attrs=None):
        """
        Render the ``input`` field based on the defined ``template_name``. The
        image URL is take from *value* and is provided to the template as
        ``image_url`` context variable relative to ``MEDIA_URL``. Further
        attributes for the ``input`` element are provide in ``input_attrs`` and
        contain parameters specified in *attrs* and *name*.
        If *value* contains no valid image URL an empty string will be provided
        in the context.
        """
        if value is None:
            value = ''

        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_unicode(self._format_value(value))

        image_url = final_attrs.get('value', '')

        return render_to_string(self.template_name, Context({
            'input_attrs': flatatt(final_attrs),
            'image_url': image_url,
            'image_id': "%s-image" % final_attrs['id'],
        }))

class WYSIWYGTextArea(forms.Textarea):

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('attrs', {})
        kwargs['attrs'].setdefault('class', '')
        kwargs['attrs']['class'] += ' wysiwyg'
        super(WYSIWYGTextArea, self).__init__(*args, **kwargs)

def datetime_format_to_js_date_format(format):
    """
    Convert a Python datetime format to a date format suitable for use with JS
    date pickers
    """
    converted = format
    replacements = {
        '%Y': 'yy',
        '%m': 'mm',
        '%d': 'dd',
        '%H:%M': '',
    }
    for search, replace in replacements.iteritems():
        converted = converted.replace(search, replace)
    return converted.strip()

def datetime_format_to_js_time_format(format):
    """
    Convert a Python datetime format to a time format suitable for use with JS
    date pickers
    """
    converted = format
    replacements = {
        '%Y': '',
        '%m': '',
        '%d': '',
        '%H': 'HH',
        '%M': 'mm',
    }
    for search, replace in replacements.iteritems():
        converted = converted.replace(search, replace)

    converted = re.sub('[-/][^%]', '', converted)

    return converted.strip()

def add_js_formats(widget):
    """
    Set data attributes for date and time format on a widget
    """
    attrs = {
        'data-dateFormat': datetime_format_to_js_date_format(
            widget.format),
        'data-timeFormat': datetime_format_to_js_time_format(
            widget.format)
    }
    widget.attrs.update(attrs)

class DatePickerInput(forms.DateInput):
    """
    DatePicker input that uses the jQuery UI datepicker.  Data attributes are
    used to pass the date format to the JS
    """
    def __init__(self, *args, **kwargs):
        super(DatePickerInput, self).__init__(*args, **kwargs)
        add_js_formats(self)

class DateTimePickerInput(forms.DateTimeInput):
    # Build a widget which uses the locale datetime format but without seconds.
    # We also use data attributes to pass these formats to the JS datepicker.

    def __init__(self, *args, **kwargs):
        include_seconds = kwargs.pop('include_seconds', False)
        super(DateTimePickerInput, self).__init__(*args, **kwargs)

        if not include_seconds:
            self.format = re.sub(':?%S', '', self.format)
        add_js_formats(self)

class AdvancedSelect(forms.Select):
    """
    Customised Select widget that allows a list of disabled values to be passed
    to the constructor.  Django's default Select widget doesn't allow this so
    we have to override the render_option method and add a section that checks
    for whether the widget is disabled.
    """

    def __init__(self, attrs=None, choices=(), disabled_values=()):
        self.disabled_values = set(force_text(v) for v in disabled_values)
        super(AdvancedSelect, self).__init__(attrs, choices)

    def render_option(self, selected_choices, option_value, option_label):
        option_value = force_text(option_value)
        if option_value in self.disabled_values:
            selected_html = mark_safe(' disabled="disabled"')
        elif option_value in selected_choices:
            selected_html = mark_safe(' selected="selected"')
            if not self.allow_multiple_selected:
                # Only allow for a single selection.
                selected_choices.remove(option_value)
        else:
            selected_html = ''
        return format_html(u'<option value="{0}"{1}>{2}</option>',
                           option_value,
                           selected_html,
                           force_text(option_label))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

import re

def format_outcome(outcome):
    return 'x' if outcome == 'passed' else ' '

def format_title(title, patterns):
    return _remove_patterns(
        patterns=patterns,
        statement=title
    ).replace('_', ' ').strip()

def format_class_name(class_name, patterns):
    formatted = ''

    class_name = _remove_patterns(patterns, class_name)

    for letter in class_name:
        if letter.isupper():
            formatted += ' '

        formatted += letter

    return formatted.strip()

def format_module_name(module_name, patterns):
    return format_title(
        _remove_patterns(patterns, module_name),
        patterns
    ).replace('/', '.')

def _remove_patterns(patterns, statement):
    for glob_pattern in patterns:
        pattern = glob_pattern.replace('*', '')

        if glob_pattern.startswith('*'):
            pattern = '{0}$'.format(pattern)
            statement = re.sub(pattern, '', statement)

        elif glob_pattern.endswith('*'):
            pattern = '^{0}'.format(pattern)
            statement = re.sub(pattern, '', statement)

        elif '*' in glob_pattern:
            infix_patterns = glob_pattern.split('*', 2)
            infix_patterns[0] = '{}*'.format(infix_patterns[0])
            infix_patterns[1] = '*{}'.format(infix_patterns[1])
            statement = _remove_patterns(infix_patterns, statement)

        else:
            pattern = '^{0}'.format(pattern)
            statement = re.sub(pattern, '', statement)

    return statement
<commit_msg>Remove unecessary _remove_pattern call<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

import re

def format_outcome(outcome):
    return 'x' if outcome == 'passed' else ' '

def format_title(title, patterns):
    return _remove_patterns(title, patterns).replace('_', ' ').strip()

def format_class_name(class_name, patterns):
    formatted = ''

    class_name = _remove_patterns(class_name, patterns)

    for letter in class_name:
        if letter.isupper():
            formatted += ' '

        formatted += letter

    return formatted.strip()

def format_module_name(module_name, patterns):
    return format_title(module_name, patterns).replace('/', '.')

def _remove_patterns(statement, patterns):
    for glob_pattern in patterns:
        pattern = glob_pattern.replace('*', '')

        if glob_pattern.startswith('*'):
            pattern = '{0}$'.format(pattern)
            statement = re.sub(pattern, '', statement)

        elif glob_pattern.endswith('*'):
            pattern = '^{0}'.format(pattern)
            statement = re.sub(pattern, '', statement)

        elif '*' in glob_pattern:
            infix_patterns = glob_pattern.split('*', 2)
            infix_patterns[0] = '{}*'.format(infix_patterns[0])
            infix_patterns[1] = '*{}'.format(infix_patterns[1])
            statement = _remove_patterns(statement, infix_patterns)

        else:
            pattern = '^{0}'.format(pattern)
            statement = re.sub(pattern, '', statement)

    return statement
<|endoftext|>


<commit_before>from __future__ import unicode_literals
import json

import boto
import sure  # noqa
from nose.tools import assert_raises

from moto import mock_cloudformation
from moto.cloudformation.exceptions import ValidationError

dummy_template = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Stack 1",
    "Resources": {},
}

dummy_template2 = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Stack 2",
    "Resources": {},
}

dummy_template_json = json.dumps(dummy_template)
dummy_template_json2 = json.dumps(dummy_template2)

@mock_cloudformation
def test_create_stack():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks()[0]
    stack.stack_name.should.equal('test_stack')
    stack.get_template().should.equal(dummy_template)

@mock_cloudformation
def test_describe_stack_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack.stack_name.should.equal('test_stack')

@mock_cloudformation
def test_describe_stack_by_stack_id():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack_by_id = conn.describe_stacks(stack.stack_id)[0]
    stack_by_id.stack_id.should.equal(stack.stack_id)
    stack_by_id.stack_name.should.equal("test_stack")

@mock_cloudformation
def test_describe_deleted_stack():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack_id = stack.stack_id
    conn.delete_stack(stack.stack_id)
    stack_by_id = conn.describe_stacks(stack_id)[0]
    stack_by_id.stack_id.should.equal(stack.stack_id)
    stack_by_id.stack_name.should.equal("test_stack")
    stack_by_id.stack_status.should.equal("DELETE_COMPLETE")

@mock_cloudformation
def test_get_template_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    template = conn.get_template("test_stack")
    template.should.equal(dummy_template)

@mock_cloudformation
def test_list_stacks():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )
    conn.create_stack(
        "test_stack2",
        template_body=dummy_template_json,
    )

    stacks = conn.list_stacks()
    stacks.should.have.length_of(2)
    stacks[0].template_description.should.equal("Stack 1")

@mock_cloudformation
def test_delete_stack_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    conn.list_stacks().should.have.length_of(1)
    conn.delete_stack("test_stack")
    conn.list_stacks().should.have.length_of(0)

@mock_cloudformation
def test_delete_stack_by_id():
    conn = boto.connect_cloudformation()
    stack_id = conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    conn.list_stacks().should.have.length_of(1)
    conn.delete_stack(stack_id)
    conn.list_stacks().should.have.length_of(0)
    with assert_raises(ValidationError) as ve:
        conn.describe_stacks("test_stack")

    ve.exception.code.should.equal('ValidationError')
    ve.exception.status.should.equal(400)
    ve.exception.message.should.contain('test_stack')
    conn.describe_stacks(stack_id).should.have.length_of(1)

@mock_cloudformation
def test_bad_describe_stack():
    conn = boto.connect_cloudformation()
    with assert_raises(ValidationError) as ve:
        conn.describe_stacks("bad_stack")

    ve.exception.code.should.equal('ValidationError')
    ve.exception.status.should.equal(400)
    ve.exception.message.should.contain('bad_stack')

# @mock_cloudformation
# def test_update_stack():
#     conn = boto.connect_cloudformation()
#     conn.create_stack(
#         "test_stack",
#         template_body=dummy_template_json,
#     )

#     conn.update_stack("test_stack", dummy_template_json2)

#     stack = conn.describe_stacks()[0]
#     stack.get_template().should.equal(dummy_template2)
<commit_msg>python 2.6 assert_raises<commit_after>from __future__ import unicode_literals
import json
import boto
import sure  # noqa
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises

from moto import mock_cloudformation
from moto.cloudformation.exceptions import ValidationError

dummy_template = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Stack 1",
    "Resources": {},
}

dummy_template2 = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Stack 2",
    "Resources": {},
}

dummy_template_json = json.dumps(dummy_template)
dummy_template_json2 = json.dumps(dummy_template2)

@mock_cloudformation
def test_create_stack():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks()[0]
    stack.stack_name.should.equal('test_stack')
    stack.get_template().should.equal(dummy_template)

@mock_cloudformation
def test_describe_stack_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack.stack_name.should.equal('test_stack')

@mock_cloudformation
def test_describe_stack_by_stack_id():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack_by_id = conn.describe_stacks(stack.stack_id)[0]
    stack_by_id.stack_id.should.equal(stack.stack_id)
    stack_by_id.stack_name.should.equal("test_stack")

@mock_cloudformation
def test_describe_deleted_stack():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack_id = stack.stack_id
    conn.delete_stack(stack.stack_id)
    stack_by_id = conn.describe_stacks(stack_id)[0]
    stack_by_id.stack_id.should.equal(stack.stack_id)
    stack_by_id.stack_name.should.equal("test_stack")
    stack_by_id.stack_status.should.equal("DELETE_COMPLETE")

@mock_cloudformation
def test_get_template_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    template = conn.get_template("test_stack")
    template.should.equal(dummy_template)

@mock_cloudformation
def test_list_stacks():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )
    conn.create_stack(
        "test_stack2",
        template_body=dummy_template_json,
    )

    stacks = conn.list_stacks()
    stacks.should.have.length_of(2)
    stacks[0].template_description.should.equal("Stack 1")

@mock_cloudformation
def test_delete_stack_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    conn.list_stacks().should.have.length_of(1)
    conn.delete_stack("test_stack")
    conn.list_stacks().should.have.length_of(0)

@mock_cloudformation
def test_delete_stack_by_id():
    conn = boto.connect_cloudformation()
    stack_id = conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    conn.list_stacks().should.have.length_of(1)
    conn.delete_stack(stack_id)
    conn.list_stacks().should.have.length_of(0)
    with assert_raises(ValidationError) as ve:
        conn.describe_stacks("test_stack")

    ve.exception.code.should.equal('ValidationError')
    ve.exception.status.should.equal(400)
    ve.exception.message.should.contain('test_stack')
    conn.describe_stacks(stack_id).should.have.length_of(1)

@mock_cloudformation
def test_bad_describe_stack():
    conn = boto.connect_cloudformation()
    with assert_raises(ValidationError) as ve:
        conn.describe_stacks("bad_stack")

    ve.exception.code.should.equal('ValidationError')
    ve.exception.status.should.equal(400)
    ve.exception.message.should.contain('bad_stack')

# @mock_cloudformation
# def test_update_stack():
#     conn = boto.connect_cloudformation()
#     conn.create_stack(
#         "test_stack",
#         template_body=dummy_template_json,
#     )

#     conn.update_stack("test_stack", dummy_template_json2)

#     stack = conn.describe_stacks()[0]
#     stack.get_template().should.equal(dummy_template2)
<|endoftext|>


<commit_before>import time
import threading
import matplotlib.pyplot as plt

global data
data = []

def dataInput():
    start = time.time()
    while True:
        time.sleep(.001)
        data.append(time.time() - start)

def plotter():
    while True:
        start = time.time()
        pd = data.copy()  #had to copy data because data changing mid-scatter call, #could also just note index
        plt.scatter(pd, range(len(pd)))
        plt.pause(.1)
        print(time.time() - start)
        print('')

thread1 = threading.Thread(target = dataInput)
thread2 = threading.Thread(target = plotter)

thread1.start()
thread2.start()
<commit_msg>updated io<commit_after>import time
import threading
import matplotlib.pyplot as plt
import math

global data
data = []

def dataInput():
    start = time.time()
    while True:
        time.sleep(.03)
        data.append(math.sin(time.time() - start)* (time.time() - start))

def plotter():
    while True:
        start = time.time()
        length = len(data)
        plt.scatter(range(length), data[0:length])
        plt.pause(.1)
        print(time.time() - start)
        print('')

thread1 = threading.Thread(target = dataInput)
thread2 = threading.Thread(target = plotter)

thread1.start()
thread2.start()
<|endoftext|>


<commit_before>#
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from migrate.changeset.constraint import UniqueConstraint
import sqlalchemy

from ceilometer.storage.sqlalchemy import models

def upgrade(migrate_engine):
    meta = sqlalchemy.MetaData(bind=migrate_engine)

    event = sqlalchemy.Table('event', meta, autoload=True)
    message_id = sqlalchemy.Column('message_id', sqlalchemy.String(50))
    event.create_column(message_id)

    cons = UniqueConstraint('message_id', table=event)
    cons.create()

    index = sqlalchemy.Index('idx_event_message_id', models.Event.message_id)
    index.create(bind=migrate_engine)

    # Populate the new column ...
    trait = sqlalchemy.Table('trait', meta, autoload=True)
    unique_name = sqlalchemy.Table('unique_name', meta, autoload=True)
    join = trait.join(unique_name, unique_name.c.id == trait.c.name_id)
    traits = sqlalchemy.select([trait.c.event_id, trait.c.t_string],
                               whereclause=(unique_name.c.key == 'message_id'),
                               from_obj=join)

    for event_id, value in traits.execute():
        (event.update().where(event.c.id == event_id).values(message_id=value).
         execute())

    # Leave the Trait, makes the rollback easier and won't really hurt anyone.

def downgrade(migrate_engine):
    meta = sqlalchemy.MetaData(bind=migrate_engine)
    event = sqlalchemy.Table('event', meta, autoload=True)
    message_id = sqlalchemy.Column('message_id', sqlalchemy.String(50))
    cons = UniqueConstraint('message_id', table=event)
    cons.drop()
    index = sqlalchemy.Index('idx_event_message_id', models.Event.message_id)
    index.drop(bind=migrate_engine)
    event.drop_column(message_id)
<commit_msg>remove reference to model in migration<commit_after>#
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from migrate.changeset.constraint import UniqueConstraint
import sqlalchemy

def upgrade(migrate_engine):
    meta = sqlalchemy.MetaData(bind=migrate_engine)

    event = sqlalchemy.Table('event', meta, autoload=True)
    message_id = sqlalchemy.Column('message_id', sqlalchemy.String(50))
    event.create_column(message_id)

    cons = UniqueConstraint('message_id', table=event)
    cons.create()

    index = sqlalchemy.Index('idx_event_message_id', event.c.message_id)
    index.create(bind=migrate_engine)

    # Populate the new column ...
    trait = sqlalchemy.Table('trait', meta, autoload=True)
    unique_name = sqlalchemy.Table('unique_name', meta, autoload=True)
    join = trait.join(unique_name, unique_name.c.id == trait.c.name_id)
    traits = sqlalchemy.select([trait.c.event_id, trait.c.t_string],
                               whereclause=(unique_name.c.key == 'message_id'),
                               from_obj=join)

    for event_id, value in traits.execute():
        (event.update().where(event.c.id == event_id).values(message_id=value).
         execute())

    # Leave the Trait, makes the rollback easier and won't really hurt anyone.

def downgrade(migrate_engine):
    meta = sqlalchemy.MetaData(bind=migrate_engine)
    event = sqlalchemy.Table('event', meta, autoload=True)
    message_id = sqlalchemy.Column('message_id', sqlalchemy.String(50))
    cons = UniqueConstraint('message_id', table=event)
    cons.drop()
    index = sqlalchemy.Index('idx_event_message_id', event.c.message_id)
    index.drop(bind=migrate_engine)
    event.drop_column(message_id)
<|endoftext|>