示例#1
0
def _streprs(prec, objs, fmt, ints, force, strepr):
    '''(INTERNAL) Helper for C{fstr}, C{pairs}, C{reprs} and C{strs}
    '''
    # <https://docs.Python.org/3/library/stdtypes.html#printf-style-string-formatting>
    if fmt in _FfEeGg:
        fGg = fmt in _Gg
        fmt = NN(_PERCENT_, _DOT_, abs(prec), fmt)

    elif fmt.startswith(_PERCENT_):
        fGg = False
        try:  # to make sure fmt is valid
            f = fmt.replace(_DOTSTAR_, Fmt.DOT(abs(prec)))
            _ = f % (0.0, )
        except (TypeError, ValueError):
            raise _ValueError(fmt=fmt, txt=_not_(repr(_DOTSTAR_)))
        fmt = f

    else:
        raise _ValueError(fmt=fmt, txt=_not_(repr(_Fspec_)))

    for o in objs:
        if force or isinstance(o, float):
            t = fmt % (float(o), )
            if ints and (isint(o, both=True) or  # for ...
                         # corner case testLcc lon0=-96.0
                         t.rstrip(_0_).endswith(_DOT_)):
                t = t.split(_DOT_)[0]
            elif prec > 1:
                t = fstrzs(t, ap1z=fGg)
        elif strepr:
            t = strepr(o)
        else:
            raise _IsnotError(_scalar_, floats=o)
        yield t
示例#2
0
def _streprs(prec, objs, fmt, ints, force, strepr):
    '''(INTERNAL) Helper for C{fstr}, C{pairs}, C{reprs} and C{strs}
    '''
    if fmt in _EeFfGg:
        fGg = fmt in _Gg
        fmt = '%.' + str(abs(prec)) + fmt
    elif fmt.startswith(_PERCENT_):
        fGg = False
        fmt = fmt.replace(_STAR_, str(abs(prec)))
    else:
        t = '[%s]%s' % ('%.*', '|'.join(_EeFfGg))
        raise _ValueError(fmt=fmt, txt='not %r' % (t,))

    for o in objs:
        if force or isinstance(o, float):
            t = fmt % (float(o),)
            if ints and (isint(o, both=True) or  # for ...
                         # corner case testLcc lon0=-96.0
                         t.rstrip(_0_).endswith(_DOT_)):
                t = t.split(_DOT_)[0]
            elif prec > 1:
                t = fstrzs(t, ap1z=fGg)
        elif strepr:
            t = strepr(o)
        else:
            raise _IsnotError(_scalar_, floats=o)
        yield t
示例#3
0
def fpowers(x, n, alts=0):
    '''Return a series of powers M{[x**i for i=1..n]}.

       @arg x: Value (C{scalar}).
       @arg n: Highest exponent (C{int}).
       @kwarg alts: Only alternating powers, starting with
                    this exponent (C{int}).

       @return: Powers of B{C{x}} (C{float}[]).

       @raise TypeError: Non-scalar B{C{x}} or B{C{n}} not C{int}.

       @raise ValueError: Non-finite B{C{x}} or non-positive B{C{n}}.
    '''
    if not isfinite(x):
        raise _ValueError(x=x, txt=_not_(_finite_))
    if not isint(n):
        raise _IsnotError(int.__name__, n=n)
    elif n < 1:
        raise _ValueError(n=n)

    xs = [x]
    for _ in range(1, n):
        xs.append(xs[-1] * x)

    if alts > 0:  # x**2, x**4, ...
        # XXX PyChecker chokes on xs[alts-1::2]
        xs = xs[slice(alts - 1, None, 2)]

    # XXX PyChecker claims result is None
    return xs
示例#4
0
def _streprs(prec, objs, fmt, ints, floats, strepr):
    '''(INTERNAL) Helper for C{fstr}, C{pairs}, C{reprs} and C{strs}
    '''
    if fmt in _EeFfGg:
        fGg = fmt in _Gg
        fmt = '%.' + str(abs(prec)) + fmt
    elif fmt.startswith('%'):
        fGg = False
        fmt = fmt.replace('*', str(abs(prec)))
    else:
        t = repr('[%s]%s' % ('%.*', '|'.join(_EeFfGg)))
        raise ValueError('%s not %s: %r' % ('fmt', t, fmt))

    for o in objs:
        if floats or isinstance(o, float):
            t = fmt % (float(o), )
            if ints and (isint(o, both=True) or  # for ...
                         # corner case testLcc lon0=-96.0
                         t.rstrip('0').endswith('.')):
                t = t.split('.')[0]
            elif prec > 1:
                t = fstrzs(t, ap1z=fGg)
        elif strepr:
            t = strepr(o)
        else:
            raise IsnotError('scalar', floats=o)
        yield t
示例#5
0
 def _toStr(self, hemipole, B, cs, prec, sep):
     '''(INTERNAL) Return a string for this ETM/UTM/UPS coordinate.
     '''
     z = NN(Fmt.zone(self.zone), (self.band if B else NN))  # PYCHOK band
     t = (z, hemipole) + _fstrENH2(self, prec, None)[0]
     if cs:
         prec = cs if isint(cs) else 8  # for backward compatibility
         t += (_n_a_ if self.convergence is None else degDMS(
             self.convergence, prec=prec, pos=_PLUS_),
               _n_a_ if self.scale is None else fstr(self.scale, prec=prec))
     return t if sep is None else sep.join(t)
示例#6
0
def splice(iterable, n=2, **fill):
    '''Split an iterable into C{n} slices.

       @arg iterable: Items to be spliced (C{list}, C{tuple}, ...).
       @kwarg n: Number of slices to generate (C{int}).
       @kwarg fill: Optional fill value for missing items.

       @return: A generator for each of B{C{n}} slices,
                M{iterable[i::n] for i=0..n}.

       @raise ValueError: Invalid B{C{n}}.

       @note: Each generated slice is a C{tuple} or a C{list},
              the latter only if the B{C{iterable}} is a C{list}.

       @example:

       >>> from pygeodesy import splice

       >>> a, b = splice(range(10))
       >>> a, b
       ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))

       >>> a, b, c = splice(range(10), n=3)
       >>> a, b, c
       ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))

       >>> a, b, c = splice(range(10), n=3, fill=-1)
       >>> a, b, c
       ((0, 3, 6, 9), (1, 4, 7, -1), (2, 5, 8, -1))

       >>> tuple(splice(list(range(9)), n=5))
       ([0, 5], [1, 6], [2, 7], [3, 8], [4])

       >>> splice(range(9), n=1)
       <generator object splice at 0x0...>
    '''
    if not (isint(n) and n > 0):
        raise _ValueError(n=n)

    t = iterable
    if not isinstance(t, (list, tuple)):
        t = tuple(t)  # force tuple, also for PyPy3
    if n > 1:
        fill = _xkwds_get(fill, fill=_Missing)
        if fill is not _Missing:
            m = len(t) % n
            if m > 0:  # fill with same type
                t += type(t)((fill, )) * (n - m)
        for i in range(n):
            yield t[i::n]  # slice [i:None:n] pychok -Tb ...
    else:
        yield t
示例#7
0
def frange(start, number, step=1):
    '''Generate a range of C{float}s.

       @arg start: First value (C{float}).
       @arg number: The number of C{float}s to generate (C{int}).
       @kwarg step: Increment value (C{float}).

       @return: A generator (C{float}s).

       @see: U{NumPy.prod<https://docs.SciPy.org/doc/
             numpy/reference/generated/numpy.arange.html>}.
    '''
    if not isint(number):
        raise _IsnotError(int.__name__, number=number)
    for i in range(number):
        yield start + i * step
示例#8
0
def scalar(value, low=EPS, high=1.0, name=_scalar_, Error=ValueError):  # PYCHOK no cover
    '''DEPRECATED, use class L{Number_} or L{Scalar_}.

       @arg value: The value (C{scalar}).
       @kwarg low: Optional lower bound (C{scalar}).
       @kwarg high: Optional upper bound (C{scalar}).
       @kwarg name: Optional name of value (C{str}).
       @kwarg Error: Exception to raise (C{ValueError}).

       @return: New value (C{float} or C{int} for C{int} B{C{low}}).

       @raise Error: Invalid B{C{value}}.
    '''
    from pygeodesy.basics import isint
    C_ = Number_ if isint(low) else Scalar_
    return C_(value, name=name, Error=Error, low=low, high=high)
示例#9
0
    def __new__(cls, eisu, name=NN):
        '''New L{Epsg} (I{European Petroleum Survey Group}) code from a
           UTM/USP coordinate or other EPSG code.

           @arg eisu: Other code (L{Epsg}, C{int}, C{str}, L{Utm} or L{Ups}).

           @return: New L{Epsg}.

           @raise TypeError: Invalid B{C{eisu}}.

           @raise EPSGError: Invalid B{C{eisu}}.
        '''
        if isinstance(eisu, Epsg):
            self = int.__new__(cls, int(eisu))
            self._band = eisu.band
            self._epsg = self  # XXX eisu
            self._hemisphere = eisu.hemisphere
            self._utmups = eisu.utmups
            self._zone = eisu.zone
            if eisu.name:
                self.name = eisu.name

        elif isint(eisu):
            self = int.__new__(cls, eisu)
            self._epsg = eisu
            self._zone, self._hemisphere = decode2(eisu)  # PYCHOK UtmUps2Tuple

        elif isstr(eisu):
            self = encode(eisu)

        else:
            u = eisu
            _xinstanceof(Utm, Ups, eisu=u)
            self = encode(u.zone, hemipole=u.hemisphere,
                          band=u.band)  # PYCHOK **kwds
            self._utmups = u
            if u.name:
                self.name = u.name

        if name:
            self.name = name
        return self