Example #1
0
def float2decimal(fval):
    """ Convert a floating point number to a Decimal with no loss of
        information
    """
    # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
    # exponent.  Double the mantissa until it is an integer.  Use the integer
    # mantissa and exponent to compute an equivalent Decimal.  If this cannot
    # be done exactly, then retry with more precision.
    #
    # This routine is from
    # http://docs.python.org/release/2.5.2/lib/decimal-faq.html

    mantissa, exponent = math.frexp(fval)
    try:
        while mantissa != int(mantissa):
            mantissa *= 2.0
            exponent -= 1
        mantissa = int(mantissa)
    except (OverflowError, ValueError):
        return "---"

    oldcontext = decimal.getcontext()
    decimal.setcontext(decimal.Context(traps=[decimal.Inexact]))
    try:
        while True:
            try:
                return mantissa * decimal.Decimal(2) ** exponent
            except decimal.Inexact:
                decimal.getcontext().prec += 1
    finally:
        decimal.setcontext(oldcontext)
Example #2
0
def decpi(memo={}):
    """Compute Pi to the current precision.

    >>> print pi()
    3.141592653589793238462643383

    Taken from the Python Decimal documentation and memoized.
    """
    prec = getcontext().prec
    pi = memo.get(prec, None)

    if pi is not None:
        return pi

    getcontext().prec += 2  # extra digits for intermediate steps
    three = Decimal(3)      # substitute "three=3.0" for regular floats
    lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
    while s != lasts:
        lasts = s
        n, na = n+na, na+8
        d, da = d+da, da+32
        t = (t * n) / d
        s += t
    getcontext().prec -= 2
    pi = +s                 # unary plus applies the new precision

    memo[prec] = pi
    return pi
Example #3
0
File: io.py Project: apache/avro
  def read_decimal_from_fixed(self, precision, scale, size):
    """
    Decimal is encoded as fixed. Fixed instances are encoded using the
    number of bytes declared in the schema.
    """
    datum = self.read(size)
    unscaled_datum = 0
    msb = struct.unpack('!b', datum[0])[0]
    leftmost_bit = (msb >> 7) & 1
    if leftmost_bit == 1:
      modified_first_byte = ord(datum[0]) ^ (1 << 7)
      datum = chr(modified_first_byte) + datum[1:]
      for offset in range(size):
        unscaled_datum <<= 8
        unscaled_datum += ord(datum[offset])
      unscaled_datum += pow(-2, (size*8) - 1)
    else:
      for offset in range(size):
        unscaled_datum <<= 8
        unscaled_datum += ord(datum[offset])

    original_prec = getcontext().prec
    getcontext().prec = precision
    scaled_datum = Decimal(unscaled_datum).scaleb(-scale)
    getcontext().prec = original_prec
    return scaled_datum
Example #4
0
def dms2decimal(degrees, minutes, seconds):
    """ Converts degrees, minutes, and seconds to the equivalent
    number of decimal degrees. If parameter 'degrees' is negative,
    then returned decimal-degrees will also be negative.

    NOTE: this method returns a decimal.Decimal

    Example:

        >>> dms2decimal(121, 8, 6)
        Decimal('121.135')
        >>> dms2decimal(-121, 8, 6)
        Decimal('-121.135')

    """
    decimal = D(0)
    degs = D(str(degrees))
    mins = libdecimal.getcontext().divide(D(str(minutes)), D(60))
    secs = libdecimal.getcontext().divide(D(str(seconds)), D(3600))

    if degrees >= D(0):
        decimal = degs + mins + secs
    else:
        decimal = degs - mins - secs

    return libdecimal.getcontext().normalize(decimal)
Example #5
0
def f0():
    print("--- f0 ---")

    import decimal as dec
    dec.getcontext().prec = 110
    dec.getcontext().rounding = dec.ROUND_DOWN

    Nmax = 100
    
    # Find all squares up to Nmax:
    i = 1
    squares = []
    while i*i < Nmax + 1:
        squares.append(i*i)
        i += 1

    # Loop over all sqrts, and add decimals as requested:
    total = 0
    for N in range(1,Nmax+1):
        if not N in squares:
            N = dec.Decimal(N)
            s = N.sqrt()
            s = s*10**100
            s = str(s)[:100]
            s = sum([ int(x) for x in s ])

            total += s

    # Final result:
    print(total)
    def _minimum_variable_cost(self, average_orders, reorder_cost, unit_cost) -> Decimal:
        getcontext().prec = 2
        getcontext().rounding = ROUND_HALF_UP
        holding_cost = self.__holding_cost

        step = float(0.2)
        previous_eoq_variable_cost = Decimal(0)

        Decimal(reorder_cost)
        order_factor = float(0.002)
        vc = 0.00
        counter = 0
        order_size = 0
        while previous_eoq_variable_cost >= Decimal(vc):

            previous_eoq_variable_cost = Decimal(vc)
            # reorder cost * average demand all divided by order size + (demand size * holding cost)
            if counter < 1:
                order_size = self._order_size(average_orders=average_orders, reorder_cost=reorder_cost,
                                              unit_cost=unit_cost, holding_cost=holding_cost,
                                              order_factor=order_factor)

            vc = self._variable_cost(float(average_orders), float(reorder_cost), float(order_size), float(unit_cost), float(holding_cost))

            order_size += int(float(order_size) * step)
            if counter < 1:
                previous_eoq_variable_cost = Decimal(vc)

            while counter == 0:
                counter += 1
        return Decimal(previous_eoq_variable_cost)
Example #7
0
def float_hex_2_float(str_pi_hex_digits, precisao) -> decimal:
    getcontext().prec = precisao
    getcontext().rounding = ROUND_FLOOR
    mypi10 = decimal(0)
    for i in range(len(str_pi_hex_digits)-1, -1, -1):
        mypi10 += decimal(int(str_pi_hex_digits[i], base=16) * 16 ** -i)
    return mypi10
Example #8
0
    def float_to_decimal(f):
        "Convert a floating point number to a Decimal with no loss of information"
        # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
        # exponent.  Double the mantissa until it is an integer.  Use the integer
        # mantissa and exponent to compute an equivalent Decimal.  If this cannot
        # be done exactly, then retry with more precision.

        try:
            mantissa, exponent = math.frexp(f)
        except OverflowError:
            return decimal.Inf

        while mantissa != int(mantissa):
            mantissa *= 2.0
            exponent -= 1
        mantissa = int(mantissa)

        oldcontext = decimal.getcontext()
        decimal.setcontext(decimal.Context(traps=[decimal.Inexact]))
        try:
            while True:
                try:
                    return mantissa * decimal.Decimal(2) ** exponent
                except decimal.Inexact:
                    decimal.getcontext().prec += 1
        finally:
            decimal.setcontext(oldcontext)
def convert_interest_rate(new_comp_period, interest_rate):
	getcontext().prec = InterestRate.DEFAULT_PRECISION

	old_rate = 1 + interest_rate.periodic_interest_rate
	e = Decimal(interest_rate.compounding_period / new_comp_period)

	return getcontext().power(old_rate, e) - 1
Example #10
0
def cos(x):
    """Return the cosine of x as measured in radians.

    >>> print cos(Decimal('0.5'))
    0.8775825618903727161162815826
    >>> print cos(0.5)
    0.87758256189
    >>> print cos(0.5+0j)
    (0.87758256189+0j)

    """
    x = Decimal(str(x)) % (2 * _pi())
    if isnan(x):
        return Decimal('NaN')
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i - 1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s
Example #11
0
def acos(x):
    """Return the arc cosine (measured in radians) of Decimal x."""
    x = Decimal(str(x))

    if abs(x) > 1:
        raise ValueError("Domain error: acos accepts -1 <= x <= 1")

    if x == -1:
        return _pi()
    elif x == 0:
        return _pi() / 2
    elif x == 1:
        return Decimal(0)

    getcontext().prec += 2
    one_half = Decimal('0.5')
    i, lasts, s, gamma, fact, num = Decimal(0), 0, _pi() / 2 - x, 1, 1, x
    while s != lasts:
        lasts = s
        i += 1
        fact *= i
        num *= x * x
        gamma *= i - one_half
        coeff = gamma / ((2 * i + 1) * fact)
        s -= coeff * num
    getcontext().prec -= 2
    return +s
Example #12
0
def sin(x):
    """Return the sine of x as measured in radians.

    >>> print sin(Decimal('0.5'))
    0.4794255386042030002732879352
    >>> print sin(0.5)
    0.479425538604
    >>> print sin(0.5+0j)
    (0.479425538604+0j)

    """
    x = Decimal(str(x)) % (2 * _pi())
    if isnan(x):
        return Decimal('NaN')
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i - 1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s
Example #13
0
def PHI(n=2):
	''' PHI(int) -> Decimal -- returns (1+√5)/2 to int precision, increasing the precision of Decimal if required'''
	from decimal import getcontext,Decimal
	if n > getcontext().prec:
		getcontext().prec = n
	s5 = Decimal(5).sqrt()
	return (1 + s5)/2
Example #14
0
def atan(x):
    """Return the arc tangent (measured in radians) of Decimal x."""
    x = Decimal(str(x))

    if x == Decimal('-Inf'):
        return _pi() / -2
    elif x == 0:
        return Decimal(0)
    elif x == Decimal('Inf'):
        return _pi() / 2

    if x < -1:
        c = _pi() / -2
        x = 1 / x
    elif x > 1:
        c = _pi() / 2
        x = 1 / x
    else:
        c = 0

    getcontext().prec += 2
    x_squared = x ** 2
    y = x_squared / (1 + x_squared)
    y_over_x = y / x
    i, lasts, s, coeff, num = Decimal(0), 0, y_over_x, 1, y_over_x
    while s != lasts:
        lasts = s
        i += 2
        coeff *= i / (i + 1)
        num *= y
        s += coeff * num
    if c:
        s = c - s
    getcontext().prec -= 2
    return +s
Example #15
0
    def _trade_budget(self, sum_, offers):
        """
        Calculates maximum volume purchasabale with given money sum and offers.
        Usable for both sell and buy offers.
        :param amount: int or float
        :param offers: list of lists in format [price, vol, timestamp]
        :return: float
        """
        d = decimal.Decimal
        decimal.getcontext().prec = 8
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        wallet = d(sum_)
        basket = d(0.0)
        for offer in offers:
            p = d(offer[0]) # convert string to float
            vol = d(offer[1]) # convert string to float
            if wallet > 0.0:
                if p * vol <= wallet:
                    wallet -= p * vol
                    basket += vol
                elif p * vol > wallet:
                    basket += wallet / p
                    wallet -= wallet

        return float(basket)
Example #16
0
 def _trade_vol(self, amount, offers):
     """
     Calculates total price for given amount and offers. Can be used to calc
     sell or buy price.
     :param pair: str
     :param amount: float or int
     :param bids: list of lists format[price, vol, timestamp]
     :return:
     """
     d = decimal.Decimal
     decimal.getcontext().prec = 8
     decimal.getcontext().rounding = decimal.ROUND_DOWN
     basket = d(0.0)
     left_to_trade = d(amount)
     total = d(0.0)
     for offer in offers:
         p = d(offer[0])
         vol = d(offer[1])
         if left_to_trade > d(0.0):
             if vol > left_to_trade:
                 total += left_to_trade * p
                 left_to_trade -= left_to_trade
             elif vol < amount:
                 left_to_trade -= vol
                 total += vol * p
     return float(total)
Example #17
0
    def from_decimal(self, decimal_degrees, hemisphere = ''):
        degrees = D(int(decimal_degrees))

        decimal_minutes = libdecimal.getcontext().multiply((D(str(decimal_degrees)) - degrees).copy_abs(), D(60))
        minutes = D(int(decimal_minutes))
        seconds = libdecimal.getcontext().multiply((decimal_minutes - minutes), D(60))

        return DMSCoordinate(degrees, minutes, seconds, hemisphere)
Example #18
0
def decimals_integers_division (number1=decimal.Decimal(), number2=0):
    if number1 == decimal.Decimal() or number2 == 0:
        number1 = generate_decimal(4,99)
        number2 = random.randint (4,9)
    original_precision = decimal.getcontext().prec
    decimal.getcontext().prec=5
    answer = number1 / number2
    decimal.getcontext().prec = original_precision
    question = "{} divided by {} = ______".format (number1, number2)
    return (question, answer)
 def __init__(self, reorder_quantity: float, holding_cost: float, reorder_cost: float, average_orders: float,
              unit_cost: float, total_orders: float):
     getcontext().prec = 2
     getcontext().rounding = ROUND_HALF_UP
     self.__reorder_quantity = Decimal(reorder_quantity)
     self.__holding_cost = holding_cost
     self.__reorder_cost = reorder_cost
     self.__unit_cost = unit_cost
     self.__min_variable_cost = minimum_variable_cost(total_orders, reorder_cost, unit_cost, holding_cost)
     self.__economic_order_quantity = economic_order_quantity(total_orders, reorder_cost, unit_cost,holding_cost, reorder_quantity)
Example #20
0
def integers_decimals_division (number1=0, number2= decimal.Decimal()):
    if number1 == 0 or number2 == decimal.Decimal():
        number1 = random.randint (19, 300)
        number2 = generate_decimal(9,9)
    original_precision = decimal.getcontext().prec
    decimal.getcontext().prec=4
    answer = number1 / number2
    decimal.getcontext().prec = original_precision
    question = "{} divided by {} = ______".format (number1, number2)
    return (question, answer)
Example #21
0
def binary_to_decimal(man, exp, n):
    """Represent as a decimal string with at most n digits"""
    import decimal
    prec_ = decimal.getcontext().prec
    decimal.getcontext().prec = n
    if exp >= 0: d = decimal.Decimal(man) * (1<<exp)
    else:        d = decimal.Decimal(man) / (1<<-exp)
    a = str(d)
    decimal.getcontext().prec = prec_
    return a
Example #22
0
 def product_tax_calculator(self, tax_rate):
     """ Return product final price based on the provided `tax_rate`
     Decimal module used for precision and rounding purposes
     """
     #setup decimal context
     getcontext().prec = 4
     getcontext().round = ROUND_HALF_EVEN
     total = Decimal(self.price) * Decimal(tax_rate)
     self.product_tax = round_nearest(total.__float__())
     return round(float(self.price) + self.product_tax, 2)
Example #23
0
def _prec(stack, arg):
    """set or query precision in digits"""
    if arg is not None and arg.strip():
        decimal.getcontext().prec = int(arg.strip())

        for i, v in enumerate(stack):
            if isinstance(v, Decimal) or isinstance(v, ComplexDec):
                stack[i] = v.normalize()
    else:
        stack.append(Decimal(decimal.getcontext().prec))
Example #24
0
def decimals_division (number1=decimal.Decimal(), number2=decimal.Decimal()):
    if number1 == decimal.Decimal() or number2 == decimal.Decimal():
        number1 = generate_decimal(99,9999)
        number2 = generate_decimal(9,99)
    current_precision = decimal.getcontext().prec
    decimal.getcontext().prec = 6
    answer = number1 / number2
    decimal.getcontext().prec = current_precision
    question = "Divide {} by {}. Stop the division at 4 places after decimal point.".format (number1, number2)
    return (question, answer)
Example #25
0
def arccos_d(x):
    """
    Returns the inverse sine of x as measured in radians.
    """
    
    dp.getcontext().prec += 2
    ac = pi / dp.Decimal('2') - arcsin_d(x)
    dp.getcontext().prec -= 2

    return ac
Example #26
0
 def rule_coordinate_pair(self, next_val_fn, token):
     # Inline these since this rule is so common.
     if token[0] not in self.number_tokens:
         raise SyntaxError("expecting a number; got %r" % (token,))
     x = getcontext().create_decimal(token[1])
     token = next_val_fn()
     if token[0] not in self.number_tokens:
         raise SyntaxError("expecting a number; got %r" % (token,))
     y = getcontext().create_decimal(token[1])
     token = next_val_fn()
     return [x, y], token
Example #27
0
File: dms.py Project: ElecProg/MPL
 def _pi(self):
     getcontext().prec += 2
     lasts, t, s, n, na, d, da = 0, Decimal(3), 3, 1, 0, 0, 24
     while s != lasts:
         lasts = s
         n, na = n + na, na + 8
         d, da = d + da, da + 32
         t = (t * n) / d
         s += t
     getcontext().prec -= 2
     return +s
def pi(n=None):
    ''' Estimate pi using n terms of the Chudnovsky brothers' formula. By 
    default this will attempt to calculate it to the maximum number of digits 
    storable in a decimal number. '''
    from math import factorial
    D = Decimal
    if n == None: n = round(getcontext().prec/D(14)) + 10
    with localcontext():
        getcontext().prec += 5
        f = lambda k: factorial(6*k)*D(13591409 + 545140134*k)\
            / (factorial(3*k)*factorial(k)**3*D(-640320)**(3*k))
        return 426880*D(10005)**D('0.5') / sum(f(k) for k in range (100))
def pi(context=None):
    """Compute Pi to the current precision."""
    getcontext().prec += 2
    lasts = 0; t = D(3); s = 3; n = 1; na = 0; d = 0; da = 24
    while s != lasts:
        lasts = s
        n, na = n + na, na + 8
        d, da = d + da, da + 32
        t = (t * n) / d
        s += t
    getcontext().prec -= 2
    return +s
def load_calc(places=100):
    old_result = None
    getcontext().prec = 2*places
    for n in range(10*places):
        getcontext().prec = 2*places
        result = pi_archimedes(n)
        getcontext().prec = places
        result = +result
        if result == old_result:
            break
        old_result = result
    return result
Example #31
0
 def __init__(self, context=None):
     self.context = context or decimal.getcontext()
Example #32
0
def coverage_measures(all_num, match_num):
    
    # 小数点3桁まで出力
    decimal.getcontext().prec = 3
    coverage = decimal.Decimal(match_num) / decimal.Decimal(all_num)
    return coverage
Example #33
0
__email__ = "*****@*****.**"

# Python 3 compatibility
from six.moves import xrange as range
_IS_PYTHON_3 = sys.version_info[0] == 3
identity = lambda x: x
if _IS_PYTHON_3:
    u = identity
else:
    import codecs

    def u(string):
        return codecs.unicode_escape_decode(string)[0]


getcontext().rounding = ROUND_HALF_EVEN


# Function Library
def GetRewardWeights(M, Rep=-1, Alpha=.1, Verbose=False):
    """Calculates the new reputations using Weighted Principal Components Analysis"""

    if type(Rep) is int:
        Rep = DemocracyCoin(M)

    if Verbose:
        print("****************************************************")
        print("Begin 'GetRewardWeights'")
        print("Inputs...")
        print("Matrix:")
        print(M)
Example #34
0
import click
import csv
from decimal import Decimal, getcontext
import itertools
import numpy as np

getcontext().prec = 4  # Intentionally kept fuzzy to allow learning.
OFFSET_SEQ_DAYS = 5
VALIDATION_RATIO = 0.20  # Fraction of batches to reserve for validation


def get_rows(filename):
    with open(filename, 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            yield row


def count_lines(filename):
    i = 0
    with open(filename, 'r') as file:
        for i, l in enumerate(file, 1):
            continue
    return i


def compute_delta(new, old):
    delta = (Decimal(new) - Decimal(old)) / (Decimal(old) + Decimal(0.0000001))
    return delta

Example #35
0
#        last_char = char
#    return len(num)




#def find_pattern(x):
#    num = str(x)[2:-2]
#    for i in xrange(len(num)-1,-1,-1):
#        if num[i:] == num[i-len(num[i:]):i]:
#            return len(num[i:])
#    return -1
        

        
getcontext().prec = 2000
#0.14285714285714285714285714285714285714285714285714
most = 0
high = 0
num = 0
rval = 0
for i in xrange(11,1001):
#ans = Decimal(1)/Decimal(i)
    num = str(Decimal(1)/Decimal(i))[:-1]
    rval = -1
    for z in xrange(len(num)-1,-1,-1):
        if num[z:] == num[z-len(num[z:]):z]:
            rval = len(num[z:])
            break
    if rval > most:
        most = rval
Example #36
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" 산술 콘텍스트의 정밀도를 변경해보는 예제
    
    pages 465~469; 한글 기준
"""

import decimal

ctx = decimal.getcontext()
ctx.prec = 40
num = decimal.Decimal('1') / decimal.Decimal('3')
print(num)  # 0.3333333333333333333333333333333333333333

print(num == +num)  # True

ctx.prec = 29
print(num == +num)  # False

print(+num)  # 0.33333333333333333333333333333
Example #37
0
 def decimal(b: bytes, precision=16):
     getcontext().prec = precision
     return int(b)
Example #38
0
    return mismatch


# User Input parameters
LOGLEVEL = str(arcpy.GetParameterAsText(0)).upper()
LOGDIR = arcpy.GetParameterAsText(1)
CHECK_PROJ = arcpy.GetParameterAsText(2)  # Boolean result received as text
HAZAREA_FC = arcpy.GetParameterAsText(3)
RIVERS_FC1 = arcpy.GetParameterAsText(4)
RIVERS_FC2 = arcpy.GetParameterAsText(5)
BUFFER_DIST = arcpy.GetParameterAsText(6)  # buffer distance in meters
UPDATE_ONLY = arcpy.GetParameterAsText(7)  # Boolean result received as text

# Tool Parameters
arcpy.env.addOutputsToMap = False
getcontext().prec = 4  # Set decimal precision
REQUIRED_FIELDS = ['RIVERS', 'RIVERS_BUFFER_DIST']
FILTER_FIELD = "RIVERS"  # Which field must we filter on and check for?
RIVERSFEATCLASS_LIST = [
]  # Empty list that will store the feature classes to process
RIVERSFEATLAYER_LIST = []  # Empty list that will store feature layers
# Append the Meters qualifier required for the buffer distance parameter
BUFFER_DISTM = BUFFER_DIST + " Meters"
COUNTER = 0

# Tool configuration:
# Set up the logging parameters and inform the user
DATE_STRING = time.strftime("%Y%m%d")
LOGFILE = unicode(LOGDIR + '\\' + DATE_STRING +
                  '_mcdatool.log').encode('unicode-escape')
MAXBYTES = 10485760  # 10MB
Example #39
0
a = decimal.Decimal('0.1') + decimal.Decimal('0.10') + decimal.Decimal(
    '0.10') - decimal.Decimal('0.30')
print(a)

#it’s also possible to create a decimal object from a floating point object
#conversion is exact but can sometimes yield a large default number of digits, unless they are fixed per the next section:
print(
    decimal.Decimal(0.1) + decimal.Decimal(0.1) + decimal.Decimal(0.1) -
    decimal.Decimal(0.3))  # will output : 2.775557561565156540423631668E-17

# TIP : In Python 3.3 and later, the decimal module was also optimized to improve its performance radically: the reported speedup for the
# new version is 10X to 100X, depending on the type of program benchmarked

# The precision is applied globally for all decimals created in the calling thread
decimal.getcontext(
).prec = 2  #now we will have 2 precession points ! i.e. 0.00 [2 digits after decimal point]
print(
    decimal.Decimal(0.1) + decimal.Decimal(0.1) + decimal.Decimal(0.1) -
    decimal.Decimal(0.3))  #closer to 0, but not 0.00 !

# better to pass on string to Decimal() constructor since passing on floats does not give required results (especially in monetary applications)

#it’s also possible to reset precision temporarily by using the with context manager statement.
# The precision is reset to its original value on statement exit
with decimal.localcontext() as ctx:
    ctx.prec = 5
    print(decimal.Decimal('1.00') / decimal.Decimal('3.00'))

print(decimal.Decimal('1.00') / decimal.Decimal('3.00'))
"""
TOPIC : Fractions
Example #40
0
 def tearDown(self):
     # set up decimal precision to make comparisons easier
     decimal_context = getcontext()
     decimal_context.prec = self.__prev_decimal_prec
Example #41
0
File: util.py Project: smogm/eccoin
def split_transaction(node,
                      prevouts,
                      toAddrs,
                      txfeePer=DEFAULT_TX_FEE_PER_BYTE,
                      **kwargs):
    """
      Create a transaction that divides the sum of all the passed utxos into all the destination addresses
      pass:
           node: (node object) where to send the RPC calls
           prevouts: a single UTXO description dictionary, or a list of them
           toAddrs: a list of strings specifying the output addresses
           "sendtx=False" if you don't want to transaction to be submitted.
      Returns (transaction in hex, Vin list, Vout list)
    """
    if type(prevouts) == type({}):
        prevouts = [
            prevouts
        ]  # If the user passes just one transaction then put a list around it
    txid = None
    inp = []
    decContext = decimal.getcontext().prec
    try:  # try finally block to put the decimal precision back to what it was prior to this routine
        decimal.getcontext(
        ).prec = 8 + 8  # 8 digits to get to 21million, and each bitcoin is 100 million satoshis
        amount = Decimal(0)
        iamount = 0
        count = 0
        for tx in prevouts:
            inp.append({"txid": str(tx["txid"]), "vout": tx["vout"]})
            amount += tx["amount"] * Decimal(BTC)
            iamount += int(tx["amount"] * Decimal(BTC))
            count += 1

        assert (amount == iamount
                )  # make sure Decimal and integer math is consistent
        txLen = (len(prevouts) * 100) + (len(toAddrs) * 100
                                         )  # Guess the tx Size

        while 1:
            outp = {}
            if amount - Decimal(txfeePer * txLen
                                ) < 0:  # fee too big, find something smaller
                txfeePer = (float(amount) / txLen) / 1.5

            txfee = int(math.ceil(txfeePer * txLen))
            amtPer = (Decimal(amount - txfee) /
                      len(toAddrs)).to_integral_value()
            # print "amount: ", amount, " amount per: ", amtPer, "from :", len(prevouts), "to: ", len(toAddrs), "tx fee: ", txfeePer, txfee

            for a in toAddrs[0:-1]:
                if PerfectFractions:
                    outp[str(a)] = str(amtPer / Decimal(BTC))
                else:
                    outp[str(a)] = float(amtPer / BTC)

            a = toAddrs[-1]
            amtPer = (amount - ((len(toAddrs) - 1) * amtPer)) - txfee
            # print "final amt: ", amtPer
            if PerfectFractions:
                outp[str(a)] = str(amtPer / BTC)
            else:
                outp[str(a)] = float(amtPer / BTC)

            totalOutputs = sum([Decimal(x) for x in outp.values()])
            assert (totalOutputs < amount)
            txn = node.createrawtransaction(inp, outp)
            if kwargs.get("sendtx", True):
                #print time.strftime('%X %x %Z')
                try:
                    s = str(txn)
                    # print "tx len: ", len(binascii.unhexlify(s))
                    signedtxn = node.signrawtransaction(s)
                    txLen = len(
                        binascii.unhexlify(signedtxn["hex"])
                    )  # Get the actual transaction size for better tx fee estimation the next time around
                finally:
                    #print time.strftime('%X %x %Z')
                    pass

                if signedtxn["complete"]:
                    try:
                        txid = node.sendrawtransaction(
                            signedtxn["hex"], True
                        )  # In the unit tests, we'll just allow high fees
                        return (txn, inp, outp, txid)
                    except JSONRPCException as e:
                        tmp = e.error["message"]
                        (code, msg) = tmp.split(":")
                        if int(code) == 64: raise  # bad transaction
                        if int(code) == 258:  # txn-mempool-conflict
                            # we are reusing inputs so this is all the splitting we can do
                            return (txn, inp, outp, txid)
                        # print tmp
                        if e.error["code"] == -26:  # insufficient priority
                            txfeePer = txfeePer * 2
                            print(str(e))
                            print(
                                "Insufficient priority, raising tx fee per byte to: ",
                                txfeePer)
                            continue
                        else:
                            raise
                else:
                    for err in signedtxn["errors"]:
                        print(err["error"])
            else:
                return (txn, inp, outp, txid)
    finally:
        decimal.getcontext().prec = decContext
Example #42
0
    def setUp(self):
        # set up decimal precision to make comparisons easier
        decimal_context = getcontext()
        self.__prev_decimal_prec = decimal_context.prec
        decimal_context.prec = 4

        self.plugin = Team

        # usage type
        self.usage_type = models.UsageType(
            name='Teams',
            symbol='Teams',
            by_team=True,
            type='BU',
        )
        self.usage_type.save()

        # teams
        self.team_time = models.Team(
            name='T1',
            billing_type='TIME',
            show_percent_column=True,
        )
        self.team_time.save()
        self.team_devices_cores = models.Team(
            name='T2',
            billing_type='DEVICES_CORES',
        )
        self.team_devices_cores.save()
        self.team_devices = models.Team(
            name='T3',
            billing_type='DEVICES',
        )
        self.team_devices.save()
        self.team_distribute = models.Team(
            name='T4',
            billing_type='DISTRIBUTE',
        )
        self.team_distribute.save()
        self.teams = models.Team.objects.all()

        # dateranges
        self.daterange1 = models.TeamDaterange(
            team=self.team_time,
            start=date(2013, 10, 1),
            end=date(2013, 10, 10),
        )
        self.daterange1.save()
        self.daterange2 = models.TeamDaterange(
            team=self.team_time,
            start=date(2013, 10, 11),
            end=date(2013, 10, 30),
        )
        self.daterange2.save()

        # costs
        # team time
        up = models.UsagePrice(
            type=self.usage_type,
            cost=300,
            forecast_cost=600,
            start=date(2013, 10, 1),
            end=date(2013, 10, 15),
            team=self.team_time,
            team_members_count=10,
        )
        up.save()
        up = models.UsagePrice(
            type=self.usage_type,
            cost=900,
            forecast_cost=450,
            start=date(2013, 10, 16),
            end=date(2013, 10, 30),
            team=self.team_time,
            team_members_count=20,
        )
        up.save()

        up = models.UsagePrice(
            type=self.usage_type,
            cost=300,
            forecast_cost=600,
            start=date(2013, 10, 1),
            end=date(2013, 10, 30),
            team=self.team_devices_cores,
            team_members_count=20,
        )
        up.save()

        up = models.UsagePrice(
            type=self.usage_type,
            cost=800,
            forecast_cost=1600,
            start=date(2013, 10, 1),
            end=date(2013, 10, 10),
            team=self.team_devices,
            team_members_count=20,
        )
        up.save()
        up = models.UsagePrice(
            type=self.usage_type,
            cost=100,
            forecast_cost=200,
            start=date(2013, 10, 11),
            end=date(2013, 10, 30),
            team=self.team_devices,
            team_members_count=10,
        )
        up.save()

        up = models.UsagePrice(
            type=self.usage_type,
            cost=3000,
            forecast_cost=1500,
            start=date(2013, 10, 1),
            end=date(2013, 10, 15),
            team=self.team_distribute,
            team_members_count=10,
        )
        up.save()
        up = models.UsagePrice(
            type=self.usage_type,
            cost=6000,
            forecast_cost=3000,
            start=date(2013, 10, 16),
            end=date(2013, 10, 30),
            team=self.team_distribute,
            team_members_count=10,
        )
        up.save()

        # ventures
        self.venture1 = models.Venture(name='V1', venture_id=1, is_active=True)
        self.venture1.save()
        self.venture2 = models.Venture(name='V2', venture_id=2, is_active=True)
        self.venture2.save()
        self.venture3 = models.Venture(name='V3', venture_id=3, is_active=True)
        self.venture3.save()
        self.ventures = models.Venture.objects.all()

        # ventures percentage (only for time team)
        percentage = (
            (self.daterange1, [30, 30, 40]),
            (self.daterange2, [20, 50, 30]),
        )
        for team_daterange, percent in percentage:
            for venture, p in zip(self.ventures, percent):
                tvp = models.TeamVenturePercent(
                    team_daterange=team_daterange,
                    venture=venture,
                    percent=p,
                )
                tvp.save()
Example #43
0
from copy import deepcopy
from decimal import Decimal, getcontext

from src.hyperplane import Hyperplane
from src.vector import Vector

getcontext().prec = 15


class LinearSystem(object):
    ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG = 'All planes in the system should live in the same dimension'
    NO_SOLUTIONS_MSG = 'No solutions'
    INF_SOLUTIONS_MSG = 'Infinitely many solutions'
    NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found'

    def __init__(self, planes):
        try:
            d = planes[0].dimension
            for p in planes:
                assert p.dimension == d

            self.planes = planes
            self.dimension = d

        except AssertionError:
            raise Exception(self.ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG)

    def swap_rows(self, row1, row2):

        temp = self[row1]
        self[row1] = self[row2]
Example #44
0
    def check_d2d_reward_discount_py(self, nowprice, vipprice, isgenba=0):
        if isgenba == 0:
            member_discount = 0.95
            bronze_discount = 0.92
            silver_discount = 0.88
            gold_discount = 0.85
            platinum_discount = 0.8
        else:
            member_discount = 0.98
            bronze_discount = 0.96
            silver_discount = 0.94
            gold_discount = 0.92
            platinum_discount = 0.9

        print("now price " + nowprice)
        nprice = re.sub('[!@#$]', '', nowprice)
        print("vip price " + vipprice)
        vprice = re.sub('[!@#$]', '', vipprice)

        #convert to float type
        f_nprice = float(nprice)
        f_vprice = float(vprice)

        decimal.getcontext().rounding = decimal.ROUND_UP
        # decimal.getcontext().prec = 3
        # print decimal.getcontext()

        if f_nprice < 9.99:
            # print "member_discount"
            f_nprice = f_nprice * member_discount
            f_nprice = decimal.Decimal(f_nprice).quantize(Decimal("1.0"))
            f_vprice = decimal.Decimal(f_vprice).quantize(Decimal("1.0"))
            if float(f_nprice) == float(f_vprice):
                # print "pass"
                status = 1
            else:
                # print "fail"
                # print f_nprice
                # print f_vprice
                status = 0
        elif 9.99 <= f_nprice < 19.99:
            # print "bronze_discount"
            f_nprice = f_nprice * bronze_discount
            f_nprice_2 = decimal.Decimal(f_nprice).quantize(Decimal("1.0"))
            f_vprice = decimal.Decimal(f_vprice).quantize(Decimal("1.0"))
            if float(f_nprice_2) == float(f_vprice):
                # print "pass"
                status = 1
            else:
                # print "fail"
                # print f_nprice_2
                # print f_vprice
                status = 0
        elif 19.99 <= f_nprice < 29.99:
            # print "silver_discount"
            f_nprice = f_nprice * silver_discount
            f_nprice_2 = decimal.Decimal(f_nprice).quantize(Decimal("1.0"))
            f_vprice = decimal.Decimal(f_vprice).quantize(Decimal("1.0"))
            if float(f_nprice_2) == float(f_vprice):
                # print "pass"
                status = 1
            else:
                # print "fail"
                # print f_nprice_2
                # print f_vprice
                status = 0
        elif 29.99 <= f_nprice < 59.99:
            # print "gold_discount"
            f_nprice = f_nprice * gold_discount
            f_nprice_2 = decimal.Decimal(f_nprice).quantize(Decimal("1.0"))
            f_vprice = decimal.Decimal(f_vprice).quantize(Decimal("1.0"))
            if float(f_nprice_2) == float(f_vprice):
                # print "pass"
                status = 1
            else:
                # print "fail"
                # print f_nprice_2
                # print f_vprice
                status = 0
        elif f_nprice >= 59.99:
            # print "platinum_discount"
            f_nprice = f_nprice * platinum_discount
            f_nprice_2 = decimal.Decimal(f_nprice).quantize(Decimal("1.0"))
            f_vprice = decimal.Decimal(f_vprice).quantize(Decimal("1.0"))
            if float(f_nprice_2) == float(f_vprice):
                # print "pass"
                status = 1
            else:
                # print "fail"
                # print f_nprice_2
                # print f_vprice
                status = 0
        else:
            print("exception happen")

        return status
Example #45
0
 def truncate_digits(cls, in_number: float, max_digits: int) -> float:
     """Restrict maximum decimal digits by removing them"""
     getcontext().prec = max_digits
     working_num = int(Decimal(str(in_number)) * Decimal(Decimal("10") ** Decimal(str(max_digits))))
     return working_num / (10 ** max_digits)
Example #46
0
def pdf_get_all_pageinfo(infile):
    pdf = pypdf.PdfFileReader(infile)
    getcontext().prec = 6
    return [_pdf_get_pageinfo(infile, n) for n in range(pdf.numPages)]
Example #47
0
import bisect
from collections import deque
from copy import deepcopy
import decimal
import heapq
from itertools import combinations, permutations
from itertools import combinations_with_replacement
import sys
import math
from sys import modules

sys.setrecursionlimit(100_000)
input = lambda: sys.stdin.readline().rstrip()
decimal.getcontext().rounding = decimal.ROUND_HALF_UP

test = True
if test:
    try:
        sys.stdin = open('input_data.txt', 'r')
        print('sys.stdin = input.txt')
    except FileNotFoundError:
        pass

directions = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1),
              (-1, -1)]

n, fm, k = map(int, input().split())
q = deque()
for _ in range(fm):
    r, c, m, s, d = map(int, input().split())
    q.append((r - 1, c - 1, m, s, d))
Example #48
0
def decimal_to_precision(n,
                         rounding_mode=ROUND,
                         precision=None,
                         counting_mode=DECIMAL_PLACES,
                         padding_mode=NO_PADDING):
    assert precision is not None and isinstance(precision, numbers.Integral)
    assert rounding_mode in [TRUNCATE, ROUND]
    assert counting_mode in [DECIMAL_PLACES, SIGNIFICANT_DIGITS]
    assert padding_mode in [NO_PADDING, PAD_WITH_ZERO]

    context = decimal.getcontext()

    precision = min(context.prec - 2, precision)

    # all default except decimal.Underflow (raised when a number is rounded to zero)
    context.traps[decimal.Underflow] = True
    context.rounding = decimal.ROUND_HALF_UP  # rounds 0.5 away from zero

    dec = decimal.Decimal(n)
    string = str(dec)
    precise = None

    def power_of_10(x):
        return decimal.Decimal('10')**(-x)

    if rounding_mode == ROUND:
        if counting_mode == DECIMAL_PLACES:
            precise = str(dec.quantize(
                power_of_10(precision)))  # ROUND_HALF_EVEN is default context
        elif counting_mode == SIGNIFICANT_DIGITS:
            q = precision - dec.adjusted() - 1
            sigfig = power_of_10(q)
            if q < 0:
                string_to_precision = string[:precision]
                # string_to_precision is '' when we have zero precision
                below = sigfig * decimal.Decimal(
                    string_to_precision if string_to_precision else '0')
                above = below + sigfig
                precise = str(min((below, above), key=lambda x: abs(x - dec)))
            else:
                precise = str(dec.quantize(sigfig))

    elif rounding_mode == TRUNCATE:
        # Slice a string
        if counting_mode == DECIMAL_PLACES:
            before, after = string.split('.') if '.' in string else (string,
                                                                     '')
            precise = before + '.' + after[:precision]
        elif counting_mode == SIGNIFICANT_DIGITS:
            if precision == 0:
                return '0'
            dot = string.index('.') if '.' in string else 0
            start = dot - dec.adjusted()
            end = start + precision
            # need to clarify these conditionals
            if dot >= end:
                end -= 1
            precise = string[:end].ljust(dot, '0')
        precise = precise.rstrip('.')

    if padding_mode == NO_PADDING:
        return precise.rstrip('0').rstrip('.') if '.' in precise else precise
    elif padding_mode == PAD_WITH_ZERO:
        if '.' in precise:
            if counting_mode == DECIMAL_PLACES:
                before, after = precise.split('.')
                return before + '.' + after.ljust(precision, '0')

            elif counting_mode == SIGNIFICANT_DIGITS:
                fsfg = len(
                    list(
                        itertools.takewhile(lambda x: x == '.' or x == '0',
                                            precise)))
                if '.' in precise[fsfg:]:
                    precision += 1
                return precise[:fsfg] + precise[fsfg:].rstrip('0').ljust(
                    precision, '0')
        else:
            if counting_mode == SIGNIFICANT_DIGITS:
                if precision > len(precise):
                    return precise + '.' + (precision - len(precise)) * '0'
            elif counting_mode == DECIMAL_PLACES:
                if precision > 0:
                    return precise + '.' + precision * '0'
            return precise
Example #49
0
  - prázdné mapování ({})
"""

xl = 'abcdefghchijklmno'
'd' in xl #true
'd' not in xl #false


##### decimal #####
# je to supr věc, můžu si zvolit přesnost výpočtů jakou chci
import decimal
D = decimal.Decimal
a = D(1)/D(7) #0.1428571428571428571428571429
print(a)

decimal.getcontext().prec = 5
# decimal.getcontext() vrací aktuální nastavení
print(D(1)/D(7)) #0.14286
decimal.getcontext().prec = 28

D(str(3 * 0.1)) - D('0.3') #0.0 (bez decimal by to vyhodilo komplexní číslo, což nemáme rádi a nechceme
D('1.30') + D('1.20') #2.50 -> drží nastavený počet významných míst
D('-Infinity') + D('-Infinity') #-Infinity
D(1).exp() #Decimal('2.718281828459045235360287471')
#umi i treba ln nebo sqrt

##### fractions #####
import fractions
#dalsi supercool vec, umi pracovat se zlomky
F = fractions.Fraction
F('-16/10') + F('3/5') #Fraction(-1/1)
Example #50
0
def get_random_num():
    x = [random.random()]
    decimal.getcontext().prec = 16
    return decimal.Decimal(x[0]) * 1
"""hum E1011 on .prec member is justifiable since Context instance are built
using setattr/locals :(

2007/02/17 update: .prec attribute is now detected by astroid :o)
"""
from __future__ import print_function
import decimal

decimal.getcontext().prec = 200
print(decimal.getcontext().prec)
Example #52
0
'''
Violates the spirit of the problem. Thanks python for being the best
'''
import decimal

if __name__ == '__main__':
    decimal.getcontext().prec = 110
    out = 0
    for i in range(2, 100):
        if int(i**.5)**2 == i:
            continue
        d = decimal.Decimal(i)**decimal.Decimal(.5)
        val = str(d).replace('.', '')[:100]
        v = sum([int(i) for i in list(val)])
        out += v
    print(out)
Example #53
0
        # only ufixed256x80 type supports 2-80 decimals
        ('reflect', Decimal(2**256 - 1) / 10**80),  # maximum allowed value
        ('reflect', Decimal(1) / 10**80),  # smallest non-zero value
        # minimum value (for ufixed8x1)
        ('reflect_short_u', 0),
        # maximum value (for ufixed8x1)
        ('reflect_short_u', Decimal('25.5')),
    ),
)
def test_reflect_fixed_value(web3, fixed_reflection_contract, function, value):
    contract_func = fixed_reflection_contract.functions[function]
    reflected = contract_func(value).call({'gas': 420000})
    assert reflected == value


DEFAULT_DECIMALS = getcontext().prec


@pytest.mark.parametrize(
    'function, value, error',
    (
        # out of range
        ('reflect_short_u', Decimal('25.6'), "no matching argument types"),
        ('reflect_short_u', Decimal('-.1'), "no matching argument types"),
        # too many digits for *x1, too large for 256x80
        ('reflect', Decimal('0.01'), "no matching argument types"),

        # too many digits
        ('reflect_short_u', Decimal('0.01'), "no matching argument types"),
        (
            'reflect_short_u',
Example #54
0
    def __init__(self,
                 start: tc.optional(tc.any(int, float)) = None,
                 stop: tc.optional(tc.any(int, float)) = None,
                 step: tc.optional(tc.any(int, float)) = None,
                 num: tc.optional(int) = None,
                 function: tc.optional(callable) = None,
                 precision: tc.optional(int) = None,
                 custom_spec=None):

        self.custom_spec = custom_spec

        if self.custom_spec:
            # Assumes receiver of SampleIterator will get this and know what to do with it,
            #   therefore no other attributes are needed and, to avoid confusion, they should not be available;
            #   so just assign and return.
            return

        self._precision = precision or SAMPLE_SPEC_PRECISION
        # Save global precision for later restoration
        _global_precision = getcontext().prec
        # Set SampleSpec precision
        getcontext().prec = self._precision

        if function is None:
            if start is None or stop is None:
                raise SampleIteratorError(
                    "If 'function' is not specified, then 'start' and 'stop' must be "
                    "specified.")
            if num is None and step is not None:
                num = int(Decimal(1.0) + Decimal(stop - start) / Decimal(step))
                # num = 1.0 + (stop - start) / step
            elif step is None and num is not None:
                step = (Decimal(stop) - Decimal(start)) / (num - 1)
            elif num is None and step is None:
                raise SampleIteratorError(
                    "Must specify one of {}, {} or {}.".format(
                        repr('step'), repr('num'), repr('function')))
            else:
                if not np.isclose(num, 1.0 + (stop - start) / step):
                    raise SampleIteratorError(
                        "The {} ({}) and {} ({}} values specified are not comaptible."
                        .format(repr('step'), step, repr('num'), num))

        elif callable(function):
            _validate_function(self, function)

            if start is not None:
                raise SampleIteratorError(
                    "Only one of {} ({}) and {} ({}} may be specified.".format(
                        repr('start'), start, repr('function'), function))
            if step is not None:
                raise SampleIteratorError(
                    "Only one of {} ({}) and {} ({}} may be specified.".format(
                        repr('step'), step, repr('function'), function))
        else:
            raise SampleIteratorError(
                "{} is not a valid function for {}.".format(
                    function, self.__name__))

        # FIX: ELIMINATE WHEN UPGRADING TO PYTHON 3.5.2 OR 3.6, (AND USING ONE OF THE TYPE VERSIONS COMMENTED OUT ABOVE)
        # Validate entries of specification
        #
        self.start = start
        self.stop = stop
        self.step = step
        self.num = num
        self.function = function

        # Restore global precision
        getcontext().prec = _global_precision
Example #55
0
 def getRMSValue(self, dataPoints):
     getcontext().prec = 5
     return np.sqrt(np.mean(np.square(dataPoints)))
Example #56
0
 def __init__(self, *args, **kwargs):
     super(Person, self).__init__(*args, **kwargs)
     money_context = getcontext()
     money_context.prec = 16
     money_context.rounding = ROUND_FLOOR
Example #57
0
#coding:utf-8
"""
Pi = SUM k=0 to infinity 16^-k [ 4/(8k+1) - 2/(8k+4) - 1/(8k+5) - 1/(8k+6) ]
ref: https://www.math.hmc.edu/funfacts/ffiles/20010.5.shtml
https://github.com/Flowerowl/Projects/blob/master/solutions/numbers/find_pi_to_the_nth_digit.py
"""
from __future__ import division
import math
from decimal import Decimal as D
from decimal import getcontext

getcontext().prec = 400
MAX = 10000
pi = D(0)

for k in range(MAX):
    pi += D(math.pow(16, -k)) * (D(4 / (8 * k + 1)) - D(2 / (8 * k + 4)) -
                                 D(1 / (8 * k + 5)) - D(1 / (8 * k + 6)))

print('PI=', pi)
Example #58
0
# Precision and Rounding
# ctx = decimal.getcontext()	--> context (global in the case)
# ctx.prec	--> get or set the precision (value is in int)
# ctx.rounding()  --> get or set the rounding mechanism (value is a string)
#	--> In this we have the following rounding algorithms:
#			- ROUND_UP (rounds away from zero)
#			- ROUND_DOWN (rounds towards zero)
# 			- ROUND_CEILING (round to ceiling, towards + inf)
# 			- ROUND_FLOOR (round to floor, towards -inf)
# 			- ROUND_HALF_UP (rounds to nearest, ties away from zero)
# 			- ROUND_HALF_DOWN (rounds to nearest, ties towards zero)
#			- ROUND_HALF_EVEN (rounds to nearest, ties to even)
print('\n\n----Decimals----')
print('----Context----')
g_ctx = decimal.getcontext()
print(g_ctx)
g_ctx.rounding = decimal.ROUND_HALF_DOWN
# or g_ctx.rounrding = 'ROUND_HALF_UP'
print(g_ctx)
print('type(decimal.getcontext()): ', type(g_ctx))
print('type(decimal.localcontext()): ', type(decimal.localcontext()))
# which is similar to default (or global) context in this case

x = Decimal('1.25')
y = Decimal('1.35')

# using context manager of localcontext
print('----Context Manager----')
with decimal.localcontext() as ctx:
    ctx.prec = 6
def main(argv):

    parser = argparse.ArgumentParser()

    parser.add_argument(
        "input_video_file",
        help="clip to load"
    )
    parser.add_argument(
        "input_label_file",
        help="label to load"
    )
    parser.add_argument(
        "output_file_prefix",
        help="Output file path."
    )

    parser.add_argument(
        "convert_video",
        help="Want to convert video (y/n ?)."
    )
    parser.add_argument(
        "width",
        help="Scale to resize images and labels."
    )
    parser.add_argument(
        "height",
        help="Scale to resize images and labels."
    )

    parser.add_argument(
        "ignore_smaller",
        help="ignore labels that are smaller than what is specified."
    )

    args = parser.parse_args()

    getcontext().prec = 3

    capture = cv2.VideoCapture(args.input_video_file)

    orig_width = capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
    orig_height = capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
    scale_x = float(orig_width) / float(args.width)
    scale_y = float(orig_height) / float(args.height)
    print scale_x, scale_y

    min_size = args.ignore_smaller


    # LABEL
    label_file = np.loadtxt(args.input_label_file)
    not_labbeled_list = []

    for index in range(0,int(np.amax(label_file[:,0]))):
        # print index
        # gt_file = open(args.output_file_prefix + '_' + str(index) + '.txt', 'w')

        # Check which lines have index "index"
        index_lookup = (label_file[:, 0] == index * np.ones_like(label_file[:, 0]))
        index_lookup = index_lookup.astype(int)

        if np.count_nonzero(index_lookup) != 0:
            gt_file = open(args.output_file_prefix + '_' + str(index) + '.txt', 'w')
            # pass
            # print np.nonzero(index_lookup)
            for nonz_index in range(0,np.count_nonzero(index_lookup.astype(int))):

                if min_size == 0:
                    position_to_read = int(np.nonzero(index_lookup)[0][nonz_index])

                    left_number = float(label_file[position_to_read, 1]) / float(scale_x)
                    top_number = float(label_file[position_to_read, 2])/float(scale_y)
                    right_number = (float(label_file[position_to_read, 3]) / float(scale_x) + float(label_file[position_to_read, 1]) / float(scale_x))
                    bottom_number = float(label_file[position_to_read, 2]) / float(scale_y) + float(label_file[position_to_read, 4]) / float(scale_y)
                    left = "%.2f" % left_number
                    top = "%.2f" % top_number
                    right = "%.2f" % right_number
                    bottom = "%.2f" % bottom_number

                    gt_file.write('Car' + ' ' + '0.00' + ' '+'0' + ' ' + '0.00'+' ' +  str(left)+' '+ str(top) + ' ' + str(right) + ' ' + str(bottom) + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00\n')
                #            class   truncated   occluded    alpha         left          top            right          bottom

                else:
                    position_to_read = int(np.nonzero(index_lookup)[0][nonz_index])

                    if float((label_file[position_to_read, 3])) > float(min_size) and float(label_file[position_to_read, 4]) > float(min_size):

                        left_number = float(label_file[position_to_read, 1]) / float(scale_x)
                        top_number = float(label_file[position_to_read, 2]) / float(scale_y)
                        right_number = (float(label_file[position_to_read, 3]) / float(scale_x) + float(label_file[position_to_read, 1]) / float(scale_x))
                        bottom_number = float(label_file[position_to_read, 2]) / float(scale_y) + float(label_file[position_to_read, 4]) / float(scale_y)
                        left = "%.2f" % left_number
                        top = "%.2f" % top_number
                        right = "%.2f" % right_number
                        bottom = "%.2f" % bottom_number
                        gt_file.write('Car' + ' ' + '0.00' + ' ' + '0' + ' ' + '0.00' + ' ' + str(left) + ' ' + str(top) + ' ' + str(right) + ' ' + str(
                            bottom) + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00' + ' ' + '0.00\n')
                    else:
                        pass

            gt_file.close()

        elif np.count_nonzero(index_lookup) == 0:
            not_labbeled_list = np.append(not_labbeled_list, index)

    print('not_labbeled_list ', not_labbeled_list)

    if args.convert_video == 'y':
        # VIDEO
        # capture = cv2.VideoCapture(args.input_video_file)
        # print capture.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)

        for index in range(0, int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))):
            # capture.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, index)
            print capture.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
            rect , img = capture.read()

            if np.any(not_labbeled_list == index * np.ones_like(not_labbeled_list)):
                pass
            else:
                img = cv2.resize(img,(int(args.width), int(args.height)))
                cv2.imwrite(args.output_file_prefix + '_' + str(index) + '.jpg', img)
Example #60
0
import sys
import random
import FormulaSolidityPort

from decimal import Decimal
from decimal import getcontext
getcontext(
).prec = 80  # 78 digits for a maximum of 2^256-1, and 2 more digits for after the decimal point


def formulaTest(supply, balance1, weight1, balance2, weight2, amount1):
    amount2 = FormulaSolidityPort.crossReserveTargetAmount(
        balance1, weight1, balance2, weight2, amount1)
    amount3 = FormulaSolidityPort.crossReserveTargetAmount(
        balance2 - amount2, weight2, balance1 + amount1, weight1, amount2)
    before, after = amount1, amount3
    if after > before:
        error = ['Implementation Error:']
        error.append('supply   = {}'.format(supply))
        error.append('balance1 = {}'.format(balance1))
        error.append('weight1  = {}'.format(weight1))
        error.append('balance2 = {}'.format(balance2))
        error.append('weight2  = {}'.format(weight2))
        error.append('amount1  = {}'.format(amount1))
        error.append('amount2  = {}'.format(amount2))
        error.append('amount3  = {}'.format(amount3))
        error.append('before   = {}'.format(before))
        error.append('after    = {}'.format(after))
        raise BaseException('\n'.join(error))
    return Decimal(after) / Decimal(before)