Longitude/Lagitude overlap (4 images)
340460
def _cas_4(self):
        '''  '''

        lonc_left = self._format_lon(self.lonm)
        lonc_right = self._format_lon(self.lonM)
        latc_top = self._format_lat(self.latM)
        latc_bot = self._format_lat(self.latm)

        img_name_00 = self._format_name_map(lonc_left, latc_top)
        img_00 = BinaryTable(img_name_00, self.path_pdsfiles)
        X_00, Y_00, Z_00 = img_00.extract_grid(self.lonm,
                                               float(
                                                   img_00.EASTERNMOST_LONGITUDE),
                                               float(img_00.MINIMUM_LATITUDE),
                                               self.latM)

        img_name_01 = self._format_name_map(lonc_right, latc_top)
        img_01 = BinaryTable(img_name_01, self.path_pdsfiles)
        X_01, Y_01, Z_01 = img_01.extract_grid(float(img_01.WESTERNMOST_LONGITUDE),
                                               self.lonM,
                                               float(img_01.MINIMUM_LATITUDE),
                                               self.latM)

        img_name_10 = self._format_name_map(lonc_left, latc_bot)
        img_10 = BinaryTable(img_name_10, self.path_pdsfiles)
        X_10, Y_10, Z_10 = img_10.extract_grid(self.lonm,
                                               float(
                                                   img_10.EASTERNMOST_LONGITUDE),
                                               self.latm,
                                               float(img_10.MAXIMUM_LATITUDE))

        img_name_11 = self._format_name_map(lonc_right, latc_bot)
        img_11 = BinaryTable(img_name_11, self.path_pdsfiles)
        X_11, Y_11, Z_11 = img_11.extract_grid(float(img_11.WESTERNMOST_LONGITUDE),
                                               self.lonM,
                                               self.latm,
                                               float(img_11.MAXIMUM_LATITUDE))

        X_new_top = np.hstack((X_00, X_01))
        X_new_bot = np.hstack((X_10, X_11))
        X_new = np.vstack((X_new_top, X_new_bot))

        Y_new_top = np.hstack((Y_00, Y_01))
        Y_new_bot = np.hstack((Y_10, Y_11))
        Y_new = np.vstack((Y_new_top, Y_new_bot))

        Z_new_top = np.hstack((Z_00, Z_01))
        Z_new_bot = np.hstack((Z_10, Z_11))
        Z_new = np.vstack((Z_new_top, Z_new_bot))

        return X_new, Y_new, Z_new
339090
def allSkyCoordinates(nside):
    
    lon,lat = pix2ang(nside, np.arange(0, hp.nside2npix(nside)))
    return lon, lat
325789
def check_overlap(pos, ins, thresh):
    
    ins_pos = ins[0]
    ins_len = ins[2]
    ol = overlap(ins_pos, pos)
    feat_len = pos[1] - pos[0] + 1
#    print float(ol) / float(feat_len)
    if float(ol) / float(feat_len) >= thresh:
        return True
    return False
371880
def overlap(intv1, intv2):
    """"""
    return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))
186008
def image_coordinates(self, point):
        ''''''
        # the dragpos is the top left position in image coordinates
        ret = wx.Point(int(self.dragpos.x + point.x/self.zoom),
                       int(self.dragpos.y + point.y/self.zoom))
        return ret
536671
def convertLatLngToPixelXY(self, lat, lng, level):
        '''
        
        '''
        mapSize = self.getMapDimensionsByZoomLevel(level)

        lat = self.clipValue(lat, self.min_lat, self.max_lat)
        lng = self.clipValue(lng, self.min_lng, self.max_lng)

        x = (lng + 180) / 360
        sinlat = math.sin(lat * math.pi / 180)
        y = 0.5 - math.log((1 + sinlat) / (1 - sinlat)) / (4 * math.pi)

        pixelX = int(self.clipValue(x * mapSize + 0.5, 0, mapSize - 1))
        pixelY = int(self.clipValue(y * mapSize + 0.5, 0, mapSize - 1))
        return (pixelX, pixelY)
299480
private static double[] computeTileEnlargement(double lat, int enlargementInMeter) {
        if (enlargementInMeter == 0) {
            return EPSILON_ZERO;
        }

        double[] epsilons = new double[2];

        epsilons[0] = LatLongUtils.latitudeDistance(enlargementInMeter);
        epsilons[1] = LatLongUtils.longitudeDistance(enlargementInMeter, lat);

        return epsilons;
    }
720806
def reset_coord(self):
        
        (x, y, idx) = self.world2pix(self.init_skycoord.ra,
                                     self.init_skycoord.dec,
                                     usepv=True)
        self.update_pixel_location((x, y), idx)
210358
function init$9() {
        this.no_off = this.no_off || false;
        this.no_rot = this.no_rot || false;

        if (isNaN(this.k0)) {
            this.k0 = 1;
        }
        var sinlat = Math.sin(this.lat0);
        var coslat = Math.cos(this.lat0);
        var con = this.e * sinlat;

        this.bl = Math.sqrt(1 + this.es / (1 - this.es) * Math.pow(coslat, 4));
        this.al = this.a * this.bl * this.k0 * Math.sqrt(1 - this.es) / (1 - con * con);
        var t0 = tsfnz(this.e, this.lat0, sinlat);
        var dl = this.bl / coslat * Math.sqrt((1 - this.es) / (1 - con * con));
        if (dl * dl < 1) {
            dl = 1;
        }
        var fl;
        var gl;
        if (!isNaN(this.longc)) {
            //Central point and azimuth method

            if (this.lat0 >= 0) {
                fl = dl + Math.sqrt(dl * dl - 1);
            }
            else {
                fl = dl - Math.sqrt(dl * dl - 1);
            }
            this.el = fl * Math.pow(t0, this.bl);
            gl = 0.5 * (fl - 1 / fl);
            this.gamma0 = Math.asin(Math.sin(this.alpha) / dl);
            this.long0 = this.longc - Math.asin(gl * Math.tan(this.gamma0)) / this.bl;

        }
        else {
            //2 points method
            var t1 = tsfnz(this.e, this.lat1, Math.sin(this.lat1));
            var t2 = tsfnz(this.e, this.lat2, Math.sin(this.lat2));
            if (this.lat0 >= 0) {
                this.el = (dl + Math.sqrt(dl * dl - 1)) * Math.pow(t0, this.bl);
            }
            else {
                this.el = (dl - Math.sqrt(dl * dl - 1)) * Math.pow(t0, this.bl);
            }
            var hl = Math.pow(t1, this.bl);
            var ll = Math.pow(t2, this.bl);
            fl = this.el / hl;
            gl = 0.5 * (fl - 1 / fl);
            var jl = (this.el * this.el - ll * hl) / (this.el * this.el + ll * hl);
            var pl = (ll - hl) / (ll + hl);
            var dlon12 = adjust_lon(this.long1 - this.long2);
            this.long0 = 0.5 * (this.long1 + this.long2) - Math.atan(jl * Math.tan(0.5 * this.bl * (dlon12)) / pl) / this.bl;
            this.long0 = adjust_lon(this.long0);
            var dlon10 = adjust_lon(this.long1 - this.long0);
            this.gamma0 = Math.atan(Math.sin(this.bl * (dlon10)) / gl);
            this.alpha = Math.asin(dl * Math.sin(this.gamma0));
        }

        if (this.no_off) {
            this.uc = 0;
        }
        else {
            if (this.lat0 >= 0) {
                this.uc = this.al / this.bl * Math.atan2(Math.sqrt(dl * dl - 1), Math.cos(this.alpha));
            }
            else {
                this.uc = -1 * this.al / this.bl * Math.atan2(Math.sqrt(dl * dl - 1), Math.cos(this.alpha));
            }
        }

    }
818531
def count_overlap(self, time, other_object, other_time):
        
        ti = np.where(time == self.times)[0][0]
        ma = np.where(self.masks[ti].ravel() == 1)
        oti = np.where(other_time == other_object.times)[0]
        obj_coords = np.zeros(self.masks[ti].sum(), dtype=[('x', int), ('y', int)])
        other_obj_coords = np.zeros(other_object.masks[oti].sum(), dtype=[('x', int), ('y', int)])
        obj_coords['x'] = self.i[ti].ravel()[ma]
        obj_coords['y'] = self.j[ti].ravel()[ma]
        other_obj_coords['x'] = other_object.i[oti][other_object.masks[oti] == 1]
        other_obj_coords['y'] = other_object.j[oti][other_object.masks[oti] == 1]
        return float(np.intersect1d(obj_coords,
                                    other_obj_coords).size) / np.maximum(self.masks[ti].sum(),
                                                                         other_object.masks[oti].sum())
3799
def overlap_bbox_and_point(bbox, xp, yp):
    """"""
    cx, cy = get_midpoint(bbox)

    dir_x = np.sign(cx-xp)
    dir_y = np.sign(cy-yp)

    if dir_x == -1:
        dx = xp - bbox.xmax
    elif dir_x == 1:
        dx = xp - bbox.xmin
    else:
        dx = 0

    if dir_y == -1:
        dy = yp - bbox.ymax
    elif dir_y == 1:
        dy = yp - bbox.ymin
    else:
        dy = 0
    return dx, dy
218748
def main(args):
    

    v = VerbosityMixin()

    if args:

        if 'clip' in args:
            bounds = convert_to_float_list(args.clip)
        else:
            bounds = None

        if args.subs == 'process':
            verbose = True if args.verbose else False
            force_unzip = True if args.force_unzip else False
            stored = process_image(args.path, args.bands, verbose, args.pansharpen, args.ndvi, force_unzip,
                                   args.ndvigrey, bounds)

            if args.upload:
                u = Uploader(args.key, args.secret, args.region)
                u.run(args.bucket, get_file(stored), stored)

            return ["The output is stored at %s" % stored]

        elif args.subs == 'search':

            try:
                if args.start:
                    args.start = reformat_date(parse(args.start))
                if args.end:
                    args.end = reformat_date(parse(args.end))
                if args.latest > 0:
                    args.limit = 25
                    end = datetime.now()
                    start = end - relativedelta(days=+365)
                    args.end = end.strftime("%Y-%m-%d")
                    args.start = start.strftime("%Y-%m-%d")
            except (TypeError, ValueError):
                return ["Your date format is incorrect. Please try again!", 1]

            s = Search()

            try:
                if args.lat is not None:
                    lat = float(args.lat)
                else:
                    lat = None

                if args.lon is not None:
                    lon = float(args.lon)
                else:
                    lon = None
            except ValueError:
                return ["The latitude and longitude values must be valid numbers", 1]

            address = args.address
            if address and (lat and lon):
                return ["Cannot specify both address and latitude-longitude"]

            result = s.search(paths_rows=args.pathrow,
                              lat=lat,
                              lon=lon,
                              address=address,
                              limit=args.limit,
                              start_date=args.start,
                              end_date=args.end,
                              cloud_max=args.cloud,
                              geojson=args.geojson)

            if 'status' in result:

                if result['status'] == 'SUCCESS':
                    if args.json:
                        return json.dumps(result)

                    if args.latest > 0:
                        datelist = []
                        for i in range(0, result['total_returned']):
                            datelist.append((result['results'][i]['date'], result['results'][i]))

                        datelist.sort(key=lambda tup: tup[0], reverse=True)
                        datelist = datelist[:args.latest]

                        result['results'] = []
                        for i in range(0, len(datelist)):
                            result['results'].append(datelist[i][1])
                            result['total_returned'] = len(datelist)

                    else:
                        v.output('%s items were found' % result['total'], normal=True, arrow=True)

                    if result['total'] > 100:
                        return ['Over 100 results. Please narrow your search', 1]
                    else:
                        v.output(json.dumps(result, sort_keys=True, indent=4), normal=True, color='green')
                    return ['Search completed!']

                elif result['status'] == 'error':
                    return [result['message'], 1]

            if args.geojson:
                return json.dumps(result)

        elif args.subs == 'download':
            d = Downloader(download_dir=args.dest, usgs_user=args.username, usgs_pass=args.password)
            try:
                bands = convert_to_integer_list(args.bands)

                if args.process:
                    if args.pansharpen:
                        bands.append(8)

                    if args.ndvi or args.ndvigrey:
                        bands = [4, 5]

                    if not args.bands:
                        bands = [4, 3, 2]

                files = d.download(args.scenes, bands)

                if args.process:
                    if not args.bands:
                        args.bands = '432'
                    force_unzip = True if args.force_unzip else False
                    for f in files:
                        stored = process_image(f, args.bands, False, args.pansharpen, args.ndvi, force_unzip,
                                               args.ndvigrey, bounds=bounds)

                        if args.upload:
                            try:
                                u = Uploader(args.key, args.secret, args.region)
                            except NoAuthHandlerFound:
                                return ["Could not authenticate with AWS", 1]
                            except URLError:
                                return ["Connection timeout. Probably the region parameter is incorrect", 1]
                            u.run(args.bucket, get_file(stored), stored)

                    return ['The output is stored at %s' % stored, 0]
                else:
                    return ['Download Completed', 0]
            except IncorrectSceneId:
                return ['The SceneID provided was incorrect', 1]
            except (RemoteFileDoesntExist, USGSInventoryAccessMissing) as e:
                return [e.message, 1]
1347133
def pix2ang(nside, pix, nest=False):
    
    theta, phi =  hp.pix2ang(nside, pix, nest=nest)
    lon = phi2lon(phi)
    lat = theta2lat(theta)
    return lon, lat
1064172
def atlas_overlap(dset,atlas=None):
    ''''''
    atlas = find_atlas(atlas)
    if atlas==None:
        return None
    
    cost_func = 'crM'
    infile = os.path.abspath(dset)
    tmpdir = tempfile.mkdtemp()
    with nl.run_in(tmpdir):
        o = nl.run(['3dAllineate','-verb','-base',atlas,'-source',infile + '[0]','-NN','-final','NN','-cost',cost_func,'-nmatch','20%','-onepass','-fineblur','2','-cmass','-prefix','test.nii.gz'])
        m = re.search(r'Final\s+cost = ([\d.]+) ;',o.output)
        if m:
            cost = float(m.group(1))
        o = nl.run(['3dmaskave','-mask',atlas,'-q','test.nii.gz'],stderr=None)
        data_thresh = float(o.output) / 4
        i = nl.dset_info('test.nii.gz')
        o = nl.run(['3dmaskave','-q','-mask','SELF','-sum',nl.calc([atlas,'test.nii.gz'],'equals(step(a-10),step(b-%.2f))'%data_thresh)],stderr=None)
        overlap = 100*float(o.output) / (i.voxel_dims[0]*i.voxel_dims[1]*i.voxel_dims[2])
    try:
        shutil.rmtree(tmpdir)
    except:
        pass
    return (cost,overlap)
1289143
public function overlaps(LatLngBounds $other)
    {
        $southWest = $other->getSouthWest();
        $northEast = $other->getNorthEast();

        $latOverlaps = ($northEast->getLatitude() > $this->southWest->getLatitude())
            && ($southWest->getLatitude() < $this->northEast->getLatitude());

        $lngOverlaps = ($northEast->getLongitude() > $this->southWest->getLongitude())
            && ($southWest->getLongitude() < $northEast->getLongitude());

        return $latOverlaps && $lngOverlaps;
    }
648155
function intersects(num, pos, angle)
{
    angle %= 4;
    var fig = getTransformedFigure(num, angle, pos);
    for (var i=0; i < fig.length; i+= 2)
    {
        var x = fig[i];
        var y = fig[i+1]
        if (y < 0)
            return true;
        if (x < 0)
            return true;
        if (x >= cupsize[0])
            return true;
        if (y >= cupsize[1])
            return true;
        if (cup[x + y*cupsize[0]])
            return true;
    }
    return false;
}
402426
private function _blendMultiply($canvas, $gd1, $gd2, $loopStartY, $loopEndY, $loopStartX, $loopEndX, $offsetX, $offsetY, $opacity){

        for ( $y = $loopStartY; $y < $loopEndY; $y++ ) {
            for ( $x = $loopStartX; $x < $loopEndX; $x++ ) {
                $canvasX    = $x + $offsetX;
                $canvasY    = $y + $offsetY;
                $argb1 = imagecolorat( $gd1, $canvasX, $canvasY );
                $r1    = ( $argb1 >> 16 ) & 0xFF;
                $g1    = ( $argb1 >> 8 ) & 0xFF;
                $b1    = $argb1 & 0xFF;

                $argb2 = imagecolorat( $gd2, $x, $y );
                $a2 = ($argb2 >> 24) & 0x7F; // 127 in hex. These are binary operations.
                $r2    = ( $argb2 >> 16 ) & 0xFF;
                $g2    = ( $argb2 >> 8 ) & 0xFF;
                $b2    = $argb2 & 0xFF;

                $r3 = round($r1 * $r2 / 255);
                $g3 = round($g1 * $g2 / 255);
                $b3 = round($b1 * $b2 / 255);

                $reverse = 127 - $a2;
                $reverse = round($reverse * $opacity);

                $argb3 = imagecolorallocatealpha( $canvas, $r3, $g3, $b3, 127 - $reverse );
                imagesetpixel( $canvas, $canvasX, $canvasY, $argb3 );
            }
        }
        return $canvas;
    }