use ogr2ogr for clip around bound use mapshaper for clip around shapefile polygons
14899
function getCmd(program, opt) {
            var cmd,
                expr;

            if(program==='ogr2ogr') {

                if(opt==='where') {
                    expr = [
                        '-where ',
                        "\"", specs.key, " IN ",
                        "('", specs.val, "')\" ",
                        '-clipsrc ',
                        specs.bounds.join(' ')
                    ].join('');
                }
                else if(opt==='clipsrc') {
                    expr = [
                        '-clipsrc ',
                        specs.bounds.join(' ')
                    ].join('');
                }
                else  expr = '';

                cmd = [
                    "ogr2ogr -f GeoJSON",
                    expr,
                    common.geojsonDir + common.tn(r, s.name, v.name, 'geo.json'),
                    common.wgetDir + common.srcPrefix + common.bn(r, v.src, 'shp')
                ].join(' ');

            }
            else if(program==='mapshaper') {
                cmd = [
                    mapshaper,
                    common.wgetDir + common.srcPrefix + common.bn(r, v.src, 'shp'),
                    "encoding=utf8",
                    "-clip",
                    common.wgetDir + common.tn(r, s.name, specs.src, 'shp'),
                    "-filter remove-empty",
                    "-o",
                    common.geojsonDir + common.tn(r, s.name, v.name, 'geo.json')
               ].join(' ');
            }

            return cmd;
        }
947588
def clip_boxes(boxes, shape):
    
    orig_shape = boxes.shape
    boxes = boxes.reshape([-1, 4])
    h, w = shape
    boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0)
    boxes[:, 2] = np.minimum(boxes[:, 2], w)
    boxes[:, 3] = np.minimum(boxes[:, 3], h)
    return boxes.reshape(orig_shape)
644878
def _get_bounds(mapper, values):
        

        array = np.array([mapper.get(x) for x in values])
        return array[:, 0], array[:, 1]
975748
@Override
    protected void drawWithoutTransforms(final Context2D context, double alpha, final BoundingBox bounds)
    {
        if ((context.isSelection()) && (false == isListening()))
        {
            return;
        }
        alpha = alpha * getAttributes().getAlpha();

        if (alpha <= 0)
        {
            return;
        }
        BoundingBox bbox = getStorageBounds();

        if (null == bbox)
        {
            bbox = bounds;
        }
        final NFastArrayList<M> list = getChildNodes(bbox);

        final int size = list.size();

        final IPathClipper clip = getPathClipper();

        if ((null != clip) && (clip.isActive()))
        {
            context.save();

            clip.clip(context);

            for (int i = 0; i < size; i++)
            {
                list.get(i).drawWithTransforms(context, alpha, bbox);
            }
            context.restore();
        }
        else
        {
            for (int i = 0; i < size; i++)
            {
                list.get(i).drawWithTransforms(context, alpha, bbox);
            }
        }
    }
561438
def shapefile(self, file):
         
        
        driver = ogr.GetDriverByName('ESRI Shapefile')
        dataset = driver.Open(file)
        if dataset is not None:
            # from Layer
            layer = dataset.GetLayer()
            spatialRef = layer.GetSpatialRef()
            # from Geometry
            feature = layer.GetNextFeature()
            geom = feature.GetGeometryRef()
            spatialRef = geom.GetSpatialReference()
            
            #WGS84
            outSpatialRef = osr.SpatialReference()
            outSpatialRef.ImportFromEPSG(4326)
    
            coordTrans = osr.CoordinateTransformation(spatialRef, outSpatialRef)
    
            env = geom.GetEnvelope()
            xmin = env[0]
            ymin = env[2]
            xmax = env[1]
            ymax = env[3]
    
            pointMAX = ogr.Geometry(ogr.wkbPoint)
            pointMAX.AddPoint(env[1], env[3])
            pointMAX.Transform(coordTrans)
            
            pointMIN = ogr.Geometry(ogr.wkbPoint)
            pointMIN.AddPoint(env[0], env[2])
            pointMIN.Transform(coordTrans)
    
    
            self.bbox = str(pointMIN.GetPoint()[0])+','+str(pointMIN.GetPoint()[1])+','+str(pointMAX.GetPoint()[0])+','+str(pointMAX.GetPoint()[1])
            self.query = None
        else:
            exit(" shapefile not found. Please verify your path to the shapefile")
771310
def bounding_box(lat, lng, zoom)
      top, left = MapKit.shift_latlng(lat, lng, @shift_x - @peak_x, @shift_y - @peak_y, zoom)
      bottom, right = MapKit.shift_latlng(top, left, @width, @height, zoom)
      MapKit::BoundingBox.new(top, left, bottom, right, zoom)
    end
1036206
function (otherCsg, csg) {
  if ((otherCsg.polygons.length === 0) || (csg.polygons.length === 0)) {
    return false
  } else {
    let mybounds = bounds(otherCsg)
    let otherbounds = bounds(csg)
    if (mybounds[1].x < otherbounds[0].x) return false
    if (mybounds[0].x > otherbounds[1].x) return false
    if (mybounds[1].y < otherbounds[0].y) return false
    if (mybounds[0].y > otherbounds[1].y) return false
    if (mybounds[1].z < otherbounds[0].z) return false
    if (mybounds[0].z > otherbounds[1].z) return false
    return true
  }
}
480982
def raster_to_shape(raster):
    """"""
    left = raster.bounds.left
    right = raster.bounds.right
    top = raster.bounds.top
    bottom = raster.bounds.bottom

    top_left = (left, top)
    top_right = (right, top)
    bottom_left = (left, bottom)
    bottom_right = (right, bottom)

    return Polygon((
        top_left, top_right, bottom_right, bottom_left, top_left,
    ))
489206
def stack_clip(s_orig, extent, out_stack_fn=None, copy=True, save=False):
    
    #Should check for valid extent

    #This is not memory efficient, but is much simpler
    #To be safe, if we are saving out, create a copy to avoid overwriting
    if copy or save:
        from copy import deepcopy
        print("Copying original DEMStack")
        s = deepcopy(s_orig)
    else:
        #Want to be very careful here, as we could overwrite the original file
        s = s_orig

    from pygeotools.lib import geolib
    gt = s.gt
    s_shape = s.ma_stack.shape[1:3]

    #Compute pixel bounds for input extent
    min_x_px, max_y_px = geolib.mapToPixel(extent[0], extent[1], gt)
    max_x_px, min_y_px = geolib.mapToPixel(extent[2], extent[3], gt)

    #Clip to stack extent and round to whole integers
    min_x_px = int(max(0, min_x_px)+0.5)
    max_x_px = int(min(s_shape[1], max_x_px)+0.5)
    min_y_px = int(max(0, min_y_px)+0.5)
    max_y_px = int(min(s_shape[0], max_y_px)+0.5)
  
    #Clip the stack
    x_slice = slice(min_x_px,max_x_px)
    y_slice = slice(min_y_px,max_y_px)
    s.ma_stack = s.ma_stack[:, y_slice, x_slice]

    #Now update geospatial info
    #This returns the pixel center in map coordinates
    #Want to remove 0.5 px offset for upper left corner in gt
    out_ul = geolib.pixelToMap(min_x_px - 0.5, min_y_px - 0.5, gt)
   
    #Update stack geotransform
    s.gt[0] = out_ul[0]
    s.gt[3] = out_ul[1]
    #Update new stack extent
    s.get_extent()

    #Check for and discard emtpy arrays 
    #Might be faster to reshape then np.ma.count(s.ma_stack, axis=1)
    count_list = np.array([i.count() for i in s.ma_stack])
    idx = count_list > 0 
    
    #Output subset with valid data in next extent
    #fn_list, source, error, error_dict_list, date_list, date_list_o
    #Note: no need to copy again
    s_sub = get_stack_subset(s, idx, out_stack_fn=out_stack_fn, copy=False, save=False) 

    print("Orig filename:", s_orig.stack_fn)
    print("Orig extent:", s_orig.extent)
    print("Orig dimensions:", s_orig.ma_stack.shape)
    print("Input extent:", extent)
    print("New filename:", s_sub.stack_fn)
    print("New extent:", s_sub.extent)
    print("New dimensions:", s_sub.ma_stack.shape)
    
    if save:
        if os.path.abspath(s_orig.stack_fn) == os.path.abspath(s_sub.stack_fn):
            print("Original stack would be overwritten!")
            print("Skipping save")
        else:
            s_sub.save = True
            s_sub.savestack()

    #The following should be unchanged by clip - it is more efficient to clip thes, but easier to regenerate
    #if s.stats:
    #stack_count, stack_mean, stack_min, stack_max, stack_std
    #s.stack_min = s.stack_min[y_slice, x_slice]
    #if s.datestack:
    #dt_ptp, dt_min, dt_max, dt_center
    #if s.med:
    #stack_med
    #if s.trend:
    #trend, intercept, detrended_std
    #Recompute stats/etc

    return s_sub
26717
function(polygons, bbox) {
        var clip = this.getClippingPolygon(bbox);
        for (var i = 0; i < polygons.length; i++) {
            if (this.bboxIntersectsPolygonWithHoles(polygons[i], bbox))
                return true;
        }
        return false;
    }
295050
def _get_shaperecords(self, num_fill_bits,
                          num_line_bits, shape_number):
        """"""
        shape_records = []
        bc = BitConsumer(self._src)

        while True:
            type_flag = bc.u_get(1)
            if type_flag:
                # edge record
                straight_flag = bc.u_get(1)
                num_bits = bc.u_get(4)
                if straight_flag:
                    record = _make_object('StraightEdgeRecord')
                    record.TypeFlag = 1
                    record.StraightFlag = 1
                    record.NumBits = num_bits
                    record.GeneralLineFlag = general_line_flag = bc.u_get(1)
                    if general_line_flag:
                        record.DeltaX = bc.s_get(num_bits + 2)
                        record.DeltaY = bc.s_get(num_bits + 2)
                    else:
                        record.VertLineFlag = vert_line_flag = bc.s_get(1)
                        if vert_line_flag:
                            record.DeltaY = bc.s_get(num_bits + 2)
                        else:
                            record.DeltaX = bc.s_get(num_bits + 2)
                else:
                    record = _make_object('CurvedEdgeRecord')
                    record.TypeFlag = 1
                    record.StraightFlag = 0
                    record.NumBits = num_bits
                    record.ControlDeltaX = bc.s_get(num_bits + 2)
                    record.ControlDeltaY = bc.s_get(num_bits + 2)
                    record.AnchorDeltaX = bc.s_get(num_bits + 2)
                    record.AnchorDeltaY = bc.s_get(num_bits + 2)

            else:
                # non edge record
                record = _make_object('StyleChangeRecord')
                record.TypeFlag = 0

                five_bits = [bc.u_get(1) for _ in range(5)]
                if not any(five_bits):
                    # the five bits are zero, this is an EndShapeRecord
                    break

                # we're not done, store the proper flags
                (record.StateNewStyles, record.StateLineStyle,
                    record.StateFillStyle1, record.StateFillStyle0,
                    record.StateMoveTo) = five_bits

                if record.StateMoveTo:
                    record.MoveBits = move_bits = bc.u_get(5)
                    record.MoveDeltaX = bc.s_get(move_bits)
                    record.MoveDeltaY = bc.s_get(move_bits)
                if record.StateFillStyle0:
                    record.FillStyle0 = bc.u_get(num_fill_bits)
                if record.StateFillStyle1:
                    record.FillStyle1 = bc.u_get(num_fill_bits)
                if record.StateLineStyle:
                    record.LineStyle = bc.u_get(num_line_bits)

                if record.StateNewStyles:
                    record.FillStyles = self._get_struct_fillstylearray(
                        shape_number)
                    record.LineStyles = self._get_struct_linestylearray(
                        shape_number)
                    # these two not only belong to the record, but also
                    # modifies the number of bits read in the future
                    # if shape number bigs enough (didn't find this in the
                    # spec, but works for now, maybe '2' is not the limit...)
                    if shape_number > 2:
                        record.NumFillBits = num_fill_bits = bc.u_get(4)
                        record.NumLineBits = num_line_bits = bc.u_get(4)
                    else:
                        record.NumFillBits = bc.u_get(4)
                        record.NumLineBits = bc.u_get(4)

                    # reset the BC here, as the structures just read work at
                    # byte level
                    bc = BitConsumer(self._src)

            shape_records.append(record)
        return shape_records
473213
def polygon_bounds(points):
    ''''''
    (minx, miny) = (points[0][0], points[0][1])
    (maxx, maxy) = (minx, miny)
    for p in points:
        minx = min(minx, p[0])
        maxx = max(maxx, p[0])
        miny = min(miny, p[1])
        maxy = max(maxy, p[1])
    return (minx, miny, maxx-minx, maxy-miny)
1370217
def _global_tiles_from_bounds(tp, bounds, zoom):
    """"""
    seen = set()

    # clip to tilepyramid top and bottom bounds
    left, right = bounds.left, bounds.right
    top = tp.top if bounds.top > tp.top else bounds.top
    bottom = tp.bottom if bounds.bottom < tp.bottom else bounds.bottom

    if left >= tp.left and right <= tp.right:
        for tile in _tiles_from_cleaned_bounds(tp, bounds, zoom):
            yield tile

    # bounds overlap on the Western side with antimeridian
    if left < tp.left:
        for tile in chain(
            # tiles west of antimeridian
            _tiles_from_cleaned_bounds(
                tp,
                Bounds(left + (tp.right - tp.left), bottom, tp.right, top),
                zoom
            ),
            # tiles east of antimeridian
            _tiles_from_cleaned_bounds(
                tp, Bounds(tp.left, bottom, right, top), zoom
            )
        ):
            # make output tiles unique
            if tile.id not in seen:
                seen.add(tile.id)
                yield tile

    # bounds overlap on the Eastern side with antimeridian
    if right > tp.right:
        for tile in chain(
            # tiles west of antimeridian
            _tiles_from_cleaned_bounds(
                tp, Bounds(left, bottom, tp.right, top), zoom
            ),
            # tiles east of antimeridian
            _tiles_from_cleaned_bounds(
                tp,
                Bounds(tp.left, bottom, right - (tp.right - tp.left), top),
                zoom
            )
        ):
            # make output tiles unique
            if tile.id not in seen:
                seen.add(tile.id)
                yield tile
91221
def features_keep_using_features(obj, bounds):
    
    # Build an R-tree index of bound features and their shapes.
    bounds_shapes = [
        (feature, shapely.geometry.shape(feature['geometry'])) 
        for feature in tqdm(bounds['features'])
        if feature['geometry'] is not None
      ]
    index = rtree.index.Index()
    for i in tqdm(range(len(bounds_shapes))):
        (feature, shape) = bounds_shapes[i]
        index.insert(i, shape.bounds)

    features_keep = []
    for feature in tqdm(obj['features']):
        if 'geometry' in feature and 'coordinates' in feature['geometry']:
            coordinates = feature['geometry']['coordinates']
            if any([
                shape.contains(shapely.geometry.Point(lon, lat))
                for (lon, lat) in coordinates
                for (feature, shape) in [bounds_shapes[i]
                for i in index.nearest((lon,lat,lon,lat), 1)]
              ]):
                features_keep.append(feature)
                continue
    obj['features'] = features_keep
    return obj
148942
protected void selectBoundaryCorners() {
		List<Point2D_F64> layout = detector.getLayout();

		Polygon2D_F64 hull = new Polygon2D_F64();
		UtilPolygons2D_F64.convexHull(layout,hull);
		UtilPolygons2D_F64.removeAlmostParallel(hull,0.02);

		boundaryIndexes = new int[hull.size()];
		for (int i = 0; i < hull.size(); i++) {
			Point2D_F64 h = hull.get(i);
			boolean matched = false;
			for (int j = 0; j < layout.size(); j++) {
				if( h.isIdentical(layout.get(j),1e-6)) {
					matched = true;
					boundaryIndexes[i] = j;
					break;
				}
			}
			if( !matched )
				throw new RuntimeException("Bug!");
		}

	}
1106798
public void expandBoundingBox(BoundingBox boundingBox) {

        switch (shapeType) {

            case LAT_LNG:
                expandBoundingBox(boundingBox, (LatLng) shape);
                break;
            case MARKER_OPTIONS:
                expandBoundingBox(boundingBox,
                        ((MarkerOptions) shape).getPosition());
                break;
            case POLYLINE_OPTIONS:
                expandBoundingBox(boundingBox,
                        ((PolylineOptions) shape).getPoints());
                break;
            case POLYGON_OPTIONS:
                expandBoundingBox(boundingBox, ((PolygonOptions) shape).getPoints());
                break;
            case MULTI_LAT_LNG:
                expandBoundingBox(boundingBox, ((MultiLatLng) shape).getLatLngs());
                break;
            case MULTI_POLYLINE_OPTIONS:
                MultiPolylineOptions multiPolylineOptions = (MultiPolylineOptions) shape;
                for (PolylineOptions polylineOptions : multiPolylineOptions
                        .getPolylineOptions()) {
                    expandBoundingBox(boundingBox, polylineOptions.getPoints());
                }
                break;
            case MULTI_POLYGON_OPTIONS:
                MultiPolygonOptions multiPolygonOptions = (MultiPolygonOptions) shape;
                for (PolygonOptions polygonOptions : multiPolygonOptions
                        .getPolygonOptions()) {
                    expandBoundingBox(boundingBox, polygonOptions.getPoints());
                }
                break;
            case MARKER:
                expandBoundingBox(boundingBox, ((Marker) shape).getPosition());
                break;
            case POLYLINE:
                expandBoundingBox(boundingBox, ((Polyline) shape).getPoints());
                break;
            case POLYGON:
                expandBoundingBox(boundingBox, ((Polygon) shape).getPoints());
                break;
            case MULTI_MARKER:
                expandBoundingBoxMarkers(boundingBox,
                        ((MultiMarker) shape).getMarkers());
                break;
            case MULTI_POLYLINE:
                MultiPolyline multiPolyline = (MultiPolyline) shape;
                for (Polyline polyline : multiPolyline.getPolylines()) {
                    expandBoundingBox(boundingBox, polyline.getPoints());
                }
                break;
            case MULTI_POLYGON:
                MultiPolygon multiPolygon = (MultiPolygon) shape;
                for (Polygon polygon : multiPolygon.getPolygons()) {
                    expandBoundingBox(boundingBox, polygon.getPoints());
                }
                break;
            case POLYLINE_MARKERS:
                expandBoundingBoxMarkers(boundingBox,
                        ((PolylineMarkers) shape).getMarkers());
                break;
            case POLYGON_MARKERS:
                expandBoundingBoxMarkers(boundingBox,
                        ((PolygonMarkers) shape).getMarkers());
                break;
            case MULTI_POLYLINE_MARKERS:
                MultiPolylineMarkers multiPolylineMarkers = (MultiPolylineMarkers) shape;
                for (PolylineMarkers polylineMarkers : multiPolylineMarkers
                        .getPolylineMarkers()) {
                    expandBoundingBoxMarkers(boundingBox,
                            polylineMarkers.getMarkers());
                }
                break;
            case MULTI_POLYGON_MARKERS:
                MultiPolygonMarkers multiPolygonMarkers = (MultiPolygonMarkers) shape;
                for (PolygonMarkers polygonMarkers : multiPolygonMarkers
                        .getPolygonMarkers()) {
                    expandBoundingBoxMarkers(boundingBox,
                            polygonMarkers.getMarkers());
                }
                break;
            case COLLECTION:
                @SuppressWarnings("unchecked")
                List<GoogleMapShape> shapeList = (List<GoogleMapShape>) shape;
                for (GoogleMapShape shapeListItem : shapeList) {
                    shapeListItem.expandBoundingBox(boundingBox);
                }
                break;
        }

    }
794650
def _union_in_blocks(contours, block_size):
    

    n_contours = len(contours)
    for i in range(0, n_contours, block_size):
        j = min(i + block_size, n_contours)

        inners = []
        for c in contours[i:j]:
            p = _contour_to_poly(c)
            if p.type == 'Polygon':
                inners.append(p)
            elif p.type == 'MultiPolygon':
                inners.extend(p.geoms)
        holes = unary_union(inners)
        assert holes.is_valid

        yield holes