Exemplo n.º 1
0
def evaluate(self, context=None):
    item = self.get_argument(context)
    if item is None:
        return
    elif isinstance(item, float) and (math.isnan(item) or math.isinf(item)):
        return item
    elif not isinstance(item, (float, int, Decimal)):
        code = 'XPTY0004' if isinstance(item, str) else 'FORG0006'
        raise self.error(code, "invalid argument type {!r}".format(type(item)))

    precision = 0 if len(self) < 2 else self[1].evaluate(context)
    try:
        if isinstance(item, int):
            return round(item, precision)
        elif isinstance(item, Decimal):
            return round(item, precision)
        elif isinstance(item, Float10):
            return Float10(round(item, precision))
        return float(round(Decimal.from_float(item), precision))
    except TypeError as err:
        raise self.error('XPTY0004', err)
    except (DecimalException, OverflowError):
        if isinstance(item, Decimal):
            return Decimal.from_float(round(float(item), precision))
        return round(item, precision)
Exemplo n.º 2
0
def test_floats_in_tiny_interval_within_bounds(xlo, xhi, data, center):
    assume(not (math.isinf(next_down(center)) or math.isinf(next_up(center))))
    lo = Decimal.from_float(next_down(center)).next_plus()
    hi = Decimal.from_float(next_up(center)).next_minus()
    assert float(lo) < lo < center < hi < float(hi)
    val = data.draw(st.floats(lo, hi, exclude_min=xlo, exclude_max=xhi))
    assert lo < val < hi
Exemplo n.º 3
0
def market_and_business_value_updater():
    # Update every market row in DB
    for market in Market.objects.all():
        # Freeze market if no one owns any of its businesses
        if market.num_businesses == 0:
            market.started = False
            market.save()
        # If someone has bought one of the businesses
        if market.started == True:

            # Set range of change depending on volatility and growth rate
            low = float(Decimal.from_float(-.1)*market.volatility)
            high = float(market.growth_rate*market.volatility)

            # Randomly generate the market change
            change = Decimal.from_float(random.uniform(low, high))
            market.current_multiplier += change

            # print(f"Market = {market.name}, Change = {change}, Market_multiplier = {market.current_multiplier} Num businesses = {market.num_businesses}")

            # Save new current_multiplier to market in DB
            market.save()

            # Update all business values in DB
            for business in market.businesses.all():
                business.value = business.base_value*market.current_multiplier
                business.save()
def test_floats_in_tiny_interval_within_bounds(data, center):
    assume(not (math.isinf(next_down(center)) or math.isinf(next_up(center))))
    lo = Decimal.from_float(next_down(center)).next_plus()
    hi = Decimal.from_float(next_up(center)).next_minus()
    assert float(lo) < lo < center < hi < float(hi)
    val = data.draw(st.floats(lo, hi))
    assert lo < val < hi
Exemplo n.º 5
0
def test_lossy_serialization_warning(caplog):
    caplog.set_level(logging.WARNING, logger="great_expectations.core")

    d = (
        Decimal(7091.17117297555159893818) ** Decimal(2)
        + Decimal(7118.70008070942458289210) ** Decimal(2)
        + (Decimal(-1513.67274389594149397453)) ** Decimal(2)
    ) ** Decimal(1.5)
    f_1 = (
        7091.17117297555159893818 ** 2
        + 7118.70008070942458289210 ** 2
        + (-1513.67274389594149397453) ** 2
    ) ** 1.5
    f_2 = float(d)
    assert not (-1e-55 < Decimal.from_float(f_1) - d < 1e-55)
    assert not (-1e-55 < Decimal.from_float(f_2) - d < 1e-55)

    convert_to_json_serializable(d)
    assert len(caplog.messages) == 1
    assert caplog.messages[0].startswith("Using lossy conversion for decimal")

    caplog.clear()
    d = Decimal(0.1)
    f_1 = 0.1
    f_2 = float(d)

    assert -1e-55 < Decimal.from_float(f_1) - d < 1e-55
    assert -1e-55 < Decimal.from_float(f_2) - d < 1e-55
    convert_to_json_serializable(d)
    assert len(caplog.messages) == 0
Exemplo n.º 6
0
def excel_scan_teams(teams: list, season: str):  # 201

    start = time.time()
    number = 0
    sheet_line = 0

    while True:
        while number < len(teams):
            teamloop = teams[number]
            # ['sheet_%d' % sheetnb].write = book.add_sheet(teamloop, cell_overwrite_ok= True)
            print('')
            print(teamloop)
            print('')
            number += 1
            sheet_line += 1
            json_dict = vexdb_json("rankings", {
                "team": teamloop,
                "season": season
            })
            output = []
            for r in json_dict["result"]:
                line = 'Team = {} Wins = {} Losses = {} AP = {} Ranking in Current Match = {} Highest Score = {}' \
                    .format(r["team"], r["wins"], r["losses"], r["ap"], r["rank"], r["max_score"])
                datateam = '{}'.format(r["team"])
                datawins = '{}'.format(r["wins"])
                datalosses = '{}'.format(r["losses"])
                dataap = '{}'.format(r["ap"])
                datarank = '{}'.format(r["rank"])
                datamaxscore = '{}'.format(r["max_score"])
                if int(datawins) > int(datalosses):
                    sheet2.write(sheet_line, 6, "Positive", STYLE_RED)
                elif int(datawins) < int(datalosses):
                    sheet2.write(sheet_line, 6, "Negative", STYLE_BLUE)
                output.append(line)
                sheet2.write(sheet_line, 0, datateam)
                sheet2.write(sheet_line, 1, datawins)
                sheet2.write(sheet_line, 2, datalosses)
                sheet2.write(sheet_line, 3, dataap)
                sheet2.write(sheet_line, 4, datarank)
                sheet2.write(sheet_line, 5, datamaxscore)
                sheet_line += 1
            book.save("Data.xls")
            print('')
            decimal = (time.time() - start)
            decimal = Decimal.from_float(decimal).quantize(Decimal('0.0'))
            ave = (float(decimal) / (int(number)))
            ave = Decimal.from_float(ave).quantize(Decimal('0.0'))
            eta = (float(ave) * (int(len(teams) - (int(number)))))
            etatomin = (float(eta) / 60)
            etatomin = Decimal.from_float(etatomin).quantize(Decimal('0.0'))
            print(
                str(number) + "/" + str(len(teams)) + " Finished, Used " +
                str(decimal) + " seconds. Average " + str(ave) +
                " seconds each. ETA: " + str(etatomin) + " mins.")
        if number >= 5:
            number = 0
            sheet_line = 1
            print('\n reset and xls saved!')
            main()
Exemplo n.º 7
0
 def TranslateToDecimal(amount):
     '''金额的float类型转换为保留两位小数的Decimal类型,用于准确计算'''
     try:
         return Decimal.from_float(amount).quantize(Decimal('0.00'))
     except TypeError:
         if isinstance(amount, Decimal):
             return Decimal.from_float(float(amount)).quantize(
                 Decimal('0.00'))
Exemplo n.º 8
0
    def get(self, request):

        p2pproducts = P2PProduct.objects.filter(hide=False).filter(status=u'正在招标')

        p2p_list = []
        repaymentType = ''
        for p2p in p2pproducts:
            # 计算进度
            amount = Decimal.from_float(p2p.total_amount).quantize(Decimal('0.00'))
            percent = p2p.ordered_amount / amount * 100
            schedule = '{}%'.format(percent.quantize(Decimal('0.0'), 'ROUND_DOWN'))

            for pay_method, value in WANGDAI:
                if p2p.pay_method == u'日计息一次性还本付息':
                    repaymentType = 1
                    break
                if p2p.pay_method == u'日计息月付息到期还本':
                    repaymentType = 5
                    break
                if p2p.pay_method == u'先息后本':
                    repaymentType = 9
                    break
                if pay_method == p2p.pay_method:
                    repaymentType = value
                    break

            p2pequities = p2p.equities.all()
            subscribes = [{
                              "subscribeUserName": eq.user.username,
                              "amount": Decimal.from_float(eq.equity).quantize(Decimal('0.00')),
                              "validAmount": Decimal.from_float(eq.equity).quantize(Decimal('0.00')),
                              "addDate": timezone.localtime(eq.created_at).strftime("%Y-%m-%d %H:%M:%S"),
                              "status": "1",
                              "type": "0"
                          } for eq in p2pequities]

            reward = (p2p.activity.rule.rule_amount * 100).quantize(Decimal('0.0')) if p2p.activity else 0

            temp_p2p = {
                "projectId": str(p2p.pk),
                "title": p2p.name,
                "amount": amount,
                "schedule": schedule,
                "interestRate": '{}%'.format(Decimal.from_float(p2p.expected_earning_rate).quantize(Decimal('0.0'))+reward),
                "deadline": str(p2p.period),
                "deadlineUnit": u"月",
                "reward": '{}%'.format(0),#'{}%'.format(reward),
                "type": u"信用标" if p2p.category == u'证大速贷'else u"抵押标",
                "repaymentType": str(repaymentType),
                "subscribes": subscribes,
                "userName": md5(p2p.borrower_bankcard_bank_name.encode('utf-8')).hexdigest(),
                "amountUsedDesc": strip_tags(p2p.short_usage),
                "loanUrl": "https://{}/p2p/detail/{}".format(request.get_host(), p2p.id),
                "publishTime": timezone.localtime(p2p.publish_time).strftime("%Y-%m-%d %H:%M:%S")
            }
            p2p_list.append(temp_p2p)

        return HttpResponse(renderers.JSONRenderer().render(p2p_list, 'application/json'))
 def get_ws_wq(df_document_cut):
     stay_time_cut = df_document_cut['finish'] - df_document_cut[
         'come']  #得到逗留时间队列
     wait_time_cut = df_document_cut['wait']  #得到等待时间队列
     ws_cut = np.mean(stay_time_cut)  #平均逗留时间
     wq_cut = np.mean(wait_time_cut)  #平均排队等待时间
     ws_cut = Decimal.from_float(ws_cut).quantize(Decimal('0.0000'))
     wq_cut = Decimal.from_float(wq_cut).quantize(Decimal('0.0000'))
     return ws_cut, wq_cut
Exemplo n.º 10
0
 def _format_ohlc(result):
     return OHLC(
         result[0],
         Decimal.from_float(result[1]),
         Decimal.from_float(result[3]),
         Decimal.from_float(result[4]),
         Decimal.from_float(result[2]),
         Decimal.from_float(result[5]),
     )
Exemplo n.º 11
0
def func_sin(x, n):
    sin_aprox = 0
    coefs=[]
    for i in range(n):
        coef = (-1)**i
        num = x**(2*i+1)
        denom = math.factorial(2*i+1)
        sin_aprox += (Decimal.from_float(coef)) * ( Decimal.from_float((num))/Decimal.from_float((denom)))
        coefs.append(sin_aprox)
    return (sin_aprox,coefs)
Exemplo n.º 12
0
def getItemdetails(buyer_state, seller_state, item, item_tax_amount):
    if (buyer_state != seller_state):
        item_details = Item_details.objects.create(
            igst_tax_percentage=item.tax_percentage, igst_amt=item_tax_amount)
    else:
        item_details = Item_details.objects.create(
            sgst_tax_percentage=Decimal.from_float(item.tax_percentage / 2),
            cgst_tax_percentage=Decimal.from_float(item.tax_percentage / 2),
            sgst_amt=Decimal(item_tax_amount / 2),
            cgst_amt=Decimal(item_tax_amount / 2))
    return item_details
Exemplo n.º 13
0
    def test_saving_and_retrieving_items(self):
        create_two_agereements_with_periods()

        periods = Period.objects.all()

        self.assertEqual(periods.count(), 2)
        self.assertEqual(periods[0].start_date, date.today())
        self.assertEqual(periods[0].end_date, date(date.today().year+1, date.today().month, date.today().day))
        self.assertAlmostEqual(periods[0].agreement.credit_turnover, Decimal.from_float(1111.11), places=5)
        self.assertEqual(periods[1].start_date, date(date.today().year+1, date.today().month, date.today().day))
        self.assertEqual(periods[1].end_date, date(date.today().year+4, date.today().month, date.today().day))
        self.assertAlmostEqual(periods[1].agreement.credit_turnover, Decimal.from_float(5678.11), places=5)
Exemplo n.º 14
0
 def clean_uah_rate(self):
     """ Validation function to allow users enter rate with ',' instead of '.' """
     data = self.cleaned_data['uah_rate']
     if ',' in data:
         data = data.replace(',', '.')
     try:
         data = float(data)
         if data <= 0:
             raise ValidationError("Should be a number greater than 0")
         Decimal.from_float(data)
     except ValueError:
         raise ValidationError("Should be a number")
     return data
Exemplo n.º 15
0
    def string_to_decimal(cls, value):
        if value is None:
            return None

        value = value.replace(',', '')

        if not len(value):
            return Decimal.from_float(0.0)

        try:
            return parse_decimal(value)
        except Exception:
            return Decimal.from_float(0.0)
Exemplo n.º 16
0
def buy_coins():
    symbol = "DOGE" + BUY_WITH
    avg_market_price = binance_client.get_avg_price(symbol=symbol)

    quan = max_spending / float(avg_market_price["price"])
    sym_info = binance_client.get_symbol_info(symbol)

    lotSizeFilter = next(item for item in sym_info["filters"]
                         if item["filterType"] == "LOT_SIZE")
    #corrected_Quantity = math.floor(quan / float(lotSizeFilter["stepSize"])) * float(lotSizeFilter["stepSize"])
    corrected_Quantity = float(
        D.from_float(quan).quantize(
            D(str(lotSizeFilter["stepSize"]).rstrip("0"))))

    try:
        order = binance_client.create_order(symbol=symbol,
                                            side=Client.SIDE_BUY,
                                            type=Client.ORDER_TYPE_MARKET,
                                            quantity=corrected_Quantity)

        avg_price = avg_market_price["price"]
        print(
            f"Bought {corrected_Quantity} {symbol} (avg market pric was {avg_price}), fills:"
        )
        for fill in order["fills"]:
            qty = fill["qty"]
            price_fill = fill["price"]
            print(f"Qty: {qty}, Price: {price_fill}")

        # placing sell order
        sell_price = float(order["fills"][0]["price"]) * sell_price_mutiplier

        priceFilter = next(item for item in sym_info["filters"]
                           if item["filterType"] == "PRICE_FILTER")

        sell_price_filtered = float(
            D.from_float(sell_price).quantize(
                D(priceFilter["tickSize"].rstrip("0"))))

        print(f"Placing sell order at avg price: : {sell_price_filtered}")
        sell_order = binance_client.order_limit_sell(
            symbol=symbol,
            quantity=corrected_Quantity,
            price=sell_price_filtered)

        print(f"Placed sell order at avg price: {sell_price_filtered}")

    except BinanceAPIException as e:
        print(e)
    except BinanceOrderException as e:
        print(e)
Exemplo n.º 17
0
    def update_revenue_estimate(self):
        if self.ce_model_id:
            qty = self.quantity
            if not isinstance(qty, Decimal):
                qty = Decimal.from_float(qty)

            if not self.ce_unit_revenue_estimate:
                raise ValidationError(
                    'Must provide unit sales price estimate.')

            uc = self.ce_unit_revenue_estimate
            if not isinstance(uc, Decimal):
                uc = Decimal.from_float(uc)

            self.ce_revenue_estimate = uc * qty
Exemplo n.º 18
0
    def __init__(self, api, steps, stop, *args, **kwargs):
        super().__init__(api, *args, **kwargs)

        logger = getLogger(__name__)

        self.orders = []
        self.pending_order = None

        self.pivot = -1
        self.steps = steps
        self.stop = Decimal.from_float(stop)
        self.correction = Decimal.from_float(0.5)

        logger.info('ladder strategy started with steps={}, stop={}'.format(
            self.steps, self.stop))
Exemplo n.º 19
0
    def get(self, request):
        now = time.mktime(datetime.datetime.now().timetuple())
        project_list = []

        result = {
            'timestamp': now,
            'project_list': project_list
        }
        p2pproducts = P2PProduct.objects.select_related('warrant_company', 'activity').filter(hide=False).filter(
            status=u'正在招标').order_by('-priority')[0:5]

        for p2pproduct in p2pproducts:
            rate_vip = p2pproduct.activity.rule.rule_amount * 100 if p2pproduct.activity else 0
            rate_total = Decimal.from_float(p2pproduct.expected_earning_rate) + rate_vip

            income = 10000 * rate_total * Decimal(p2pproduct.period) / (12 * 100)
            income = float(income.quantize(Decimal('0.00')))

            # 进度
            amount = Decimal.from_float(p2pproduct.total_amount).quantize(Decimal('0.00'))
            percent = (p2pproduct.ordered_amount / amount) * 100
            percent = percent.quantize(Decimal('0.00'))

            obj = {
                'id': p2pproduct.id,
                'title': p2pproduct.name,
                #'title_url': 'https://{}/p2p/detail/{}'.format(request.get_host(), p2pproduct.id),
                'title_url': 'https://www.wanglibao.com/activity/xunlei_setp/?promo_token=xunlei9',
                'rate_year': p2pproduct.expected_earning_rate,
                'rate_vip': float(rate_vip),
                'income': income,
                'finance': float(p2pproduct.total_amount),
                'min_invest': float(100.00),
                'guarantor': p2pproduct.warrant_company.name,
                'finance_progress': float(percent),
                'finance_left': float(p2pproduct.remain),
                'repayment_period': p2pproduct.period * 30,
                'repayment_type': XUNLEI_PAY_WAY.get(p2pproduct.pay_method, 0),
                #'buy_url': 'https://{}/p2p/detail/{}?promo_token=xunlei'.format(request.get_host(), p2pproduct.id),
                #'buy_url': 'https://www.wanglibao.com/activity/xunleidenglu/?promo_token=xunlei9',
                'buy_url': 'https://www.wanglibao.com/activity/xunlei_setp/?promo_token=xunlei9',
                'finance_start_time': time.mktime(timezone.localtime(p2pproduct.publish_time).timetuple()),
                'finance_end_time': time.mktime(timezone.localtime(p2pproduct.end_time).timetuple()),
                'status': p2pproduct.status
            }
            project_list.append(obj)
        result.update(project_list=project_list)
        return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))
Exemplo n.º 20
0
def _to_decimal(amount):
    if isinstance(amount, Decimal):
        return amount
    elif isinstance(amount, float):
        return Decimal.from_float(amount)
    else:
        return Decimal(amount)
Exemplo n.º 21
0
class Product(models.Model):
    DISCOUNT_RATE = Decimal.from_float(0.10)

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    description = models.TextField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    sale_start = models.DateTimeField(blank=True, null=True, default=None)
    sale_end = models.DateTimeField(blank=True, null=True, default=None)
    photo = models.ImageField(blank=True,
                              null=True,
                              default=None,
                              upload_to='products')

    def is_on_sale(self):
        now = timezone.now()
        if self.sale_start:
            if self.sale_end:
                return self.sale_start <= now <= self.sale_end
            return self.sale_start <= now
        return False

    def get_rounded_price(self):
        return round(self.price, 2)

    def current_price(self):
        if self.is_on_sale():
            discounted_price = self.price * (1 - self.DISCOUNT_RATE)
            return round(discounted_price, 2)
        return self.get_rounded_price()

    def __repr__(self):
        return '<Product object ({}) "{}">'.format(self.id, self.name)
Exemplo n.º 22
0
def done(request, bill_id):
    bill = Bill.objects.get(pk=bill_id)
    if bill.voucher:
        v = bill.voucher
        v.used = True
        v.save()
    if hasattr(bill, 'servescharge'):
        print('sc')
        charge = bill.servescharge
        charge.paid = True
        charge.save()
    else:
        print('dc')
        charge = bill.depositcharge
        charge.paid = True
        charge.save()
        if hasattr(bill.customer, 'card'):
            card = bill.customer.card
            card.deposit += charge.deposit_amount
        else:
            card = Card(deposit=charge.deposit_amount, customer=bill.customer)
        card.save()
    if bill.customer:
        i = bill.valid_income()
        c = bill.customer
        c.credit += i
        c.save()
        if bill.customer.card:
            card = bill.customer.card
            card.deposit += Decimal.from_float(float(i) * CASH_BACK_PERCENTAGE)
            card.save()

    return render(request, 'reception/done.html', {'bill': bill})
Exemplo n.º 23
0
    def payAll(self):
        #获取购买的书籍信息
        sql = "call searchCart('" + self.logininfo[0] + "');"
        self.cursor.execute(sql)

        payBookID = []
        payPrice = []
        payNum = []
        totalPrices = Decimal.from_float(0.00)

        while True:
            CartInfo = self.cursor.fetchone()
            if CartInfo == None:
                break
            payBookID.append(CartInfo[0])
            payNum.append(CartInfo[5])
            payPrice.append(CartInfo[4] * CartInfo[5])
            totalPrices += CartInfo[4] * CartInfo[5]
        #检查余量合法
        for i in range(len(payBookID)):
            sql = "select BName,BStock from books where BookID = '" + payBookID[
                i] + "'"
            self.cursor.execute(sql)
            message = self.cursor.fetchone()
            if (message[1] < payNum[i]):
                QMessageBox.critical(
                    self, "Critical",
                    self.tr("库存不足(《" + message[0] + "》仅剩 " + str(message[1]) +
                            " 本)!"))
                return
        print("库存检查通过")
        #减少相应库存
        for i in range(len(payBookID)):
            sql = "update books set BStock = BStock - " + str(
                payNum[i]) + " where BookID = '" + payBookID[i] + "'"
            self.cursor.execute(sql)
        #付款信息输入
        self.payDialog = payDialog.payDialog(totalPrices, self)
        self.payDialog.exec_()

        payTime = time.strftime('%Y-%m-%d %H:%M:%S',
                                time.localtime(time.time()))
        payType = self.payDialog.payInfo[0]
        deliverType = self.payDialog.payInfo[1]

        #插入消费记录
        for i in range(len(payBookID)):
            sql = "insert into records values(null,'" + payBookID[
                i] + "','" + self.curUser + "','" + payTime + "'," + str(
                    payNum[i]) + "," + str(
                        payPrice[i]
                    ) + ",'" + payType + "','" + deliverType + "')"
            self.cursor.execute(sql)
        #清空购物车
        sql = "delete from carts where CusID = '" + self.curUser + "'"
        self.cursor.execute(sql)

        #提交
        self.connect.commit()
        self.rightTable("cart")
Exemplo n.º 24
0
def make_20ma(r2_sp):
    """计算20ma
    MA20 = 20天内收盘价之和/20
    """
    from copy import deepcopy
    from decimal import Decimal

    r2_sp_test = deepcopy(r2_sp)
    r3_sp_test = deepcopy(r2_sp)
    r2_sp_test[-1] = r2_sp_test[-2] * Decimal.from_float(1.1)

    if len(r2_sp_test) == 20:  # 如果收盘列表达到20天长度

        # print(r2_sp_test[-1],r2_sp_test[-2],r2_sp_test[-3],r2_sp_test[-4],r2_sp_test[-5],r2_sp_test[-6],r2_sp_test[-7],
        #       r2_sp_test[-8],r2_sp_test[-9],r2_sp_test[-10],r2_sp_test[-11],r2_sp_test[-12],r2_sp_test[-13],r2_sp_test[-14],
        #     r2_sp_test[-15],r2_sp_test[-16],r2_sp_test[-17],r2_sp_test[-18],r2_sp_test[-19],r2_sp_test[-20])

        ma20 = sum(r2_sp_test) / 20  # 计算ma20
        # print(ma20)
        return ma20, 0  # 返回ma20 和0

    elif len(r2_sp_test) > 20:  # 如果收盘列表天数 大于20

        r2_sp_test.pop(0)  # 除去列表头部的天数

        ma20 = sum(r2_sp_test) / 20  # 计算ma20

        r2_sp.pop(0)

        return ma20, r2_sp  # 返回ma20 和 除去头部天数的新列表
Exemplo n.º 25
0
def upgrade():
    op.add_column('request',
            sa.Column('numeric_base_payout', sa.Numeric(precision=15, scale=2),
                    default=0.0)
    )
    request = table('request',
            column('id', sa.Integer),
            column('base_payout', sa.Float),
            column('numeric_base_payout', sa.Numeric(precision=15, scale=2)),
    )
    conn = op.get_bind()
    requests_sel = select([request.c.id, request.c.base_payout])
    requests = conn.execute(requests_sel)
    for request_id, float_payout in requests:
        decimal_payout = Decimal.from_float(float_payout)
        decimal_payout *= 1000000
        update_stmt = update(request)\
                .where(request.c.id == request_id)\
                .values({
                    'numeric_base_payout': decimal_payout,
                })
        conn.execute(update_stmt)
    requests.close()
    op.drop_column('request', 'base_payout')
    op.alter_column('request',
            column_name='numeric_base_payout',
            new_column_name='base_payout',
            existing_type=sa.Numeric(precision=15, scale=2),
            existing_server_default=0.0)
Exemplo n.º 26
0
def get_trip_dist(start_lon, start_lat, end_lon, end_lat):
    """Calculate trip distance from pickup and delivery location

    When testing, dont calculate using a geocoding webservice.
    If Geocoding fails, fall back to using Euclidean distance
    """
    if not settings.TESTING:
        try:
            origin = str(start_lat) + ',' + str(start_lon)
            dest = str(end_lat) + ',' + str(end_lon)
            base_url = 'http://maps.googleapis.com/maps/api/distancematrix/json'
            headers = {'content-type': 'application/json'}
            data = {'origins': origin, 'destinations': dest, 'units': 'imperial'}
            response = requests.get(base_url, params=data, headers=headers)
            distance_meters = int(
                response.json()['rows'][0]['elements'][0]['distance']['value'])
            if distance_meters > 10:
                print 'using google trip dist'
                return distance_meters
        except:
            pass
    distance_meters = (sin(radians(start_lat)) *
                    sin(radians(end_lat)) +
                    cos(radians(start_lat)) *
                    cos(radians(end_lat)) *
                    cos(radians(start_lon - end_lon)))
    distance_meters = (degrees(acos(distance_meters))) * 69.09 * 1609.34
    print 'using naive trip dist'
    return Decimal.from_float(distance_meters)
Exemplo n.º 27
0
 def price_limit_reached(self, peer):
     if peer in self.strategy.pending_sent_offers:
         offer = self.strategy.pending_sent_offers[peer]
         return (offer.is_too_low
                 and round(Decimal.from_float(offer.rate), 5) >= round(
                     self.strategy.max_rate, 5))
     return False
Exemplo n.º 28
0
def _to_decimal(amount):
    if isinstance(amount, Decimal):
        return amount
    elif isinstance(amount, float):
        return Decimal.from_float(amount)
    else:
        return Decimal(amount)
Exemplo n.º 29
0
	def prices(self, quantities, requirements):
		"""
		Return the prices for specified parts at specified quantities.

		requirements must have a validate function that takes two arguments: an offer and the quantity
		quantities must be a dictionary mapping reference numbers to quantities 
		"""

		result = {}

		for ref,quantity in self.quantities.iteritems():
			info = self.match_info(ref)

			if len(info) > 1:
				result[ref] = {'error': 'Part not uniquely matched'}
				continue

			offers = filter(lambda x: requirements.validate(x, quantity), info[0].offers)

			best = Decimal.from_float(1e15)
			best_offer = None
			for offer in offers:
				price = offer.best_price(quantity)
				if price is not None and price < best:
					best = price
					best_offer = offer

			if best_offer is None:
				result[ref] = {'error', 'No valid offers found'}
			else:
				result[ref] = {'price': best, 'offer': offer}

		return result
Exemplo n.º 30
0
def processInteract(session, redis):
    today = date.today()
    start = datetime.now()
    start = start.replace(hour=0, minute=0, second=0, microsecond=0)
    orders = SinaWeiboInteractOrder.queryTodo(session, today)
    for order in orders:
        logging.info('process Interact order: {id}'.format(id=order.order_id))
        if SinaWeiboInteractChildOrder.search(session, order.order_id, start):
            continue
        child = SinaWeiboInteractChildOrder()
        child.parent_order_id = order.order_id
        child.create_at = datetime.now()
        child.user_id = order.user_id
        child.sina_blog_info_id = order.sina_blog_info_id
        child.purchase_number = order.purchase_number
        child.order_id = '{ss}{us}24'.format(
            ss=datetime.strftime(datetime.now(), '%Y%m%d%H%M%S'),
            us=str(Decimal.from_float(time.time()).quantize(
                Decimal('0.000')))[11:])
        child.status = ORDER_STATUS_DOING
        child.update_at = datetime.now()
        child.pay_at = order.pay_at
        child.order_amount = 0
        child.center = order.center
        child.priority = 1
        child.flag = ORDER_FLAG_DEFAULT
        session.add(child)
        session.commit()
Exemplo n.º 31
0
    def update_ui(self, state=True):
        """Updates various UI elements to match current settings,
        UI selections etc.
        """

        # Cost
        in_us = self.application.config['settings']['user']['in_us']
        cost_per_mb = Decimal("0.15") if in_us else Decimal("0.99")
        free = self.free_radiobutton.get_active()
        if free:
            cost = 0
        else:
            cost = Decimal.from_float(
                self.filesize / 1024.0 / 1024) / cost_per_mb
        self.cost_label.set_label("Estimated Cost: $%.2f" % round(cost, 2))
        self.cost_label.set_visible(cost!=0)

        # If not yet configured, force the user to do so first
        if not self.application.is_configured():
            self.send_button.set_label('Setup your Kindle first')
            self.configure_button.hide()
        else:
            self.send_button.set_label('Send to %s' % self.get_recipient())
            self.configure_button.show()

        # State
        if state:
            state = self.application.config['state']
            self.free_radiobutton.set_active(state['free'])
            self.objects.get_object('convert-checkbox').set_active(
                state['convert'])
Exemplo n.º 32
0
def test_convert_to(data):
    if abs(data) < Decimal('1e16'):
        number = convert_to.decimal(data)
        assert number == Decimal.from_float(data).quantize(Decimal('1e-8'))
    else:
        with pytest.raises(InvalidOperation):
            convert_to.decimal(data)
Exemplo n.º 33
0
def vyhodnot(scoredResults, scoredRunId):
    scoredRun = Run.objects.get(pk=int(scoredRunId))
    for scoredResult in scoredResults:
        scoredPerson = Person.objects.get(pk=scoredResult[0])
        databaseResult = Result.objects.get(run = scoredRun, person = scoredPerson)
        databaseResult.points = Decimal.from_float(scoredResult[2])
        databaseResult.save()
        databaseResult = None
    results = Result.objects.all()
    nullPoints()
    for i in range(len(results)):
        try:
            newPos = Position.objects.get(person=results[i].person, season=results[i].run.season)
            newPos.points += results[i].points
        except Position.DoesNotExist:
            newPos = Position(person=results[i].person, position_season = 0, season = results[i].run.season, position_category = 0, points = results[i].points)
        newPos.save()
    position = Position.objects.all().order_by('-points')
    categories = Category.objects.all()
    categoryPositionCursor = dict()
    for category in categories:
        categoryPositionCursor[category] = 1
    for i in range(len(position)):
        position[i].position_season = i+1
        position[i].position_category = categoryPositionCursor[position[i].person.category]
        categoryPositionCursor[position[i].person.category] += 1
        position[i].save()
Exemplo n.º 34
0
def to_decimal(value):
    """
    Преобразование значения в большое число с фиксированной дробной частью.
    При неудаче возвращается None
    """
    value = to_float(value)
    return None if value is None else Decimal.from_float(value)
Exemplo n.º 35
0
 def _distance(self, lat2, lng2):
     a = abs(self.lat - lat2)
     b = abs(self.lng - lng2)
     s = 2*math.asin(math.sqrt(math.pow(math.sin(a/2),2)+math.cos(self.lat)*math.cos(lat2)*math.pow(math.sin(b/2),2)))
     d = EARTH_R*Decimal.from_float(s)
     d_i = d.to_integral()
     return d_i
Exemplo n.º 36
0
def turtlePath(path):
    f = open(path, 'r')
    lines = f.readlines()
    num_obs, num_paths = lines[0].split(' ')
    num_obs = int(num_obs)
    num_paths = int(num_paths[0:len(num_paths)-1])
    obs = {}
    for ob in range(1, num_obs+1):
        x,y = lines[ob].split(' ')
        x = int(x)
        y = int(y[0:len(y)-1])
        obs[(x,y)] = True
    curr_pos = (0,0)
    #influences curr_pos delta for reach move based on direction turtle is facing
    curr_dir = (0,1)
    #max straight line distance from the origin
    max_dist = 0
    for l in range(num_obs+1, len(lines)):
        command = lines[l]
        c_type = command[0]
        # print(c_type)
        if c_type != 'M':
            curr_dir = change_dir(c_type, curr_dir)
        else:
            dist = int(command[2:len(command)-1])
            delta = collision_block(obs, curr_dir, curr_pos, dist)
            curr_pos = (curr_pos[0]+delta[0], curr_pos[1]+delta[1])
            hypotenuse = math.sqrt(curr_pos[0]**2 + curr_pos[1]**2)
            max_dist = hypotenuse if hypotenuse > max_dist else max_dist
    f.close()
    return float(round(Decimal.from_float(max_dist), 2))
Exemplo n.º 37
0
def simulation(request):
	query = request.GET.get('q')
	if query:
        # There was a query entered.
		results = Product.objects.filter(name=query)
	else:
   		# If no query was entered, simply return all objects
		results = None #Product.objects.all()
	date = timezone.now()
	try:
		salesID = Sale.objects.latest('id').id+1
	except ObjectDoesNotExist:
		salesID = 1
	items = Item.objects.filter(sale_id = salesID)
	print(items)
	subtotal = items.aggregate(Sum('total')).values()[0]
	cash = Cashier.objects.get(id=1)
	tax = Decimal.from_float((float(cash.tax)/100)).quantize(Decimal("0.00"))
	if subtotal is not None:
		total = (subtotal*(1+tax)).quantize(Decimal("0.00"))
	else:
		total = 0.00
	tax *= 100
	session = Sale(date_created = timezone.now(), subtotal = subtotal, tax = tax, payment = total, total = total)
	form = SaleForm(request.POST, instance=session)
	return render_to_response("simulation.html",{"form":form,"date": date, "sales": salesID, "ItemsParameter": items, "subtotal": subtotal, "tax":tax, "total":total, "results": results} , context_instance = RequestContext(request))
Exemplo n.º 38
0
def to_positive_decimal(value):
    """
    Преобразование значения в неотрицательное большое число с фиксированной дробной частью.
    При неудаче возвращается None
    """
    value = to_float(value)
    return None if value is None or value < 0 else Decimal.from_float(value)
Exemplo n.º 39
0
    def test_deserialize(self):
        # Given
        class TestMixResponse(BaseResponse):
            def __init__(self, text: str, success: bool, dec: Decimal,
                         uid: UUID, dt: datetime.datetime):
                self.text = text
                self.success = success
                self.dec = dec
                self.uid = uid
                self.dt = dt

        time = datetime.datetime.now()
        uid = uuid.uuid4()
        mix_response = TestMixResponse(text="bla bla",
                                       success=True,
                                       dec=Decimal.from_float(1.123),
                                       uid=uid,
                                       dt=time)

        # When
        response = mix_response.to_json()

        # Then
        assert response is not None
        assert mix_response.text == response["text"]
        assert mix_response.success == response["success"]
        assert 1.12 == response["dec"]
        assert str(mix_response.uid) == response["uid"]
        assert time.isoformat() == str(response["dt"])
Exemplo n.º 40
0
	def price_advanced(self, reference, quantity, requirements):
		"""
		Find the price of a single item subject to various requirements

		requirements must have a validate function that takes two arguments: an offer and the quantity		
		"""

		info = self.match_info(reference)

		if len(info) > 1:
			return {'error': 'Part not uniquely matched'}

		offers = filter(lambda x: requirements.validate(x, quantity), info[0].offers)

		best = Decimal.from_float(1e15)
		best_offer = None
		for offer in offers:
			price = offer.best_price(quantity)
			if price is not None and price < best:
				best = price
				best_offer = offer

		if best_offer is None:
			return {'error': 'No valid offers found'}
		else:
			return {'price': best, 'offer': offer}
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    # Use the decimal module for simplicity of implementation (and
    # hopefully correctness).
    from decimal import Decimal, ROUND_HALF_EVEN
 
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)
    d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    if return_int:
        return int(d)
    else:
        return float(d)
Exemplo n.º 42
0
    def __init__(self, owner, tag):
        self.owner = owner
        self.id = int(tag.attrib["key"])
        self.type = int(tag.attrib["type"])
        self.name = tag.attrib["name"]
        self.flags = int(tag.attrib.get("flags", 0))

        self._initial = Decimal.from_float(float(tag.attrib["initial"]))
Exemplo n.º 43
0
    def test_saving_and_retrieving_items(self):
        create_two_agereements_with_periods()

        agreements = Agreement.objects.all()

        self.assertEqual(agreements.count(), 2)
        self.assertEqual(agreements[1].start_date, date.today())
        self.assertEqual(agreements[1].end_date, date(date.today().year+1, date.today().month, date.today().day))
        self.assertEqual(agreements[1].negotiator.username, 'testUser')
        self.assertEqual(agreements[1].company.name, 'company1')
        self.assertAlmostEqual(agreements[1].credit_turnover, Decimal.from_float(1111.11), places=5)
        self.assertAlmostEqual(agreements[1].debit_turnover, Decimal.from_float(123.45), places=5)
        self.assertEqual(agreements[0].start_date, date.today())
        self.assertEqual(agreements[0].end_date, date(date.today().year+4, date.today().month, date.today().day))
        self.assertEqual(agreements[0].negotiator.username, 'testUser2')
        self.assertEqual(agreements[0].company.name, 'company2')
        self.assertAlmostEqual(agreements[0].credit_turnover, Decimal.from_float(5678.11), places=5)
        self.assertAlmostEqual(agreements[0].debit_turnover, Decimal.from_float(9876.45), places=5)
Exemplo n.º 44
0
    def get(self, api_type):
        # TODO: Get data

        self.lat = RAD_K * Decimal.from_float(_get_float(self.get_argument('lat', ''), DEFAULT_LAT))
        self.lng = RAD_K * Decimal.from_float(_get_float(self.get_argument('lng', ''), DEFAULT_LNG))

        # TODO: Query out less point
        presents = self.sql_session.query(Presentation).all()
        final_presents = []
        for present in presents:
            lat2 = RAD_K*present.lat
            lng2 = RAD_K*present.lng
            d = self._distance(lat2, lng2)
            if d < 1000:
                present.distance_string = '%d m' % d
            elif d<=5000:
                present.distance_string = '%.2f km' % (float(d)/1000)
            else:
                continue
            
            upload_file = FileList.by_present_id(present.p_key, self.sql_session).scalar()
            present.file_url = '/download/' + upload_file.key + '/' + upload_file.filename + '.' + upload_file.file_type
            present.img_url = '/download/' + upload_file.key + '/' + upload_file.filename + '.png'
            final_presents.append(present)
        if api_type == None:
            self.render('querypresent.html', presents = final_presents)
        elif api_type[1:] == 'json':
            return_data = []
            for present in final_presents:
                return_data.append({
                    'title': present.title,
                    'owner': present.owner,
                    'distance': present.distance_string,
                    'created': present.created.strftime("%Y-%m-%d %H:%M"),
                    'updated': present.updated.strftime("%Y-%m-%d %H:%M"),
                    'file_url': present.file_url,
                    'img_url': present.img_url,
                    'lat': str(present.lat),
                    'lng': str(present.lng)}
                )
            self.write(json.dumps(return_data))
        else:
            raise self.HTTPError(500, 'Unknown api type')
Exemplo n.º 45
0
def upgrade():
    # Add discriminator column
    op.add_column('modifier', sa.Column('_type', sa.String(length=20)))
    # Create new subclass tables
    op.create_table('absolute_modifier',
            sa.Column('id', sa.Integer,
                    sa.ForeignKey('modifier.id'),
                    primary_key=True),
            sa.Column('value', sa.Numeric(precision=15, scale=2),
                    nullable=False, server_default='0.0'))
    op.create_table('relative_modifier',
            sa.Column('id', sa.Integer, sa.ForeignKey('modifier.id'),
                    primary_key=True),
            sa.Column('value', sa.Float, nullable=False, server_default='0.0'))
    # Add new entries to the subclass tables for each modifier
    conn = op.get_bind()
    modifier_sel = select([modifier.c.id, modifier.c.value, modifier.c.type_])
    modifiers = conn.execute(modifier_sel)
    absolutes = []
    relatives = []
    for modifier_id, modifier_value, modifier_type in modifiers:
        if modifier_type == 'absolute':
            discriminator = 'AbsoluteModifier'
            absolutes.append({
                    'id': modifier_id,
                    'value': Decimal.from_float(modifier_value) * 1000000,
            })
        elif modifier_type == 'percentage':
            discriminator = 'RelativeModifier'
            relatives.append({
                    'id': modifier_id,
                    'value': modifier_value / 100,
            })
        update_stmt = update(modifier)\
                .where(modifier.c.id == modifier_id)\
                .values({
                        '_type': discriminator,
                })
        conn.execute(update_stmt)
    modifiers.close()
    op.bulk_insert(abs_table, absolutes)
    op.bulk_insert(rel_table, relatives)
    # Drop the old value and type_ columns from modifier
    op.drop_column('modifier', 'value')
    op.drop_column('modifier', 'type_')
    # Add the not-null constraint to the _type column
    op.alter_column('modifier',
            column_name='_type',
            nullable=True,
            existing_type=sa.String(length=20),
    )
    def recover(self, block):
        p      = block['prime']
        points = block['points']

        M = 0
        for point in points:
            point['li'] = self.lagrange_interpolate(point['id'], points)

            coof = point['li'].pop() 
            M   += Decimal.from_float(coof) * Decimal(point['shadow'])

        SECRET = round(M) % p

        return SECRET
Exemplo n.º 47
0
    def round(number, ndigits=None):
        return_int = False
        if ndigits is None:
            return_int = True
            ndigits = 0
        if hasattr(number, "__round__"):
            return number.__round__(ndigits)

        if ndigits < 0:
            raise NotImplementedError("negative ndigits not supported yet")
        exponent = Decimal("10") ** (-ndigits)
        d = Decimal.from_float(number).quantize(exponent, rounding=ROUND_HALF_EVEN)
        if return_int:
            return int(d)
        else:
            return float(d)
Exemplo n.º 48
0
def get_bin_decimals(v, max_sample=100, default=3):
    v = v.astype(float, raise_on_error=False)
    if len(v) <= max_sample:
        sample = v
    else:
        sample = random.sample(v, max_sample)

    num_decimals = []
    for e in sample:
        # num_decimals.append(str(e).find('.'))
        num_decimals.append(Decimal.from_float(e).as_tuple().exponent * -1)
    try:
        max_decimals = max(num_decimals)
    except:
        return default

    return min((max_decimals + 1), default)
Exemplo n.º 49
0
 def _parse_expression(self, tokens):
     expression = u''
     for token in tokens:
         if token in cal_callback._ops:
             expression += cal_callback._ops[token]
         else:
             num = Util.cn2dig(token)
             if num is None:
                 return None
             expression += str(num)
     res = None
     INFO("expression: " + expression)
     try:
         res = eval(expression)
         res = Decimal.from_float(res).quantize(Decimal('0.00'))
     except Exception, ex:
         ERROR("cal expression error:", ex)
Exemplo n.º 50
0
    def __init__(self, owner, tag):
        self.owner = owner

        self.amount = Decimal.from_float(float(tag.attrib["amount"]))
        self.account = next(
            x for x in self.owner.accounts if x.id == int(tag.attrib["account"])
        )
        self.mode_id = int(tag.attrib.get("paymode", 0))
        self.flags = int(tag.attrib.get("flags", 0)) or None
        self.payee_id = int(tag.attrib.get("payee", 0)) or None
        self.category_id = int(tag.attrib.get("category", 0)) or None

        self.wording = tag.attrib.get("wording")
        self.info = tag.attrib.get("info")

        self.date = from_gdate(int(tag.attrib["date"]))

        self.dst_account_id = int(tag.attrib.get("dst_account", 0)) or None

        self.id = None
Exemplo n.º 51
0
	def price(self, reference, quantity, seller):
		"""
		Return the best price for N parts from seller as a Decimal
		"""

		info = self.match_info(reference)
		can_seller = self._canonicalize_name(seller)

		if len(info) > 1:
			raise ArgumentError("part is not uniquely matched", reference=reference)

		offers = filter(lambda x: self._canonicalize_name(x.seller)==can_seller, info[0].offers)

		best = Decimal.from_float(1e15)
		for offer in offers:
			price = offer.best_price(quantity)
			if price is not None and price < best:
				best = price

		return best
Exemplo n.º 52
0
    def test_binary_floats(self):
        # check that floats hash equal to corresponding Fractions and Decimals

        # floats that are distinct but numerically equal should hash the same
        self.check_equal_hash(0.0, -0.0)

        # zeros
        self.check_equal_hash(0.0, D(0))
        self.check_equal_hash(-0.0, D(0))
        self.check_equal_hash(-0.0, D('-0.0'))
        self.check_equal_hash(0.0, F(0))

        # infinities and nans
        self.check_equal_hash(float('inf'), D('inf'))
        self.check_equal_hash(float('-inf'), D('-inf'))

        for _ in range(1000):
            x = random.random() * math.exp(random.random()*200.0 - 100.0)
            self.check_equal_hash(x, D.from_float(x))
            self.check_equal_hash(x, F.from_float(x))
Exemplo n.º 53
0
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
Exemplo n.º 54
0
def ppma(s, D=5):
    print('<tr><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th></tr>', file=utf8stdout)
    frmt = '<tr class="{}"><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>'
    letters_left = 256

    def find_context(i):
        k = 0
        for j in range(min(i,D)+1):
            f = s.find(s[i-j:i], 0, i-1)
            if f == -1:
                break
            k = j
        return s[i-k:i]
    def context_stat(i, cont):
        stat = defaultdict(lambda: 0)
        p = 0
        while p < i:
            p = s.find(cont, p, i - 1)
            if p == -1:
                break
            stat[s[p+len(cont)]] += 1
            p += 1
        return stat
    def calc_numbers(i, context, seen=set()):
        c = s[i]
        stat = context_stat(i, context)
        for b in seen:
            del stat[b]
        sm = sum(stat.values())
        if c in stat.keys():
            return ([sm], [], Fraction(stat[c], sm+1))
        else: # need esc
            if context:
                taus, p_escs, p_a = calc_numbers(i, context[1:], set(stat.keys()) | seen)
            else:
                nonlocal letters_left
                taus, p_escs, p_a = [], [], Fraction(1, letters_left)
                letters_left -= 1
            return ([sm] + taus, [Fraction(1, sm + 1)] + p_escs, p_a)

    def fracs(fs):
        return ' * '.join(map(frac, fs))
    def frac(f):
        if f.denominator == 1:
            return str(f.numerator)
        else:
            return '{} / {}'.format(f.numerator, f.denominator)

    i = 0
    total = Decimal(0)
    while i < len(s):
        letter = s[i]
        context = find_context(i)
        taus, p_escs, p_a = calc_numbers(i, context)
        if not context:
            context = '-'
        elif isinstance(context, bytes):
            context = ' '.join(map(hex, context))
        fr1 = fracs(p_escs)
        #if fr1:
        #    fr1 = '$'+fr1+'$'
        fr2 = frac(p_a)
        #if fr2:
        #    fr2 = '$'+fr2+'$'
        print(frmt.format('odd' if i % 2 == 0 else 'even',
                          letter,
                          context,
                          ';'.join(map(str,taus)),
                          fr1,
                          fr2), file=utf8stdout)
        i += 1
        total += sum(map(lambda p: Decimal.from_float(-log(p, 2)), p_escs + [p_a]))
    print('<tr><td colspan="5"><center>Total bits: {}</center></td></tr>'.format(ceil(total)+1), file=utf8stdout)
Exemplo n.º 55
0
def test_decimal_should_convert_to_model():
    field = s.Decimal()

    assert field.json_to_model(999999.0) == Decimal('999999')
    assert field.json_to_model(-0.99) == Decimal.from_float(-0.99)
    assert field.json_to_model(0) == Decimal('0')
Exemplo n.º 56
0
try:
    xrange
except NameError:
    xrange = range


def _get_float(s, default):
    try:
        f = float(s)
    except ValueError:
        return default
    return f

EARTH_R = Decimal('6371009') # Meter
RAD_K = Decimal.from_float(math.pi) / Decimal(180)

DEFAULT_LAT = 25.0724763
DEFAULT_LNG = 121.5185635

class QueryPresentHandler(BaseHandler):
    def get(self, api_type):
        # TODO: Get data

        self.lat = RAD_K * Decimal.from_float(_get_float(self.get_argument('lat', ''), DEFAULT_LAT))
        self.lng = RAD_K * Decimal.from_float(_get_float(self.get_argument('lng', ''), DEFAULT_LNG))

        # TODO: Query out less point
        presents = self.sql_session.query(Presentation).all()
        final_presents = []
        for present in presents:
Exemplo n.º 57
0
def cutDot(x):
    return Decimal.from_float(x).quantize(Decimal('0.0000000'))
Exemplo n.º 58
0
 def round_decimal(self, x):
     return Decimal.from_float(x).quantize(Decimal(".01"), rounding=ROUND_HALF_UP)
Exemplo n.º 59
0
 def __init__(self, payout):
     self.raw_payout = payout
     scaled = Decimal.from_float(self.raw_payout)
     scaled *= 1000000
     self.scaled_payout = scaled
Exemplo n.º 60
0
def format_picture(conv, value, picture):
    monetary = False
    decimal_point = conv['decimal_point']
    thousands_sep = conv[monetary and 'mon_thousands_sep' or 'thousands_sep']
    percent = '%'
    per_mille = '\u2030'
    minus_sign = '-'
    #grouping = conv[monetary and 'mon_grouping' or 'grouping']

    if isinstance(value, float):
        value = Decimal.from_float(value)
    elif isinstance(value, _STR_NUM_TYPES):
        value = Decimal(value)
    elif not isinstance(value, Decimal):
        raise ValueError(_('Picture requires a number convertable to decimal or float').format(picture))
        
    if value.is_nan():
        return 'NaN'
    
    isNegative = value.is_signed()
    
    pic, sep, negPic = picture.partition(';')
    if negPic and ';' in negPic:
        raise ValueError(_('Picture contains multiple picture sepearators {0}').format(picture))
    if isNegative and negPic:
        pic = negPic
    
    if len([c for c in pic if c in (percent, per_mille) ]) > 1:
        raise ValueError(_('Picture contains multiple percent or per_mille charcters {0}').format(picture))
    if percent in pic:
        value *= 100
    elif per_mille in pic:
        value *= 1000
        
    intPart, sep, fractPart = pic.partition(decimal_point)
    prefix = ''
    numPlaces = 0
    intPlaces = 0
    grouping = 0
    fractPlaces = 0
    suffix = ''
    if fractPart:
        if decimal_point in fractPart:
            raise ValueError(_('Sub-picture contains decimal point sepearators {0}').format(pic))
    
        for c in fractPart:
            if c.isdecimal():
                numPlaces += 1
                fractPlaces += 1
                if suffix:
                    raise ValueError(_('Sub-picture passive character {0} between active characters {1}').format(c, fractPart))
            else:
                suffix += c

    intPosition = 0                
    for c in reversed(intPart):
        if c.isdecimal() or c == '#' or c == thousands_sep:
            if prefix:
                raise ValueError(_('Sub-picture passive character {0} between active characters {1}').format(c, intPart))
        if c.isdecimal():
            numPlaces += 1
            intPlaces += 1
            intPosition += 1
            prefix = ''
        elif c == '#':
            numPlaces += 1
            intPosition += 1
        elif c == thousands_sep:
            if not grouping:
                grouping = intPosition
        else:
            prefix = c + prefix

    if not numPlaces and prefix != minus_sign:
            raise ValueError(_('Sub-picture must contain at least one digit position or sign character {0}').format(pic))
    if intPlaces == 0 and fractPlaces == 0:
        intPlaces = 1
    
    return format_decimal(value, intPlaces=intPlaces, fractPlaces=fractPlaces, 
                          sep=thousands_sep, dp=decimal_point, grouping=grouping,
                          pos=prefix,
                          neg=prefix if negPic else prefix + minus_sign,
                          trailpos=suffix,
                          trailneg=suffix)