Converts a decimal.Decimal to BID (high bits, low bits).

    :Parameters:
      - `value`: An instance of decimal.Decimal
502925
def _decimal_to_128(value):
    
    with decimal.localcontext(_DEC128_CTX) as ctx:
        value = ctx.create_decimal(value)

    if value.is_infinite():
        return _NINF if value.is_signed() else _PINF

    sign, digits, exponent = value.as_tuple()

    if value.is_nan():
        if digits:
            raise ValueError("NaN with debug payload is not supported")
        if value.is_snan():
            return _NSNAN if value.is_signed() else _PSNAN
        return _NNAN if value.is_signed() else _PNAN

    significand = int("".join([str(digit) for digit in digits]))
    bit_length = _bit_length(significand)

    high = 0
    low = 0
    for i in range(min(64, bit_length)):
        if significand & (1 << i):
            low |= 1 << i

    for i in range(64, bit_length):
        if significand & (1 << i):
            high |= 1 << (i - 64)

    biased_exponent = exponent + _EXPONENT_BIAS

    if high >> 49 == 1:
        high = high & 0x7fffffffffff
        high |= _EXPONENT_MASK
        high |= (biased_exponent & 0x3fff) << 47
    else:
        high |= biased_exponent << 49

    if sign:
        high |= _SIGN

    return high, low
1009145
def value(self) -> Decimal:
        
        assert isinstance(self.price, Decimal)
        
        return self.quantity * self.price
352484
def to_integer(value, ctx):
    
    if isinstance(value, bool):
        return 1 if value else 0
    elif isinstance(value, int):
        return value
    elif isinstance(value, Decimal):
        try:
            val = int(value.to_integral_exact(ROUND_HALF_UP))
            if isinstance(val, int):
                return val
        except ArithmeticError:
            pass
    elif isinstance(value, str):
        try:
            return int(value)
        except ValueError:
            pass

    raise EvaluationError("Can't convert '%s' to an integer" % str(value))
173480
def convert(self, value, param, ctx):  # pylint: disable=inconsistent-return-statements
        """"""
        matches = MEMORY_RE.match(value.lower())
        if matches is None:
            self.fail('%s is not a valid value for memory amount' % value, param, ctx)
        amount_str, unit = matches.groups()
        amount = int(amount_str)
        if unit in [None, 'm', 'mb']:
            # Assume the user intends gigabytes if they specify a number < 1024
            if amount < 1024:
                return amount * 1024
            else:
                if amount % 1024 != 0:
                    self.fail('%s is not an integer that is divisable by 1024' % value, param, ctx)
                return amount
        elif unit in ['g', 'gb']:
            return amount * 1024
365589
def adapt_decimalfield_value(self, value, max_digits, decimal_places):
        
        if value is None:
            return None
        if isinstance(value, decimal.Decimal):
            context = decimal.getcontext().copy()
            context.prec = max_digits
            #context.rounding = ROUND_FLOOR
            return "%.*f" % (decimal_places + 1, value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
        else:
            return "%.*f" % (decimal_places + 1, value)
168439
def _convert_to_boolean(self, value):
        
        if value.lower() not in self.BOOLEAN_STATES:
            raise ValueError('Not a boolean: %s' % value)
        return self.BOOLEAN_STATES[value.lower()]
1121375
def __set_amount(self, value):
        '''
        
        '''
        try:
            self.__amount = quantize(Decimal(str(value)))
        except:
            raise ValueError('Invalid amount value')
1108101
def set_value(self, value: str):
        
        [digit.clear() for digit in self._digits]

        grouped = self._group(value)  # return the parts, reversed
        digits = self._digits[::-1]  # reverse the digits

        # fill from right to left
        has_period = False
        for i, digit_value in enumerate(grouped):
            try:
                if has_period:
                    digits[i].set_value(digit_value + '.')
                    has_period = False

                elif grouped[i] == '.':
                    has_period = True

                else:
                    digits[i].set_value(digit_value)
            except IndexError:
                raise ValueError('the value "{}" contains too '
                                 'many digits'.format(value))
33014
def _send_byte(self,value):
        

        # Coerce to int. This will throw a ValueError if the value can't
        # actually be converted.
        if type(value) != int:
            new_value = int(value)

            if self.give_warnings:
                w = "Coercing {} into int ({})".format(value,new_value)
                warnings.warn(w,Warning)
                value = new_value

        # Range check
        if value > 255 or value < 0:
            err = "Value {} exceeds the size of the board's byte.".format(value)
            raise OverflowError(err)

        return struct.pack("B",value)
1028331
def encode(cls, value):
        
        if value not in [True, False]:
            raise InvalidValue('not a boolean')

        return b'1' if value else b''
730238
def encode_value(value, flags=None, base64=False):
    
    if flags:
        # still a no-operation
        logger.debug("Flag %s encoding not implemented yet" % flags)
    if not isinstance(value, bytes):
        raise ValueError("value must be bytes")
    return b64encode(value) if base64 else value
178082
def to_decimal(value, ctx):
    
    if isinstance(value, bool):
        return Decimal(1) if value else Decimal(0)
    elif isinstance(value, int):
        return Decimal(value)
    elif isinstance(value, Decimal):
        return value
    elif isinstance(value, str):
        try:
            return Decimal(value)
        except Exception:
            pass

    raise EvaluationError("Can't convert '%s' to a decimal" % str(value))
236324
def format_price(self, price):
        
        # ensure we have a float
        price = api.to_float(price, default=0.0)
        dm = self.get_decimal_mark()
        cur = self.get_currency_symbol()
        price = "%s %.2f" % (cur, price)
        return price.replace(".", dm)
359866
def convert(self, value, param, ctx):
        
        value = super(PositiveInt, self).convert(value, param, ctx)
        if value < 0:
            self.fail('%s is not positive' % value, param, ctx)
        if not self.allow_zero and not value:
            self.fail('%s is not greater than 0' % value, param, ctx)
        return value
804003
def convert(self, value, param, ctx):
        
        self.gandi = ctx.obj
        # remove deprecated * prefix
        choices = [choice.replace('*', '') for choice in self.choices]
        value = value.replace('*', '')
        # Exact match
        if value in choices:
            return value

        # Try to find 64 bits version
        new_value = '%s 64 bits' % value
        if new_value in choices:
            return new_value

        # Try to find without specific bits version
        p = re.compile(' (64|32) bits')
        new_value = p.sub('', value)
        if new_value in choices:
            return new_value

        self.fail('invalid choice: %s. (choose from %s)' %
                  (value, ', '.join(self.choices)), param, ctx)
691129
def _bit_value(self, group, val):
        """"""
        bitshift = group - 1
        if val:
            new_value = self._value | (1 << bitshift)
        else:
            new_value = self._value & (0xff & ~(1 << bitshift))
        return new_value
508942
def put_bits( self, value, count ):
        
        for _ in range( count ):

            # bits are retrieved from the source LSB first
            bit = (value & 1)
            value >>= 1

            # however, bits are put into the result based on the rule
            if self.bits_reverse:
                if self.insert_at_msb:
                    self.current_bits |= (bit << (self.bits_remaining-1))
                else:
                    self.current_bits <<= 1
                    self.current_bits |= bit
            else:
                if self.insert_at_msb:
                    self.current_bits >>= 1
                    self.current_bits |= (bit << 7)
                else:
                    self.current_bits |= (bit << (8-self.bits_remaining))

            self.bits_remaining -= 1
            if self.bits_remaining <= 0:
                self.output.append( self.current_bits )

                self.current_bits = 0
                self.bits_remaining = 8