Convert a PocketTopo `Shot` to a Compass `Shot`
429487
def shot2shot(insurvey, inshot, calculate_lrud=True):
    """"""
    # FIXME: requires angles in degrees only, no grads

    splays = insurvey.splays[inshot['FROM']]
    if calculate_lrud and not inshot.is_splay and splays:
        # Try our best to convert PocketTopo splay shots into LRUDs
        print '\n\n' 'sta %s has %d splays' % (inshot['FROM'], len(splays))

        left_azm, right_azm = (inshot['AZM'] - 90) % 360, (inshot['AZM'] + 90) % 360
        left_shot, right_shot = None, None
        left_candidates = find_candidate_splays(splays, left_azm, 0)
        if left_candidates:
            left_shot = max(left_candidates, key=lambda shot: hd(shot['INC'], shot['LENGTH']))
            left = hd(left_shot['INC'], left_shot['LENGTH'])
        else:
            left = 0
        right_candidates = find_candidate_splays(splays, right_azm, 0)
        if right_candidates:
            right_shot = max(right_candidates, key=lambda shot: hd(shot['INC'], shot['LENGTH']))
            right = hd(right_shot['INC'], right_shot['LENGTH'])
        else:
            right = 0

        print '\t' 'left=%.1f  azm=%.1f  right=%.1f' % (left_azm, inshot['AZM'], right_azm)
        print '\t' '%d candidate LEFT shots' % len(left_candidates)
        for splay in left_candidates:
            print '\t\t\t' + str(splay)
        print '\t\t' '%.1f - Chose: %s' % (left, str(left_shot))
        print '\t' '%d candidate RIGHT shots' % len(right_candidates)
        for splay in right_candidates:
            print '\t\t\t' + str(splay)
        print '\t\t' '%.1f - Chose: %s' % (right, str(right_shot))

        up_candidates = find_candidate_vert_splays(splays, 90)
        if up_candidates:
            up_shot = max(up_candidates, key=lambda splay: vd(splay['INC'], splay['LENGTH']))
            up = vd(up_shot['INC'], up_shot['LENGTH'])
        else:
            up = 0
        down_candidates = find_candidate_vert_splays(splays, -90)
        if down_candidates:
            down_shot = max(down_candidates, key=lambda splay: vd(splay['INC'], splay['LENGTH']))  # TODO: should vd() give negative and we find min()?
            down = vd(down_shot['INC'], down_shot['LENGTH'])
        else:
            down = 0

        print '\t', inshot, 'LRUD=', ', '.join(('%0.1f' % v) for v in (left, right, up, down))
        assert(all(v >=0 for v in (left, right, up, down)))
    else:
        up, down, left, right = None, None, None, None

    return compass.Shot([
        ('FROM', inshot['FROM']),
        # Compass requires a named TO station, so we must invent one for splays
        ('TO', inshot['TO'] or '%s.s%03d' % (inshot['FROM'], random.randint(0,1000))),
        ('LENGTH', m2ft(inshot.length)),
        # BEARING/AZM named inconsistently in Davies to reflect each program's arbitrary name. We
        # can't use `inshot.azm` here because we need the "raw" compass value without declination
        ('BEARING', inshot['AZM']),
        ('INC', inshot.inc),
        ('LEFT', m2ft(left) if left is not None else -9.90),
        ('UP', m2ft(up) if left is not None else -9.90),
        ('DOWN', m2ft(down) if left is not None else -9.90),
        ('RIGHT', m2ft(right) if left is not None else -9.90),  # Compass requires this order!
        # Compass 'L' flag excludes splays from cave length calculation
        ('FLAGS', (compass.Exclude.LENGTH, compass.Exclude.PLOT) if inshot.is_splay else ()),
        # COMMENTS/COMMENT named inconsistently in Davies to reflect each program's arbitrary name
        ('COMMENTS', inshot['COMMENT'])
    ])
570635
def add_arrows(self, cent, direction, mag=1, **kwargs):
        
        direction = direction.copy()
        if cent.ndim != 2:
            cent = cent.reshape((-1, 3))

        if direction.ndim != 2:
            direction = direction.reshape((-1, 3))

        direction[:,0] *= mag
        direction[:,1] *= mag
        direction[:,2] *= mag

        pdata = vtki.vector_poly_data(cent, direction)
        # Create arrow object
        arrow = vtk.vtkArrowSource()
        arrow.Update()
        glyph3D = vtk.vtkGlyph3D()
        glyph3D.SetSourceData(arrow.GetOutput())
        glyph3D.SetInputData(pdata)
        glyph3D.SetVectorModeToUseVector()
        glyph3D.Update()

        arrows = wrap(glyph3D.GetOutput())

        return self.add_mesh(arrows, **kwargs)
1086019
def circle(m, centerlon, centerlat, radius, *args, **kwargs):
    
    glon1 = centerlon
    glat1 = centerlat
    X = []
    Y = []
    for azimuth in range(0, 360):
        glon2, glat2, baz = _gccalc(glon1, glat1, azimuth, radius)
        X.append(glon2)
        Y.append(glat2)
    X.append(X[0])
    Y.append(Y[0])

    proj_x, proj_y = m(X,Y)
    return zip(proj_x, proj_y)
822422
function( shot, callback ) {

        var scope = this;

        scope.getShotBuffer( shot, function( err, data ) {

            if( err ) {

                callback( err );

                return;

            }

            var base64 = scope.getBase64FromBuffer( data );

            callback( null, base64 );

        });

    }
1305582
def rotate_orth(self, quads):
        ""
        with _LeptonicaErrorTrap():
            return Pix(lept.pixRotateOrth(self._cdata, quads))
1135611
def angToPix(nside, lon, lat, nest=False):
    
    theta = np.radians(90. - lat)
    phi = np.radians(lon)
    return hp.ang2pix(nside, theta, phi, nest=nest)
121360
def equi_basemap(m, centerlon, centerlat, radius, color):
    
    glon1 = centerlon
    glat1 = centerlat
    X = []
    Y = []
    for azimuth in range(0, 360):
        glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius)
        X.append(glon2)
        Y.append(glat2)
    X.append(X[0])
    Y.append(Y[0])

    X, Y = m(X, Y)
    plt.plot(X, Y, color)
693189
def plt2xyz(fname):
	""""""
	parser = CompassPltParser(fname)
	plt = parser.parse()

	for segment in plt:
		for command in segment:
			if command.cmd == 'd':
				if plt.utm_zone:
					x, y, z = command.x * FT_TO_M, command.y * FT_TO_M, command.z * FT_TO_M
				else:
					x, y, z = command.x, command.y, command.z
				print('%.3f\t%.3f\t%.3f' % (x, y, z))
21306
def shift_to_coords(self, pix, fill_value=np.nan):
        """"""

        pix_offset = self.get_offsets(pix)
        dpix = np.zeros(len(self.shape) - 1)
        for i in range(len(self.shape) - 1):
            x = self.rebin * (pix[i] - pix_offset[i + 1]
                              ) + (self.rebin - 1.0) / 2.
            dpix[i] = x - self._pix_ref[i]

        pos = [pix_offset[i] + self.shape[i] // 2
               for i in range(self.data.ndim)]
        s0, s1 = utils.overlap_slices(self.shape_out, self.shape, pos)

        k = np.zeros(self.data.shape)
        for i in range(k.shape[0]):
            k[i] = shift(self._data_spline[i], dpix, cval=np.nan,
                         order=2, prefilter=False)

        for i in range(1, len(self.shape)):
            k = utils.sum_bins(k, i, self.rebin)

        k0 = np.ones(self.shape_out) * fill_value

        if k[s1].size == 0 or k0[s0].size == 0:
            return k0
        k0[s0] = k[s1]
        return k0
1048013
def read(fname, merge_duplicate_shots=False, encoding='windows-1252'):
        """"""
        return PocketTopoTxtParser(fname, merge_duplicate_shots, encoding).parse()
611382
def downsample_trace(mesh, tol=1.0):
    
    idx = _find_turning_points(mesh, tol)
    if mesh.depths is not None:
        return numpy.column_stack([mesh.lons[0, idx],
                                   mesh.lats[0, idx],
                                   mesh.depths[0, idx]])
    else:
        return numpy.column_stack([mesh.lons[0, idx], mesh.lats[0, idx]])
85791
function (point) {
        var dx = point[0] - this.cx;
        var dy = point[1] - this.cy;
        var angleAxis = this.getAngleAxis();
        var extent = angleAxis.getExtent();
        var minAngle = Math.min(extent[0], extent[1]);
        var maxAngle = Math.max(extent[0], extent[1]);
        // Fix fixed extent in polarCreator
        // FIXME
        angleAxis.inverse
            ? (minAngle = maxAngle - 360)
            : (maxAngle = minAngle + 360);

        var radius = Math.sqrt(dx * dx + dy * dy);
        dx /= radius;
        dy /= radius;

        var radian = Math.atan2(-dy, dx) / Math.PI * 180;

        // move to angleExtent
        var dir = radian < minAngle ? 1 : -1;
        while (radian < minAngle || radian > maxAngle) {
            radian += dir * 360;
        }

        return [radius, radian];
    }
1089867
function getDialCoords(radius, startAngle, endAngle) {
      var cx = GaugeDefaults.centerX,
          cy = GaugeDefaults.centerY;
      return {
        end: getCartesian(cx, cy, radius, endAngle),
      	start: getCartesian(cx, cy, radius, startAngle)
      };
    }
1037112
function mapToProps(_, {
  phone: {
    brand,
    callLogger,
    callMonitor,
    locale,
    regionSettings,
    rolesAndPermissions,
    callHistory,
    connectivityMonitor,
    rateLimiter,
    dateTimeFormat,
    call,
    composeText,
  },
  showContactDisplayPlaceholder = false,
  enableContactFallback = false,
}) {
  return {
    currentLocale: locale.currentLocale,
    activeRingCalls: callMonitor.activeRingCalls,
    activeOnHoldCalls: callMonitor.activeOnHoldCalls,
    activeCurrentCalls: callMonitor.activeCurrentCalls,
    otherDeviceCalls: callMonitor.otherDeviceCalls,
    areaCode: regionSettings.areaCode,
    countryCode: regionSettings.countryCode,
    outboundSmsPermission: !!(
      rolesAndPermissions.permissions &&
      rolesAndPermissions.permissions.OutboundSMS
    ),
    internalSmsPermission: !!(
      rolesAndPermissions.permissions &&
      rolesAndPermissions.permissions.InternalSMS
    ),
    // showSpinner: false,
    brand: brand.fullName,
    showContactDisplayPlaceholder,
    autoLog: !!(callLogger && callLogger.autoLog),
    enableContactFallback,
    calls: callHistory.latestCalls,
    disableLinks: !connectivityMonitor.connectivity ||
    rateLimiter.throttling,
    disableClickToDial: !(call && call.isIdle),
    loggingMap: (callLogger && callLogger.loggingMap),
    showSpinner: !(
      callHistory.ready &&
      locale.ready &&
      regionSettings.ready &&
      dateTimeFormat.ready &&
      connectivityMonitor.ready &&
      (!rolesAndPermissions || rolesAndPermissions.ready) &&
      (!call || call.ready) &&
      (!composeText || composeText.ready) &&
      (!callLogger || callLogger.ready)
    ),
    readTextPermission: rolesAndPermissions.readTextPermissions,
  };
}
64230
public static GeometryLocation getVertexToSnap(Geometry g, Point p, double tolerance) {
        DistanceOp distanceOp = new DistanceOp(g, p);
        GeometryLocation snapedPoint = distanceOp.nearestLocations()[0];
        if (tolerance == 0 || snapedPoint.getCoordinate().distance(p.getCoordinate()) <= tolerance) {
            return snapedPoint;
        }
        return null;

    }
238548
function getSnapOffset(event, axis) {
  var context = event.context,
      shape = event.shape,
      gridSnappingContext = context.gridSnappingContext || {},
      snapLocation = gridSnappingContext.snapLocation;

  if (!shape || !snapLocation) {
    return 0;
  }

  if (axis === 'x') {
    if (/left/.test(snapLocation)) {
      return -shape.width / 2;
    }

    if (/right/.test(snapLocation)) {
      return shape.width / 2;
    }
  } else {
    if (/top/.test(snapLocation)) {
      return -shape.height / 2;
    }

    if (/bottom/.test(snapLocation)) {
      return shape.height / 2;
    }
  }

  return 0;
}
778137
def gesture(self, start1, start2, *args, **kwargs):
        '''
        
        '''
        def to(obj_self, end1, end2, steps=100):
            ctp = lambda pt: point(*pt) if type(pt) == tuple else pt  # convert tuple to point
            s1, s2, e1, e2 = ctp(start1), ctp(start2), ctp(end1), ctp(end2)
            return self.jsonrpc.gesture(self.selector, s1, s2, e1, e2, steps)
        obj = type("Gesture", (object,), {"to": to})()
        return obj if len(args) == 0 else to(None, *args, **kwargs)