Пример #1
0
def number_to_string(number):
    with decimal.localcontext() as ctx:
        ctx.prec = 20  # set floating point precision
        d = decimal.Decimal(str(number))
        return str(d.quantize(decimal.Decimal(1)) if d == d.to_integral_value() else d.normalize())
Пример #2
0
 def test_decimal_no_scale(self):
     data = [decimal.Decimal('1234234983'), decimal.Decimal('8094324')]
     type = pa.decimal(precision=10)
     arr = pa.array(data, type=type)
     assert arr.to_pylist() == data
Пример #3
0
 def test_decimal_no_whole_part(self):
     data = [decimal.Decimal('-.4234983'), decimal.Decimal('.0103943')]
     type = pa.decimal(precision=7, scale=7)
     arr = pa.array(data, type=type)
     assert arr.to_pylist() == data
Пример #4
0
 async def test_slow_uptrend(self):
     # market: 11.32644122514472
     # market: -36.64596273291926
     await self.run_test_slow_uptrend(decimal.Decimal(str(11.326)),
                                      decimal.Decimal(str(-14.477)))
Пример #5
0
def computeit( ):
    decimal.getcontext().prec = 200

    runsize = 1000

    x = 0 
    y = 0 
    z = 0 

    face1 = decimal.Decimal(int(0))
    face2 = decimal.Decimal(int(0))
    face3 = decimal.Decimal(int(0))

    runcount = 0 

    diagonal = decimal.Decimal(int(0))

    eulerfound = 0
    perfectfound = 0

    totalboxes = 0


    while 1 > 0:
      Filehandle = open("bricked.txt","r")
      Filecontents = Filehandle.readlines()
      linenum = random.randint(1, len(Filecontents) - 1)
      Linecontents = Filecontents[linenum].split()
      xstart = int(Linecontents[1]) - runsize
      ystart = int(Linecontents[3]) - runsize
      zstart = int(Linecontents[5]) - runsize
      x = xstart
      y = ystart
      z = zstart
      if x < 1:
        x = 1
      if y < 1:
        y = 1
      if z < 1:
        z = 1
      z = 0
      Filehandle.close()
      while x < xstart + runsize + runsize:
        x = x + 1
        y = ystart
        #os.system('cls')
        print ("boxes: " + str(totalboxes) + " Euler Bricks found: " + str(eulerfound) + " Perfect Cuboids found: " + str(perfectfound))
        print ("X: " + str(x) + " y: " + str(y) + " z: " + str(z))
        while y < ystart + runsize + runsize:
          y = y + 1
          z = zstart
          if y < 1:
            y = 1
          if z < 1:
            z = 1
          while z < zstart + runsize + runsize:
            totalboxes += 1
            z += 1
            face2 = decimal.Decimal((x * x) + (z * z))
            face2 = face2.sqrt()
            face3 = decimal.Decimal((y * y) + (z * z))
            face3 = face3.sqrt()
            if face2 %1 == 0:
              file = open('face2.txt', 'a')
              file.write('\n')
              file.write('x: ' + str(x)+ " z: " + str(z))
              file.close()
            if face3 %1 == 0:
              file = open('face3.txt', 'a')
              file.write('\n')
              file.write('y: ' + str(y)+ " z: " + str(z))
              file.close()
            if face2 %1 == 0 and face3 %1 == 0:
              file = open('brick.txt', 'a')
              file.write('\n')
              file.write('x: ' + str(x)+ " y: " + str(y) + " z:  " + str(z))
              file.close()
              eulerfound += 1
              diagonal = decimal.Decimal((x * x) + (y * y) + (z * z))
              diagonal = diagonal.sqrt()
              if diagonal % 1 == 0:
                print (diagonal)
                perfectfound += 1
                file = open('perfectcube.txt', 'a')
                file.write('\n')
                file.write('x: ' + str(x)+ " y: " + str(y) + " z:  " + str(z))
                file.close()
    null_boolean_field = models.NullBooleanField()
    positive_integer_field = models.PositiveIntegerField()
    positive_small_integer_field = models.PositiveSmallIntegerField()
    slug_field = models.SlugField(max_length=100)
    small_integer_field = models.SmallIntegerField()
    text_field = models.TextField()
    time_field = models.TimeField()
    url_field = models.URLField(max_length=100)
    custom_field = CustomField()

    def method(self):
        return 'method'


COLOR_CHOICES = (('red', 'Red'), ('blue', 'Blue'), ('green', 'Green'))
DECIMAL_CHOICES = (('low', decimal.Decimal('0.1')), ('medium', decimal.Decimal('0.5')), ('high', decimal.Decimal('0.9')))


class FieldOptionsModel(models.Model):
    value_limit_field = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])
    length_limit_field = models.CharField(validators=[MinLengthValidator(3)], max_length=12)
    blank_field = models.CharField(blank=True, max_length=10)
    null_field = models.IntegerField(null=True)
    default_field = models.IntegerField(default=0)
    descriptive_field = models.IntegerField(help_text='Some help text', verbose_name='A label')
    choices_field = models.CharField(max_length=100, choices=COLOR_CHOICES)


class ChoicesModel(models.Model):
    choices_field_with_nonstandard_args = models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES, verbose_name='A label')
Пример #7
0
 async def test_default_run(self):
     # market: -49.25407390406244
     await self.run_test_default_run(decimal.Decimal(str(-25.195)))
Пример #8
0
def _imround(x):
    """Round float pixel values like imagemagick does it."""
    return decimal.Decimal(x).to_integral(decimal.ROUND_HALF_UP)
Пример #9
0
def donate(request):
    """Add a single donation item to the cart and proceed to payment.

    Warning: this call will clear all the items in the user's cart
    before adding the new item!

    Arguments:
        request (Request): The Django request object.  This should contain
            a JSON-serialized dictionary with "amount" (string, required),
            and "course_id" (slash-separated course ID string, optional).

    Returns:
        HttpResponse: 200 on success with JSON-encoded dictionary that has keys
            "payment_url" (string) and "payment_params" (dictionary).  The client
            should POST the payment params to the payment URL.
        HttpResponse: 400 invalid amount or course ID.
        HttpResponse: 404 donations are disabled.
        HttpResponse: 405 invalid request method.

    Example usage:

        POST /shoppingcart/donation/
        with params {'amount': '12.34', course_id': 'edX/DemoX/Demo_Course'}
        will respond with the signed purchase params
        that the client can send to the payment processor.

    """
    amount = request.POST.get('amount')
    course_id = request.POST.get('course_id')

    # Check that required parameters are present and valid
    if amount is None:
        msg = u"Request is missing required param 'amount'"
        log.error(msg)
        return HttpResponseBadRequest(msg)
    try:
        amount = (
            decimal.Decimal(amount)
        ).quantize(
            decimal.Decimal('.01'),
            rounding=decimal.ROUND_DOWN
        )
    except decimal.InvalidOperation:
        return HttpResponseBadRequest("Could not parse 'amount' as a decimal")

    # Any amount is okay as long as it's greater than 0
    # Since we've already quantized the amount to 0.01
    # and rounded down, we can check if it's less than 0.01
    if amount < decimal.Decimal('0.01'):
        return HttpResponseBadRequest("Amount must be greater than 0")

    if course_id is not None:
        try:
            course_id = CourseLocator.from_string(course_id)
        except InvalidKeyError:
            msg = u"Request included an invalid course key: {course_key}".format(course_key=course_id)
            log.error(msg)
            return HttpResponseBadRequest(msg)

    # Add the donation to the user's cart
    cart = Order.get_cart_for_user(request.user)
    cart.clear()

    try:
        # Course ID may be None if this is a donation to the entire organization
        Donation.add_to_order(cart, amount, course_id=course_id)
    except InvalidCartItem as ex:
        log.exception((
            u"Could not create donation item for "
            u"amount '{amount}' and course ID '{course_id}'"
        ).format(amount=amount, course_id=course_id))
        return HttpResponseBadRequest(unicode(ex))

    # Start the purchase.
    # This will "lock" the purchase so the user can't change
    # the amount after we send the information to the payment processor.
    # If the user tries to make another donation, it will be added
    # to a new cart.
    cart.start_purchase()

    # Construct the response params (JSON-encoded)
    callback_url = request.build_absolute_uri(
        reverse("shoppingcart.views.postpay_callback")
    )

    response_params = json.dumps({
        # The HTTP end-point for the payment processor.
        "payment_url": get_purchase_endpoint(),

        # Parameters the client should send to the payment processor
        "payment_params": get_signed_purchase_params(
            cart,
            callback_url=callback_url,
            extra_data=([unicode(course_id)] if course_id else None)
        ),
    })

    return HttpResponse(response_params, content_type="text/json")
Пример #10
0
 def to_decimal(self, digits=0):
     return decimal.Decimal(self.value)
Пример #11
0
 def to_decimal(self, digits=0):
     fmt = "{0:0.{digits}f}"
     return decimal.Decimal(fmt.format(self.to_float(), digits=digits))
Пример #12
0
 def _detect_decimal(self, value):
     if "." in value:
         return decimal.Decimal(value)
     else:
         return int(value)
Пример #13
0
 def parse(self, value):
     for pattern, replacement in self.subs.items():
         value = re.sub(pattern, replacement, value)
     return decimal.Decimal(value)
Пример #14
0
def _parse_geocoord(strike_geocoord):
    if strike_geocoord:
        return decimal.Decimal(strike_geocoord)
    return None
Пример #15
0
def valid_decimal(value):
    try:
        decimal.Decimal(value)
        return True
    except decimal.InvalidOperation:
        return False
Пример #16
0
class ActionTable:
    toggleTime = decimal.Decimal('.1')

    def __init__(self):
        ## List of (time, handler, parameter) tuples indicating what actions
        # must be taken at what times.
        self.actions = []
        ## Time of our first action.
        # \todo How do we handle the removal of actions rendering this invalid?
        # For now, we don't.
        self.firstActionTime = None
        ## Time of our last action.
        self.lastActionTime = None

    ## Insert an element into self.actions.
    def addAction(self, time, handler, parameter):
        self.actions.append((time, handler, parameter))
        if self.firstActionTime is None or self.firstActionTime > time:
            self.firstActionTime = time
        if self.lastActionTime is None or self.lastActionTime < time:
            self.lastActionTime = time
        return time

    ## Like addDigital, but rapidly toggle the output on and then off.
    # Return the time after the toggle is completed.
    def addToggle(self, time, handler):
        time, dt = handler.addToggle(time, self)
        return time

    ## Retrieve the last time and action we performed with the specified
    # handler.
    # NB assumes that self.actions has been sorted.
    def getLastActionFor(self, handler):
        for time, altHandler, parameter in reversed(self.actions):
            if altHandler is handler:
                return time, parameter
        return None, None

    ## Sort all the actions in the table by time.
    # \todo We should remove redundant entries in here (e.g. due to
    # 0 stabilization time for stage movement).
    def sort(self):
        # First element in each action is the timestamp.
        self.actions.sort(key=lambda a: a[0])

    ## Clear invalid entries from the list. Sometimes when the table is
    # modified, an entry needs to be deleted without affecting indexing into
    # the list; thus, the user sets it to None and then calls this function
    # afterwards.
    def clearBadEntries(self):
        pairs = [item for item in enumerate(self.actions)]
        for i, action in reversed(pairs):
            if action is None:
                del self.actions[i]

    ## Go through the table and ensure all timepoints are positive.
    # NB assumes the table has been sorted.
    def enforcePositiveTimepoints(self):
        delta = -self.actions[0][0]
        if delta < 0:
            # First event is at a positive time, so we're good to go.
            return
        for i in range(len(self.actions)):
            self.actions[i] = (self.actions[i][0] + delta, self.actions[i][1],
                               self.actions[i][2])
        self.firstActionTime += delta
        self.lastActionTime += delta

    ## Move all actions after the specified time back by the given offset,
    # to make room for some new action.
    def shiftActionsBack(self, markTime, delta):
        for i, (actionTime, handler, action) in enumerate(self.actions):
            if actionTime >= markTime:
                self.actions[i] = (actionTime + delta, handler, action)
        if self.firstActionTime > markTime:
            self.firstActionTime += delta
        if self.lastActionTime > markTime:
            self.lastActionTime += delta

    ## Return the time of the first and last action we have.
    # Use our cached values if allowed.
    def getFirstAndLastActionTimes(self, canUseCache=True):
        if canUseCache:
            return self.firstActionTime, self.lastActionTime
        firstTime = lastTime = None
        for actionTime, handler, action in self.actions:
            if firstTime is None:
                firstTime = lastTime = actionTime
            firstTime = min(firstTime, actionTime)
            lastTime = max(lastTime, actionTime)
        return firstTime, lastTime

    ## Access an element in the table.
    def __getitem__(self, index):
        return self.actions[index]

    ## Modify an item in the table
    def __setitem__(self, index, val):
        self.actions[index] = val

    ## Get the length of the table.
    def __len__(self):
        return len(self.actions)

    ## Generate pretty text for our table, optionally only for the specified
    # handler(s)
    def prettyString(self, handlers=[]):
        result = ''
        for event in self.actions:
            if event is None:
                result += '<Deleted event>\n'
            else:
                time, handler, action = event
                if not handlers or handler in handlers:
                    result += '%8.2f % 20s % 20s' % (time, handler.name,
                                                     action)
                    result += '\n'
        return result

    ## Cast to a string -- generate a textual description of our actions.
    def __repr__(self):
        return self.prettyString()
Пример #17
0
def measure_temp():
    # temp = os.popen("vcgencmd measure_temp").readline()
    # return (temp.replace("temp=",""))
    return float(decimal.Decimal(random.randrange(0, 1000) / 10))
Пример #18
0
s_list = []

for failed in failed_tests:
	passed = passed_tests.readline()
	
	
	f = failed.split(':', 2)[0]
	p = passed.split(':', 2)[0]
	line_number = passed.split(':', 2)[1]
	
	if (f.count('-') > 0 or f.count('#') > 0):
		f = '0'
	if (p.count('-') > 0 or p.count('#') > 0):
		p = '0'
	
	f = decimal.Decimal(f)
	p = decimal.Decimal(p)

	
	#Compute suspiciousness
	total_passed = numTests - total_failed
	s = -1
	if ((p / total_passed  +  f / total_failed) != 0):
		s = decimal.Decimal((f / total_failed) / (p / total_passed  +  f / total_failed))
		s_list.append((str(round(s, 3)), line_number))

	tarantula.write(str(round(s, 3)) + "\t" + str(failed))
	
	
	
failed_tests.close()
 def get_total(self):
     total = decimal.Decimal(0)
     for i in self.pizzas.all():
         total += decimal.Decimal(i.price)
     return total
Пример #20
0
 def __init__(self, precision, scale):
     self.context = decimal.Context(prec=precision)
     self.scale_format = decimal.Decimal(10)**-scale
Пример #21
0
 async def test_sharp_downtrend(self):
     # market: -34.67997135795625
     await self.run_test_sharp_downtrend(decimal.Decimal(str(-22.231)),
                                         None,
                                         skip_extended=True)
Пример #22
0
 def decode_from_stream(self, stream, nested):
     size = stream.read_bigendian_int32()
     value = decimal.Decimal(stream.read(size).decode("utf-8"))
     return value
Пример #23
0
 async def test_sharp_uptrend(self):
     # market: -17.047906776003458
     # market: -18.25837965302341
     await self.run_test_sharp_uptrend(decimal.Decimal(str(2.640)),
                                       decimal.Decimal(str(10.578)))
Пример #24
0
print('原数据:', c, '转换后:', bin(c), oct(c), hex(c))
print('原数据类型:', type(c), '转换后类型:', type(bin(c)), type(oct(c)), type(hex(c)))
#2/8/16进制间计算要先转换,不然只是字符串的计算
print('0b11' + '0b11', int('0b11', 2) + int('0x11', 16))

import os
if os.path.exists('知识点.txt'):
    os.remove('知识点.txt')

print('===================浮点数,小数类,分数类')
import decimal
from fractions import Fraction
a, b = .13442, 1.12312
print('a+b=', a + b)
decimal.getcontext().prec = 9  #设置小数保留位数
print('a+b=', decimal.Decimal(a) + decimal.Decimal(b))
with decimal.localcontext() as ctx:  #临时重置小数精度,退出with后变为默认
    ctx.prec = 2
    print(decimal.Decimal('1.0') / decimal.Decimal('3.0'))
print(decimal.Decimal('1.0') / decimal.Decimal('3.0'))
print('a+b=', decimal.Decimal('.13442') + decimal.Decimal('1.12312'))
print('还可以这样控制精度:', '%.2f' % a, '{0:.2f}'.format(a))

f1, f2 = Fraction(1, 2), Fraction(2, 3)
print(f1, '+', f2, '=', f1 + f2)
print('===================复数')
a = 2 + 3j
b = complex(3, 4)
print(a, '+', b, '=', a + b)

print('===================除法')
Пример #25
0
 def test_decimal(self):
     data = [decimal.Decimal('1234.183'), decimal.Decimal('8094.234')]
     type = pa.decimal(precision=7, scale=3)
     arr = pa.array(data, type=type)
     assert arr.to_pylist() == data
Пример #26
0
 def amount( self ):
   return decimal.Decimal(self.results[ 'payment_gross' ])
Пример #27
0
 def test_decimal_negative(self):
     data = [decimal.Decimal('-1234.234983'), decimal.Decimal('-8.094324')]
     type = pa.decimal(precision=10, scale=6)
     arr = pa.array(data, type=type)
     assert arr.to_pylist() == data
Пример #28
0
pi = 3.14159
answer = 42

print(int(pi))
print(float(answer))

print(int("1000", 3))  # base3

print(True)
print(False)
print(int(True))  # => 1
print(int(False))  # => 0
print(str(True))
print(issubclass(bool, int))  # => True

# Falsy
print()
print(bool(0))
print(bool(0.0))
print(bool(""))
print(bool("0"))  # => True
print(bool(None))
print(bool([]))
print(bool(()))
print(bool({}))
print(bool(set()))
print(bool(range(0)))
print(bool(decimal.Decimal(0)))
print(bool(fractions.Fraction(0, 10)))
Пример #29
0
import decimal
import math

print("Hello World!")

print(id(33))
print(type(3.22222))

print(9.8 * -7.2)
print(2e3)
print(5//2)

a = decimal.Decimal(10.0)
b = decimal.Decimal(3)
print(a+b)
print(a-b)
print(a/b)
print(a*b)
print(a**b)
# divmod(9/2)

print(math.pi)

print("以下の数字を入力してください:")
x = decimal.Decimal(input('x = '))
y = decimal.Decimal(input('y = '))
# print('%d + %d = %d' % (x, y, x+y))
print(('{0} + {1} = {2}').format(x, y, x+y))
# print('%d - %d = %d' % (x, y, x-y))
print(('{0} - {1} = {2}').format(x, y, x-y))
print(('{0} * {1} = {2}').format(x, y, x*y))
Пример #30
0
from pos.point_of_sale.verifications import mts as mt
from pos.point_of_sale.web import web
from pos.point_of_sale.bep import bep
from pos.point_of_sale.db_functions.dbactions import DBActions

db_agent = DBActions()
start_time = datetime.now()
pricepoints_options = 'single'
url_options = options.ref_variables() + options.refurl() + config.template
# ==================================================================> for 511 and 510
transguids = []
pricingguid = {}
transids = []
rebills_pids = []
pricepoint_type = 0
dynamic_price = decimal.Decimal('%d.%d' %
                                (random.randint(3, 19), random.randint(0, 99)))
merchantbillconfig = []

# ==================================================================================================> Begining of the script
for merchantid in config.merchants:
    try:
        if pricepoints_options == 'type':
            pricepoints = db_agent.pricepoint_type(merchantid,
                                                   [511, 501, 506])  # ,505
        elif pricepoints_options == 'list':
            pricepoints = db_agent.pricepoint_list(merchantid)
        else:
            pricepoints = config.pricepoints
        for pricepoint in pricepoints:
            # selected_language = random.choice(config.available_languages)
            try: