예제 #1
0
def test_negative_infinity_f():
    inf = float("-infinity")
    dumped = rj.dumps(inf)
    loaded = rj.loads(dumped)
    assert loaded == inf

    dumped = rj.dumps(inf, allow_nan=True)
    loaded = rj.loads(dumped, allow_nan=True)
    assert loaded == inf

    with pytest.raises(ValueError):
        rj.dumps(inf, number_mode=None)

    with pytest.raises(ValueError):
        rj.dumps(inf, allow_nan=False)

    d = Decimal(inf)
    assert d.is_infinite()

    with pytest.raises(ValueError):
        rj.dumps(d, number_mode=rj.NM_DECIMAL)

    dumped = rj.dumps(d, number_mode=rj.NM_DECIMAL|rj.NM_NAN)
    loaded = rj.loads(dumped, number_mode=rj.NM_DECIMAL, allow_nan=True)
    assert loaded == inf
    assert loaded.is_infinite()
예제 #2
0
파일: routing.py 프로젝트: frostming/baize
 def to_string(self, value: Decimal) -> str:
     if value.is_nan():
         raise ValueError("NaN values are not supported")
     if value.is_infinite():
         raise ValueError("Infinite values are not supported")
     if Decimal("0.0") > value:
         raise ValueError("Negative decimal are not supported")
     return str(value).rstrip("0").rstrip(".")
예제 #3
0
파일: yaml.py 프로젝트: lellisjr/yakut
def _represent_decimal(self: ruamel.yaml.BaseRepresenter,
                       data: decimal.Decimal) -> ruamel.yaml.ScalarNode:
    if data.is_finite():
        s = str(
            _POINT_ZERO_DECIMAL + data
        )  # The zero addition is to force float-like string representation
    elif data.is_nan():
        s = ".nan"
    elif data.is_infinite():
        s = ".inf" if data > 0 else "-.inf"
    else:
        assert False
    return self.represent_scalar("tag:yaml.org,2002:float", s)
예제 #4
0
    def testInvalidConstruction(self):
        self.assertRaises(SimpleTypeValueError, xsd.decimal, 'bogus')

        nan = Decimal('NaN')
        self.assertTrue(nan.is_nan())
        self.assertEqual('NaN', str(nan))
        self.assertRaises(SimpleTypeValueError, xsd.decimal, nan)
        self.assertRaises(SimpleTypeValueError, xsd.decimal, 'NaN')

        inf = Decimal('Infinity')
        self.assertTrue(inf.is_infinite())
        self.assertEqual('Infinity', str(inf))
        self.assertRaises(SimpleTypeValueError, xsd.decimal, inf)
        self.assertRaises(SimpleTypeValueError, xsd.decimal, 'Infinity')
예제 #5
0
    def testInvalidConstruction (self):
        self.assertRaises(SimpleTypeValueError, xsd.decimal, 'bogus')

        nan = Decimal('NaN')
        self.assertTrue(nan.is_nan())
        self.assertEqual('NaN', str(nan))
        self.assertRaises(SimpleTypeValueError, xsd.decimal, nan)
        self.assertRaises(SimpleTypeValueError, xsd.decimal, 'NaN')

        inf = Decimal('Infinity')
        self.assertTrue(inf.is_infinite())
        self.assertEqual('Infinity', str(inf))
        self.assertRaises(SimpleTypeValueError, xsd.decimal, inf)
        self.assertRaises(SimpleTypeValueError, xsd.decimal, 'Infinity')
예제 #6
0
def test_negative_infinity_c():
    inf = float("-infinity")
    dumped = rj.Encoder()(inf)
    loaded = rj.Decoder()(dumped)
    assert loaded == inf

    with pytest.raises(ValueError):
        rj.Encoder(number_mode=None)(inf)

    d = Decimal(inf)
    assert d.is_infinite()

    with pytest.raises(ValueError):
        rj.Encoder(number_mode=rj.NM_DECIMAL)(d)

    dumped = rj.Encoder(number_mode=rj.NM_DECIMAL|rj.NM_NAN)(d)
    loaded = rj.Decoder(number_mode=rj.NM_DECIMAL|rj.NM_NAN)(dumped)
    assert loaded == inf
    assert loaded.is_infinite()
예제 #7
0
    def __new__(cls, value, dec_places=0):
        if dec_places < 0 or not isinstance(dec_places, int):
            raise ValueError('dec_places must be nonnegative integer')

        if isinstance(value, int):
            return _qpdf._new_real(value, 0)

        if isinstance(value, float) and isfinite(value):
            return _qpdf._new_real(value, dec_places)

        try:
            dec = Decimal(value)
        except InvalidOperation:
            raise TypeError(
                'Could not convert object to int, float or Decimal')

        if dec.is_infinite() or dec.is_nan():
            raise ValueError('NaN and infinity are not valid PDF objects')

        return _qpdf._new_real(str(dec))
예제 #8
0
 def from_decimal(cls, dec):
     """Converts a finite Decimal instance to a rational number, exactly."""
     from decimal import Decimal
     if isinstance(dec, numbers.Integral):
         dec = Decimal(int(dec))
     elif not isinstance(dec, Decimal):
         raise TypeError(
             "%s.from_decimal() only takes Decimals, not %r (%s)" %
             (cls.__name__, dec, type(dec).__name__))
     if dec.is_infinite():
         raise OverflowError(
             "Cannot convert %s to %s." % (dec, cls.__name__))
     if dec.is_nan():
         raise ValueError("Cannot convert %s to %s." % (dec, cls.__name__))
     sign, digits, exp = dec.as_tuple()
     digits = int(''.join(map(str, digits)))
     if sign:
         digits = -digits
     if exp >= 0:
         return cls(digits * 10 ** exp)
     else:
         return cls(digits, 10 ** -exp)
예제 #9
0
파일: db.py 프로젝트: Alex-ala/photonix
def record_photo(path):
    file_modified_at = datetime.fromtimestamp(os.stat(path).st_mtime, tz=utc)

    try:
        photo_file = PhotoFile.objects.get(path=path)
    except PhotoFile.DoesNotExist:
        photo_file = PhotoFile()

    if photo_file and photo_file.file_modified_at == file_modified_at:
        return False

    metadata = PhotoMetadata(path)
    date_taken = parse_datetime(metadata.get('Date/Time Original'))
    if date_taken is None:
        date_taken = datetime.now(utc)

    camera = None
    camera_make = metadata.get('Make')
    camera_model = metadata.get('Camera Model Name')
    if camera_model:
        camera_model = camera_model.replace(camera_make, '').strip()
    if camera_make and camera_model:
        try:
            camera = Camera.objects.get(make=camera_make, model=camera_model)
            if date_taken < camera.earliest_photo:
                camera.earliest_photo = date_taken
                camera.save()
            if date_taken > camera.latest_photo:
                camera.latest_photo = date_taken
                camera.save()
        except Camera.DoesNotExist:
            camera = Camera(make=camera_make,
                            model=camera_model,
                            earliest_photo=date_taken,
                            latest_photo=date_taken)
            camera.save()

    lens = None
    lens_name = metadata.get('Lens ID')
    if lens_name:
        try:
            lens = Lens.objects.get(name=lens_name)
            if date_taken < lens.earliest_photo:
                lens.earliest_photo = date_taken
                lens.save()
            if date_taken > lens.latest_photo:
                lens.latest_photo = date_taken
                lens.save()
        except Lens.DoesNotExist:
            lens = Lens(name=lens_name,
                        earliest_photo=date_taken,
                        latest_photo=date_taken)
            lens.save()

    photo = None
    if date_taken:
        try:
            # TODO: Match on file number/file name as well
            photo = Photo.objects.get(taken_at=date_taken)
        except Photo.DoesNotExist:
            pass

    latitude = None
    longitude = None
    if metadata.get('GPS Position'):
        latitude, longitude = parse_gps_location(metadata.get('GPS Position'))

    if not photo:
        # Save Photo

        aperture = None
        aperturestr = metadata.get('Aperture')
        if aperturestr:
            try:
                aperture = Decimal(aperturestr)
                if aperture.is_infinite():
                    aperture = None
            except:
                pass

        photo = Photo(
            taken_at=date_taken,
            taken_by=metadata.get('Artist') or None,
            aperture=aperture,
            exposure=metadata.get('Exposure Time') or None,
            iso_speed=metadata.get('ISO') and int(metadata.get('ISO')) or None,
            focal_length=metadata.get('Focal Length')
            and metadata.get('Focal Length').split(' ', 1)[0] or None,
            flash=metadata.get('Flash')
            and 'on' in metadata.get('Flash').lower() or False,
            metering_mode=metadata.get('Metering Mode') or None,
            drive_mode=metadata.get('Drive Mode') or None,
            shooting_mode=metadata.get('Shooting Mode') or None,
            camera=camera,
            lens=lens,
            latitude=latitude,
            longitude=longitude,
            altitude=metadata.get('GPS Altitude')
            and metadata.get('GPS Altitude').split(' ')[0])
        photo.save()

    width = metadata.get('Image Width')
    height = metadata.get('Image Height')
    if metadata.get('Orientation') in [
            'Rotate 90 CW', 'Rotate 270 CCW', 'Rotate 90 CCW', 'Rotate 270 CW'
    ]:
        old_width = width
        width = height
        height = old_width

    # Save PhotoFile
    photo_file.photo = photo
    photo_file.path = path
    photo_file.width = width
    photo_file.height = height
    photo_file.mimetype = mimetypes.guess_type(path)[0]
    photo_file.file_modified_at = file_modified_at
    photo_file.bytes = os.stat(path).st_size
    photo_file.preferred = False  # TODO
    photo_file.save()

    # Create task to ensure JPEG version of file exists (used for thumbnailing, analysing etc.)
    Task(type='ensure_raw_processed',
         subject_id=photo.id,
         complete_with_children=True).save()

    return photo
예제 #10
0
def decimals(min_value=None,
             max_value=None,
             allow_nan=None,
             allow_infinity=None,
             places=None):
    """Generates instances of decimals.Decimal, which may be:

    - A finite rational number, between ``min_value`` and ``max_value``.
    - Not a Number, if ``allow_nan`` is True.  None means "allow NaN, unless
      ``min__value`` and ``max_value`` are not None".
    - Positive or negative infinity, if ``max_value`` and ``min_value``
      respectively are None, and ``allow_infinity`` is not False.  None means
      "allow infinity, unless excluded by the min and max values".

    Note that where floats have one `NaN` value, Decimals have four: signed,
    and either *quiet* or *signalling*.  See `the decimal module docs
    <https://docs.python.org/3/library/decimal.html#special-values>`_ for
    more information on special values.

    If ``places`` is not None, all finite values drawn from the strategy will
    have that number of digits after the decimal place.

    """
    # Convert min_value and max_value to Decimal values, and validate args
    check_valid_integer(places)
    if places is not None and places < 0:
        raise InvalidArgument('places=%r may not be negative' % places)

    if min_value is not None:
        min_value = Decimal(min_value)
        if min_value.is_infinite() and min_value < 0:
            if not (allow_infinity or allow_infinity is None):
                raise InvalidArgument('allow_infinity=%r, but min_value=%r' %
                                      (allow_infinity, min_value))
            min_value = None
        elif not min_value.is_finite():
            # This could be positive infinity, quiet NaN, or signalling NaN
            raise InvalidArgument(u'Invalid min_value=%r' % min_value)
    if max_value is not None:
        max_value = Decimal(max_value)
        if max_value.is_infinite() and max_value > 0:
            if not (allow_infinity or allow_infinity is None):
                raise InvalidArgument('allow_infinity=%r, but max_value=%r' %
                                      (allow_infinity, max_value))
            max_value = None
        elif not max_value.is_finite():
            raise InvalidArgument(u'Invalid max_value=%r' % max_value)
    check_valid_bound(min_value, 'min_value')
    check_valid_bound(max_value, 'max_value')
    check_valid_interval(min_value, max_value, 'min_value', 'max_value')

    if allow_infinity and (None not in (min_value, max_value)):
        raise InvalidArgument('Cannot allow infinity between finite bounds')
    # Set up a strategy for finite decimals
    if places is not None:
        # Fixed-point decimals are basically integers with a scale factor

        def try_quantize(d):
            try:
                return d.quantize(factor)
            except InvalidOperation:  # pragma: no cover
                return None

        factor = Decimal(10)**-places
        max_num = max_value / factor if max_value is not None else None
        min_num = min_value / factor if min_value is not None else None
        strat = integers(min_value=min_num, max_value=max_num)\
            .map(lambda d: try_quantize(d * factor))\
            .filter(lambda d: d is not None)
    else:
        # Otherwise, they're like fractions featuring a power of ten
        strat = fractions(min_value=min_value, max_value=max_value).map(
            lambda f: Decimal(f.numerator) / f.denominator)
    # Compose with sampled_from for infinities and NaNs as appropriate
    special = []
    if allow_nan or (allow_nan is None and (None in (min_value, max_value))):
        special.extend(map(Decimal, ('NaN', '-NaN', 'sNaN', '-sNaN')))
    if allow_infinity or (allow_infinity is max_value is None):
        special.append(Decimal('Infinity'))
    if allow_infinity or (allow_infinity is min_value is None):
        special.append(Decimal('-Infinity'))
    return strat | sampled_from(special)
예제 #11
0
파일: accuracy.py 프로젝트: Dunes/janitor
def as_end_time(value: Decimal) -> Decimal:
    if value.is_infinite():
        return value
    return value.quantize(precision, rounding=ROUND_CEILING) - increment
예제 #12
0
def record_photo(path, library, inotify_event_type=None):
    logger.info(f'Recording photo {path}')

    mimetype = get_mimetype(path)

    if not imghdr.what(
            path) and not mimetype in MIMETYPE_WHITELIST and subprocess.run(
                ['dcraw', '-i', path]).returncode:
        logger.error(f'File is not a supported type: {path} ({mimetype})')
        return None

    if type(library) == Library:
        library_id = library.id
    else:
        library_id = str(library)
    try:
        photo_file = PhotoFile.objects.get(path=path)
    except PhotoFile.DoesNotExist:
        photo_file = PhotoFile()

    if inotify_event_type in ['DELETE', 'MOVED_FROM']:
        if PhotoFile.objects.filter(path=path).exists():
            return delete_photo_record(photo_file)
        else:
            return True

    file_modified_at = datetime.fromtimestamp(os.stat(path).st_mtime, tz=utc)

    if photo_file and photo_file.file_modified_at == file_modified_at:
        return True

    metadata = PhotoMetadata(path)
    date_taken = None
    possible_date_keys = [
        'Create Date', 'Date/Time Original', 'Date Time Original', 'Date/Time',
        'Date Time', 'GPS Date/Time', 'File Modification Date/Time'
    ]
    for date_key in possible_date_keys:
        date_taken = parse_datetime(metadata.get(date_key))
        if date_taken:
            break
    # If EXIF data not found.
    date_taken = date_taken or datetime.strptime(
        time.ctime(os.path.getctime(path)), "%a %b %d %H:%M:%S %Y")

    camera = None
    camera_make = metadata.get('Make', '')[:Camera.make.field.max_length]
    camera_model = metadata.get('Camera Model Name', '')
    if camera_model:
        camera_model = camera_model.replace(camera_make, '').strip()
    camera_model = camera_model[:Camera.model.field.max_length]
    if camera_make and camera_model:
        try:
            camera = Camera.objects.get(library_id=library_id,
                                        make=camera_make,
                                        model=camera_model)
            if date_taken < camera.earliest_photo:
                camera.earliest_photo = date_taken
                camera.save()
            if date_taken > camera.latest_photo:
                camera.latest_photo = date_taken
                camera.save()
        except Camera.DoesNotExist:
            camera = Camera(library_id=library_id,
                            make=camera_make,
                            model=camera_model,
                            earliest_photo=date_taken,
                            latest_photo=date_taken)
            camera.save()

    lens = None
    lens_name = metadata.get('Lens ID')
    if lens_name:
        try:
            lens = Lens.objects.get(name=lens_name)
            if date_taken < lens.earliest_photo:
                lens.earliest_photo = date_taken
                lens.save()
            if date_taken > lens.latest_photo:
                lens.latest_photo = date_taken
                lens.save()
        except Lens.DoesNotExist:
            lens = Lens(library_id=library_id,
                        name=lens_name,
                        earliest_photo=date_taken,
                        latest_photo=date_taken)
            lens.save()

    photo = None
    if date_taken:
        try:
            # TODO: Match on file number/file name as well
            photo = Photo.objects.get(taken_at=date_taken)
        except Photo.DoesNotExist:
            pass

    latitude = None
    longitude = None
    if metadata.get('GPS Position'):
        latitude, longitude = parse_gps_location(metadata.get('GPS Position'))

    iso_speed = None
    if metadata.get('ISO'):
        try:
            iso_speed = int(re.search(r'[0-9]+', metadata.get('ISO')).group(0))
        except AttributeError:
            pass
    if not photo:
        # Save Photo
        aperture = None
        aperturestr = metadata.get('Aperture')
        if aperturestr:
            try:
                aperture = Decimal(aperturestr)
                if aperture.is_infinite():
                    aperture = None
            except:
                pass

        photo = Photo(
            library_id=library_id,
            taken_at=date_taken,
            taken_by=metadata.get(
                'Artist', '')[:Photo.taken_by.field.max_length] or None,
            aperture=aperture,
            exposure=metadata.get(
                'Exposure Time', '')[:Photo.exposure.field.max_length] or None,
            iso_speed=iso_speed,
            focal_length=metadata.get('Focal Length')
            and metadata.get('Focal Length').split(' ', 1)[0] or None,
            flash=metadata.get('Flash')
            and 'on' in metadata.get('Flash').lower() or False,
            metering_mode=metadata.get(
                'Metering Mode', '')[:Photo.metering_mode.field.max_length]
            or None,
            drive_mode=metadata.get(
                'Drive Mode', '')[:Photo.drive_mode.field.max_length] or None,
            shooting_mode=metadata.get(
                'Shooting Mode', '')[:Photo.shooting_mode.field.max_length]
            or None,
            camera=camera,
            lens=lens,
            latitude=latitude,
            longitude=longitude,
            altitude=metadata.get('GPS Altitude')
            and metadata.get('GPS Altitude').split(' ')[0],
            star_rating=metadata.get('Rating'))
        photo.save()

        for subject in metadata.get('Subject', '').split(','):
            subject = subject.strip()
            if subject:
                tag, _ = Tag.objects.get_or_create(library_id=library_id,
                                                   name=subject,
                                                   type="G")
                PhotoTag.objects.create(photo=photo, tag=tag, confidence=1.0)
    else:
        for photo_file in photo.files.all():
            if not os.path.exists(photo_file.path):
                photo_file.delete()

    width = metadata.get('Image Width')
    height = metadata.get('Image Height')
    if metadata.get('Orientation') in [
            'Rotate 90 CW', 'Rotate 270 CCW', 'Rotate 90 CCW', 'Rotate 270 CW'
    ]:
        old_width = width
        width = height
        height = old_width

    # Save PhotoFile
    photo_file.photo = photo
    photo_file.path = path
    photo_file.width = width
    photo_file.height = height
    photo_file.mimetype = mimetype
    photo_file.file_modified_at = file_modified_at
    photo_file.bytes = os.stat(path).st_size
    photo_file.preferred = False  # TODO
    photo_file.save()

    # Create task to ensure JPEG version of file exists (used for thumbnailing, analysing etc.)
    Task(type='ensure_raw_processed',
         subject_id=photo.id,
         complete_with_children=True,
         library=photo.library).save()

    return photo
예제 #13
0
    def serialize(self, value: Decimal, **kwargs: Any) -> str:
        if value.is_infinite():
            return str(value).replace("Infinity", "INF")

        return str(value)
예제 #14
0
def record_photo(path, library, inotify_event_type=None):
    if type(library) == Library:
        library_id = library.id
    else:
        library_id = str(library)

    try:
        photo_file = PhotoFile.objects.get(path=path)
    except PhotoFile.DoesNotExist:
        photo_file = PhotoFile()

    if inotify_event_type in ['DELETE', 'MOVED_FROM']:
        if PhotoFile.objects.filter(path=path).exists():
            return delete_photo_record(photo_file)
        else:
            return False

    file_modified_at = datetime.fromtimestamp(os.stat(path).st_mtime, tz=utc)

    if photo_file and photo_file.file_modified_at == file_modified_at:
        return False

    metadata = PhotoMetadata(path)
    date_taken = None
    possible_date_keys = [
        'Date/Time Original', 'Date Time Original', 'Date/Time', 'Date Time',
        'GPS Date/Time', 'Modify Date', 'File Modification Date/Time'
    ]
    for date_key in possible_date_keys:
        date_taken = parse_datetime(metadata.get(date_key))
        if date_taken:
            break

    camera = None
    camera_make = metadata.get('Make')
    if camera_make is None:
        camera_make = ''
    camera_model = metadata.get('Camera Model Name')
    if camera_model:
        camera_model = camera_model.replace(camera_make, '').strip()
    if camera_make and camera_model:
        try:
            camera = Camera.objects.get(library_id=library_id,
                                        make=camera_make,
                                        model=camera_model)
            if date_taken < camera.earliest_photo:
                camera.earliest_photo = date_taken
                camera.save()
            if date_taken > camera.latest_photo:
                camera.latest_photo = date_taken
                camera.save()
        except Camera.DoesNotExist:
            camera = Camera(library_id=library_id,
                            make=camera_make,
                            model=camera_model,
                            earliest_photo=date_taken,
                            latest_photo=date_taken)
            camera.save()

    lens = None
    lens_name = metadata.get('Lens ID')
    if lens_name:
        try:
            lens = Lens.objects.get(name=lens_name)
            if date_taken < lens.earliest_photo:
                lens.earliest_photo = date_taken
                lens.save()
            if date_taken > lens.latest_photo:
                lens.latest_photo = date_taken
                lens.save()
        except Lens.DoesNotExist:
            lens = Lens(library_id=library_id,
                        name=lens_name,
                        earliest_photo=date_taken,
                        latest_photo=date_taken)
            lens.save()

    photo = None
    if date_taken:
        try:
            # TODO: Match on file number/file name as well
            photo = Photo.objects.get(taken_at=date_taken)
        except Photo.DoesNotExist:
            pass

    latitude = None
    longitude = None
    if metadata.get('GPS Position'):
        latitude, longitude = parse_gps_location(metadata.get('GPS Position'))

    iso_speed = None
    if metadata.get('ISO'):
        try:
            iso_speed = int(re.search(r'[0-9]+', metadata.get('ISO')).group(0))
        except AttributeError:
            pass

    if not photo:
        # Save Photo
        aperture = None
        aperturestr = metadata.get('Aperture')
        if aperturestr:
            try:
                aperture = Decimal(aperturestr)
                if aperture.is_infinite():
                    aperture = None
            except:
                pass

        photo = Photo(library_id=library_id,
                      taken_at=date_taken,
                      taken_by=metadata.get('Artist') or None,
                      aperture=aperture,
                      exposure=metadata.get('Exposure Time') or None,
                      iso_speed=iso_speed,
                      focal_length=metadata.get('Focal Length')
                      and metadata.get('Focal Length').split(' ', 1)[0]
                      or None,
                      flash=metadata.get('Flash')
                      and 'on' in metadata.get('Flash').lower() or False,
                      metering_mode=metadata.get('Metering Mode') or None,
                      drive_mode=metadata.get('Drive Mode') or None,
                      shooting_mode=metadata.get('Shooting Mode') or None,
                      camera=camera,
                      lens=lens,
                      latitude=latitude,
                      longitude=longitude,
                      altitude=metadata.get('GPS Altitude')
                      and metadata.get('GPS Altitude').split(' ')[0])
        photo.save()

    width = metadata.get('Image Width')
    height = metadata.get('Image Height')
    if metadata.get('Orientation') in [
            'Rotate 90 CW', 'Rotate 270 CCW', 'Rotate 90 CCW', 'Rotate 270 CW'
    ]:
        old_width = width
        width = height
        height = old_width

    # Save PhotoFile
    photo_file.photo = photo
    photo_file.path = path
    photo_file.width = width
    photo_file.height = height
    photo_file.mimetype = mimetypes.guess_type(path)[0]
    photo_file.file_modified_at = file_modified_at
    photo_file.bytes = os.stat(path).st_size
    photo_file.preferred = False  # TODO
    photo_file.save()

    # Create task to ensure JPEG version of file exists (used for thumbnailing, analysing etc.)
    Task(type='ensure_raw_processed',
         subject_id=photo.id,
         complete_with_children=True).save()

    return photo
예제 #15
0
    def __init__(
        self,
        amount: Optional[Union[MoneyType, Decimal, Dict, int, float, str, object]] = None,
        currency: Optional[Union[DefaultCurrencyValue, CurrencyValue, str]] = DefaultCurrency,
        from_sub_units: Optional[bool] = None,
        units: Optional[int] = None,
        nanos: Optional[int] = None,
        value: Optional[Union[MoneyType, Decimal, int, float, str]] = None,
        currency_code: Optional[str] = None,
        **kwargs: Any,
    ) -> None:
        validate_amounts = []

        if units is not None or nanos is not None:
            try:
                units = units or 0
                nanos = nanos or 0
                if (units > 0 and nanos < 0) or (units < 0 and nanos > 0):
                    raise ValueError
                units_str = str(units).lstrip("-")
                nanos_str = str(nanos).lstrip("-").rjust(NANOS_LENGTH, "0")
                if len(units_str) > UNITS_MAX_LENGTH:
                    raise ValueError
                if len(nanos_str) != NANOS_LENGTH:
                    raise ValueError
                sign = "-" if nanos < 0 or units < 0 else ""
                new_decimal = Decimal(f"{sign}{units_str}.{nanos_str}")
                if amount is None:
                    amount = new_decimal
                else:
                    validate_amounts.append(new_decimal)
            except Exception:
                raise ConversionError("Invalid values for 'units' and 'nanos'")

        if value is not None:
            try:
                new_amount = cast(MoneyType, self.__class__(value))
                if currency_code is None:
                    currency_code = new_amount.currency_code
                elif new_amount.currency_code and new_amount.currency_code != currency_code:
                    raise ConversionError("Invalid value for 'value'")
                if amount is None:
                    amount = new_amount
                else:
                    validate_amounts.append(new_amount.amount)
            except Exception:
                raise ConversionError("Invalid value for 'value'")

        if amount is not None and isinstance(amount, Dict):
            amount = self.__class__.from_dict(amount)

        if amount is None:
            raise ConversionError("Missing input values for monetary amount")

        if currency is DefaultCurrency and currency_code:
            if not isinstance(currency_code, str):
                raise ConversionError("Invalid 'currency_code' value, must be string")
            currency = str(currency_code)
        elif currency is not DefaultCurrency and currency_code and str(currency) != str(currency_code):
            raise ConversionError("Invalid 'currency' value, does not match 'currency_code'")

        if (
            isinstance(amount, Money)
            and currency is DefaultCurrency
            and from_sub_units is None
            and units is None
            and nanos is None
        ):
            object.__setattr__(self, "_amount", amount._amount)
            object.__setattr__(self, "_currency", amount._currency)
            return

        if (
            currency is not DefaultCurrency
            and not isinstance(currency, str)
            and not isinstance(currency, BaseCurrencyType)
            and currency is not None
        ):
            raise ConversionError("Invalid 'currency' value")

        output_amount = None
        output_currency: Optional[Union[CurrencyValue, str]] = None
        if currency is not DefaultCurrency:
            if isinstance(currency, BaseCurrencyType):
                output_currency = currency
            else:
                output_currency = str(currency or "").strip() or None
                output_currency = (
                    output_currency.upper() if output_currency and len(output_currency) == 3 else output_currency
                )

        if amount is not None and (
            (isinstance(amount, str) and len(amount) > 1 and amount[0] == "{")
            or (isinstance(amount, bytes) and len(amount) > 1 and amount[0] == 123)
        ):
            try:
                amount = str(self.__class__.from_dict(json.loads(amount)))
            except Exception:
                pass

        if amount is not None and isinstance(amount, bytes):
            try:
                amount = MoneyProtobufMessage.FromString(amount)
            except Exception:
                pass

        if amount is not None and isinstance(amount, GenericProtobufMessage):
            amount = str(
                self.__class__.from_dict(
                    {
                        k: getattr(amount, k)
                        for k in (
                            "value",
                            "units",
                            "nanos",
                            "amount",
                            "currency",
                            "currency_code",
                            "from_sub_units",
                        )
                        if hasattr(amount, k)
                    }
                )
            )

        if Money._is_unknown_amount_type(amount):
            try:
                match_amount = getattr(amount, "amount")
                match_amount = (match_amount()) if match_amount and callable(match_amount) else match_amount
                if match_amount is None or Money._is_unknown_amount_type(match_amount):
                    raise AttributeError

                match_currency = None
                try:
                    match_currency = getattr(amount, "currency")
                    match_currency = (
                        (match_currency()) if match_currency and callable(match_currency) else match_currency
                    )
                    if not match_currency:
                        raise AttributeError
                except AttributeError:
                    matches = re.match(r"^(?:[-+]?[0-9.]+)[ ]+([a-zA-Z]+)$", str(amount))
                    if not matches:
                        matches = re.match(r"^([a-zA-Z]+)[ ]+(?:[-+]?[0-9.]+)$", str(amount))
                    if matches:
                        match_currency = matches.group(1)

                if match_currency is not None:
                    match_currency = str(match_currency).strip()
                    match_currency = (
                        match_currency.upper()
                        if match_currency and isinstance(match_currency, str) and len(match_currency) == 3
                        else match_currency
                    )
                    if output_currency is not None and match_currency != output_currency:
                        raise ConversionError("Mismatching currency in input value and 'currency' argument")
                    output_currency = (
                        output_currency if isinstance(output_currency, BaseCurrencyType) else match_currency
                    )

                amount = match_amount
            except AttributeError:
                amount = str(amount)

        if amount is not None and isinstance(amount, int) and not isinstance(amount, bool):
            output_amount = Decimal(amount)
        elif amount is not None and isinstance(amount, float):
            output_amount = Decimal(str(amount))
        elif amount is not None and isinstance(amount, str) and amount.strip():
            amount = amount.strip()
            match_currency = None

            matches = re.match(r"^(?P<amount>[-+]?[0-9.]+)[ ]+(?P<currency>[a-zA-Z]+)$", amount)
            if not matches:
                matches = re.match(r"^(?P<currency>[a-zA-Z]+)[ ]+(?P<amount>[-+]?[0-9.]+)$", amount)
            if matches:
                amount = matches.group("amount").strip()
                match_currency = matches.group("currency").strip()
                match_currency = (
                    match_currency.upper()
                    if match_currency and isinstance(match_currency, str) and len(match_currency) == 3
                    else match_currency
                )

            if match_currency is not None:
                if output_currency is not None and match_currency != output_currency:
                    raise ConversionError("Mismatching currency in input value and 'currency' argument")
                output_currency = output_currency if isinstance(output_currency, BaseCurrencyType) else match_currency

            try:
                output_amount = Decimal(amount)
            except Exception:
                raise ConversionError("Input value cannot be used as monetary amount")
        elif amount is not None and isinstance(amount, Money):
            if amount.currency and not output_currency and currency is DefaultCurrency:
                output_currency = amount.currency

            output_amount = amount._amount
        elif amount is not None and isinstance(amount, Decimal):
            output_amount = amount

        if output_amount is None:
            raise ConversionError("Missing input values for monetary amount")

        if output_amount.is_infinite():
            raise ConversionError("Monetary amounts cannot be infinite")

        if output_amount.is_nan():
            raise ConversionError("Input amount is not a number")

        if from_sub_units:
            if output_currency and isinstance(output_currency, BaseCurrencyType):
                if output_currency.decimal_digits != 0:
                    output_amount = output_amount / Decimal(pow(10, output_currency.decimal_digits))
            else:
                output_amount = output_amount / 100

        if output_amount > Decimal(HIGHEST_SUPPORTED_AMOUNT):
            raise ConversionError(f"Input amount is too high, max value is {HIGHEST_SUPPORTED_AMOUNT}")

        if output_amount < Decimal(LOWEST_SUPPORTED_AMOUNT):
            raise ConversionError(f"Input amount is too low, min value is {LOWEST_SUPPORTED_AMOUNT}")

        if output_currency and not re.match(r"^[A-Za-z]+$", str(output_currency)):
            raise ConversionError("Invalid 'currency' or 'currency_code'")

        if output_amount == 0 and output_amount.is_signed():
            output_amount = Decimal(0)

        if any([output_amount != a for a in validate_amounts]):
            raise ConversionError("Values in input arguments does not match")

        object.__setattr__(self, "_amount", output_amount)
        object.__setattr__(self, "_currency", output_currency)
def step_gradient(k1_current, k2_current, k3_current, points, learningRate):
    decimal.setcontext(decimal.Context(prec=10))
    k1_gradient = decimal.Decimal(0.0)
    k2_gradient = decimal.Decimal(0.0)
    k3_gradient = decimal.Decimal(0.0)
    N = decimal.Decimal( float(len(points)) )
    for i in range(0, len(points)):
        x = decimal.Decimal( points[i, 0] )
        y = decimal.Decimal( points[i, 1] )
        
        try:
            common_part_1 = -(2/N) * (y - (k1_current + k2_current * x) ** k3_current)
        except Exception as e:
            print('Exception #1')
            print('(y - (k1_current + k2_current * x)) : ', (y - (k1_current + k2_current * x)))
            print('k3_current : ', k3_current)
            
        try:
            common_part_2 = (k3_current * (k1_current + k2_current * x) ** (k3_current - 1))
        except Exception as e:
            print('Exception #2')
            print('x : ', x)
            print('k3_current - 1 : ', (k3_current - 1))
            print('k3_current * (k1_current + k2_current * x) : ', (k3_current * (k1_current + k2_current * x)))
            
        try:
            common_part_3 = decimal.Decimal.ln( k1_current + k2_current * x)
        except Exception as e:
            print('Exception #3')
            print('x : ', x)
            print('k1_current + k2_current * x : ', (k1_current + k2_current * x))
            
        try:
            common_part_4 = (k1_current + k2_current * x) ** k3_current
        except Exception as e:
            print('Exception #4')
            print('x : ', x)
            print('k3_current : ', k3_current)
            print('k1_current + k2_current * x : ', (k1_current + k2_current * x))
        
#         common_part_1 = -(2/N) * (y - (k1_current + k2_current * x) ** k3_current)
#         common_part_2 = (k3_current * (k1_current + k2_current * x) ** (k3_current - 1))
#         common_part_3 = decimal.Decimal.ln( k1_current + k2_current * x)
#         common_part_4 = (k1_current + k2_current * x) ** k3_current
        k1_gradient += common_part_1 * common_part_2
        k2_gradient += common_part_1 * common_part_2 * x
        k3_gradient += common_part_1 * common_part_3 * common_part_4
        
#         k1_gradient += -(2/N) * (y - (k1_current + k2_current * x) ** k3_current) * (k3_current * (k1_current + k2_current * x) ** (k3_current - 1))
#         k2_gradient += -(2/N) * (y - (k1_current + k2_current * x) ** k3_current) * (k3_current * (k1_current + k2_current * x) ** (k3_current - 1)) * x
#         k3_gradient += -(2/N) * (y - (k1_current + k2_current * x) ** k3_current) * np.log(k1_current + k2_current * x) * (k1_current + k2_current * x) ** k3_current
        if(dc.is_nan(k1_gradient) or dc.is_nan(k2_gradient) or dc.is_nan(k1_gradient) or
           dc.is_infinite(k1_gradient) or dc.is_infinite(k2_gradient) or dc.is_infinite(k1_gradient)): 
            print('   i=', i)
            print('   x = ', x, ',  y = ', y)
            print('   comPart_2_1 = ', (k3_current * (k1_current + k2_current * x)))
            print('   comPart_2_2 = ', (k3_current - 1))
            print('   comPart_2_3 = ', k3_current * (k1_current + k2_current * x) ** (k3_current - 1))
            print('   k1_cur=', k1_current, '  k2_cur=', k2_current, '  k3_cur=', k3_current)
            print('   common_part_1 = ', common_part_1)
            print('   common_part_2 = ', common_part_2)
            print('   common_part_3 = ', common_part_3)
            print('   k1_gradient = ', k1_gradient)
            print('   k2_gradient = ', k2_gradient) 
            print('   k3_gradient = ', k3_gradient, '\n')
            k1_gradient = 1001.0
            break
        
    new_k1 = k1_current - (learningRate * k1_gradient)
    new_k2 = k2_current - (learningRate * k2_gradient)
    new_k3 = k3_current - (learningRate * k3_gradient)
    return [new_k1, new_k2, new_k3, k1_gradient, k2_gradient, k3_gradient]
예제 #17
0
    def __init__(
        self,
        amount: Optional[Union["Money", Decimal, int, float, str,
                               object]] = None,
        currency: Optional[Union[Type[DefaultCurrency], Currency,
                                 str]] = DefaultCurrency,
        is_cents: Optional[bool] = None,
        units: Optional[int] = None,
        nanos: Optional[int] = None,
        **kwargs: Any,
    ) -> None:
        validate_amounts = []

        if units is not None or nanos is not None:
            try:
                units = units or 0
                nanos = nanos or 0
                if (units > 0 and nanos < 0) or (units < 0 and nanos > 0):
                    raise ValueError
                units_str = str(units).lstrip("-")
                nanos_str = str(nanos).lstrip("-").rjust(NANOS_LENGTH, "0")
                if len(units_str) > UNITS_MAX_LENGTH:
                    raise ValueError
                if len(nanos_str) != NANOS_LENGTH:
                    raise ValueError
                sign = "-" if nanos < 0 or units < 0 else ""
                new_amount = Decimal(f"{sign}{units_str}.{nanos_str}")
                if amount is None:
                    amount = new_amount
                else:
                    validate_amounts.append(new_amount)
            except Exception:
                raise ConversionError("Invalid values for units and nanos")

        if amount is None:
            raise ConversionError("Missing input values for monetary amount")

        if (isinstance(amount, Money) and currency is DefaultCurrency
                and is_cents is None and units is None and nanos is None):
            object.__setattr__(self, "_amount", amount._amount)
            object.__setattr__(self, "_currency", amount._currency)
            return

        if (currency is not DefaultCurrency and not isinstance(currency, str)
                and not isinstance(currency, Currency)
                and currency is not None):
            raise ConversionError("Invalid currency value")

        output_amount = None
        output_currency: Optional[Union[Currency, str]] = None
        if currency is not DefaultCurrency:
            if isinstance(currency, Currency):
                output_currency = currency
            else:
                output_currency = str(currency or "").strip().upper() or None

        if Money._is_unknown_amount_type(amount):
            try:
                match_amount = getattr(amount, "amount")
                match_amount = (match_amount(
                )) if match_amount and callable(match_amount) else match_amount
                if match_amount is None or Money._is_unknown_amount_type(
                        match_amount):
                    raise AttributeError

                match_currency = None
                try:
                    match_currency = getattr(amount, "currency")
                    match_currency = ((match_currency()) if match_currency
                                      and callable(match_currency) else
                                      match_currency)
                    if not match_currency:
                        raise AttributeError
                except AttributeError:
                    matches = re.match(r"^(?:[-+]?[0-9.]+)[ ]+([a-zA-Z]+)$",
                                       str(amount))
                    if not matches:
                        matches = re.match(
                            r"^([a-zA-Z]+)[ ]+(?:[-+]?[0-9.]+)$", str(amount))
                    if matches:
                        match_currency = matches.group(1)

                if match_currency is not None:
                    match_currency = str(match_currency).strip().upper()
                    if output_currency is not None and match_currency != output_currency:
                        raise ConversionError(
                            "Mismatching currency in input value and currency argument"
                        )
                    output_currency = output_currency if isinstance(
                        output_currency, Currency) else match_currency

                amount = match_amount
            except AttributeError:
                amount = str(amount)

        if amount is not None and isinstance(
                amount, int) and not isinstance(amount, bool):
            output_amount = Decimal(amount)
        elif amount is not None and isinstance(amount, float):
            output_amount = Decimal(str(amount))
        elif amount is not None and isinstance(amount, str) and amount.strip():
            amount = amount.strip()
            match_currency = None

            matches = re.match(
                r"^(?P<amount>[-+]?[0-9.]+)[ ]+(?P<currency>[a-zA-Z]+)$",
                amount)
            if not matches:
                matches = re.match(
                    r"^(?P<currency>[a-zA-Z]+)[ ]+(?P<amount>[-+]?[0-9.]+)$",
                    amount)
            if matches:
                amount = matches.group("amount").strip()
                match_currency = matches.group("currency").strip().upper()

            if match_currency is not None:
                if output_currency is not None and match_currency != output_currency:
                    raise ConversionError(
                        "Mismatching currency in input value and currency argument"
                    )
                output_currency = output_currency if isinstance(
                    output_currency, Currency) else match_currency

            try:
                output_amount = Decimal(amount)
            except Exception:
                raise ConversionError(
                    "Value cannot be used as monetary amount")
        elif amount is not None and isinstance(amount, Money):
            if amount.currency and not output_currency and currency is not DefaultCurrency:
                output_currency = amount.currency

            output_amount = amount._amount
        elif amount is not None and isinstance(amount, Decimal):
            output_amount = amount

        if output_amount is None:
            raise ConversionError("Missing input values for monetary amount")

        if output_amount.is_infinite():
            raise ConversionError("Monetary amounts cannot be infinite")

        if output_amount.is_nan():
            raise ConversionError("Input amount is not a number")

        if is_cents:
            output_amount = output_amount / 100

        if output_amount > Decimal(HIGHEST_SUPPORTED_AMOUNT):
            raise ConversionError(
                f"Input amount is too high, max value is {HIGHEST_SUPPORTED_AMOUNT}"
            )

        if output_amount < Decimal(LOWEST_SUPPORTED_AMOUNT):
            raise ConversionError(
                f"Input amount is too low, min value is {LOWEST_SUPPORTED_AMOUNT}"
            )

        if output_currency and not re.match(r"^[A-Z]+$", str(output_currency)):
            raise ConversionError("Invalid currency")

        if output_amount == 0 and output_amount.is_signed():
            output_amount = Decimal(0)

        if any([output_amount != a for a in validate_amounts]):
            raise ConversionError("Input arguments does not match")

        object.__setattr__(self, "_amount", output_amount)
        object.__setattr__(self, "_currency", output_currency)
예제 #18
0
# -*- coding: utf-8 -*-
'''
Created on 18 de ene. de 2016

@author: dam2
'''

from decimal import Decimal

fNuml = 3.34  # float o reales usa doble precision
INuml = 3L  # Entero largo como long de C
dNuml = Decimal(fNuml)  # La mayor precision posible
print "    Funciones basicas    "
print dNuml.copy_abs()
print dNuml.is_infinite()
print dNuml.log10()
print dNuml.sqrt()
print dNuml.max(INuml)
print fNuml.hex()  # representacion hexadecimal
print INuml.bit_length()  # bits necesarios para representar el valor