Ejemplo n.º 1
0
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin
from django.core.mail import EmailMessage, EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.contrib.sites.shortcuts import get_current_site
from mibandapp.tasks import send_create_account_email, send_order_email, send_payment_recieved_email, send_create_account_email_checkout, send_push_notification, notify_admin_incomplete_payment
import decimal
from django.core import serializers
from pywebpush import webpush

import requests
import json
# Create your views here.

decimal.Context(prec=2, rounding=decimal.ROUND_UP)


# Index View
class IndexView(TemplateView):
    template_name = 'generic/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['products'] = Product.featured.all()[:6]
        context['sliders'] = ProductSlider.active.all()
        context['brands'] = Brand.objects.all()[:4]
        return context


class ProductsAll(ListView):
Ejemplo n.º 2
0
 def __init__(self, precision, scale):
     self.context = decimal.Context(prec=precision)
     self.scale_format = decimal.Decimal(10)**-scale
Ejemplo n.º 3
0
def square_root(n, prec=50):
    return int(
        decimal.Decimal(n).sqrt(context=decimal.Context(
            prec=prec)).to_integral_exact(rounding=decimal.ROUND_FLOOR))
Ejemplo n.º 4
0
def test_two_sum(i, f):
    with decimal.localcontext(decimal.Context(prec=40)):
        a = Decimal(i) + Decimal(f)
        s, r = two_sum(i, f)
        b = Decimal(s) + Decimal(r)
        assert_almost_equal(a, b, atol=Decimal(tiny), rtol=Decimal(0))
Ejemplo n.º 5
0
    :param nan_display: if `x` is :attr:`numpy:numpy.nan` then return this value
    :param as_string: return integer as a formatted string (EX: 1,000,000)
    :return: integer value
    :rtype: int
    """
    try:
        if not np.isnan(x) and not np.isinf(x):
            return fmt.format(int(x)) if as_string else int(x)
        return nan_display
    except BaseException:
        return nan_display


# hack to solve issues with formatting floats with a precision more than 4 decimal points
# https://stackoverflow.com/questions/38847690/convert-float-to-string-without-scientific-notation-and-false-precision
DECIMAL_CTX = decimal.Context()
DECIMAL_CTX.prec = 20


def json_float(x,
               precision=2,
               nan_display="nan",
               inf_display="inf",
               as_string=False):
    """
    Convert value to float to be used within JSON output

    :param x: value to be converted to integer
    :param precision: precision of float to be returned
    :param nan_display: if `x` is :attr:`numpy:numpy.nan` then return this value
    :param inf_display: if `x` is :attr:`numpy:numpy.inf` then return this value
Ejemplo n.º 6
0
    def pre_pay(self, request):
        """
        返回跳转信息{'message': message,'form': form}供跳转js使用,message包含报错信息
            form包含跳转信息
        :param request:
        :return:
        """
        if not request.user.wanglibaouserprofile.id_is_valid:
            return self.render_to_response({
                'message': u'请先进行实名认证'
            })
        form = dict()
        message = ''
        try:
            amount_str = request.POST.get('amount', '')
            amount = decimal.Decimal(amount_str). \
                quantize(TWO_PLACES, context=decimal.Context(traps=[decimal.Inexact]))
            amount_str = str(amount)
            if amount <= 0:
                # todo handler the raise
                raise decimal.DecimalException()

            gate_id = request.POST.get('gate_id', '')
            bank = Bank.objects.get(gate_id=gate_id)

            # Store this as the default bank
            request.user.wanglibaouserprofile.deposit_default_bank_name = bank.name
            request.user.wanglibaouserprofile.save()

            pay_info = PayInfo()
            pay_info.amount = amount
            pay_info.total_amount = amount
            pay_info.type = PayInfo.DEPOSIT
            pay_info.status = PayInfo.INITIAL
            pay_info.user = request.user
            pay_info.bank = bank
            pay_info.channel = "huifu"
            pay_info.request_ip = get_client_ip(request)

            order = OrderHelper.place_order(request.user, Order.PAY_ORDER, pay_info.status,
                                            pay_info=model_to_dict(pay_info))
            pay_info.order = order
            pay_info.save()

            post = {
                'OrdId': pay_info.pk,
                'GateId': gate_id,
                'OrdAmt': amount_str
            }

            form = self.pay(post)
            pay_info.request = str(form)
            pay_info.status = PayInfo.PROCESSING
            pay_info.save()
            OrderHelper.update_order(order, request.user, pay_info=model_to_dict(pay_info), status=pay_info.status)

            # 处理第三方渠道的用户充值回调
            CoopRegister(request).process_for_recharge(request.user, order.id)
        except decimal.DecimalException:
            message = u'金额格式错误'
        except Bank.DoesNotExist:
            message = u'请选择有效的银行'
        except (socket.error, SignException) as e:
            message = PayResult.RETRY
            pay_info.status = PayInfo.FAIL
            pay_info.error_message = str(e)
            pay_info.save()
            OrderHelper.update_order(order, request.user, pay_info=model_to_dict(pay_info), status=pay_info.status)
            logger.fatal('sign error! order id: ' + str(pay_info.pk) + ' ' + str(e))

        result = {
            'message': message,
            'form': form
        }

        return result
Ejemplo n.º 7
0
import statsmodels.api as sm
import operator
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import confusion_matrix
from unicodedata import normalize

from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import csv
from nltk.corpus import stopwords
from nltk import stem
from nltk.stem import RSLPStemmer
import re
import decimal

decimal.setcontext(decimal.Context(prec=4))
D = decimal.Decimal
import collections as col
#######################################################################
#######################################################################
#######################################################################
#######################################################################
# classe para filtrgagem dos textos


class ProcLing():
    def __init__(self, lista):
        self.lista = lista

    def retiraAcentuacao(self):
        lista_sem_acentos = []
Ejemplo n.º 8
0
import decimal
from decimal import ROUND_HALF_UP, Decimal
from typing import Any, Dict, Optional, Union, cast

from .currency import CurrencyValue, DefaultCurrency, DefaultCurrencyValue
from .exceptions import ConversionError
from .money import Money, MoneyType

RoundingContext = decimal.Context(rounding=ROUND_HALF_UP)


class Rate(Money):
    _currency: None

    @classmethod
    def from_sub_units(
        cls,
        amount: Optional[Union[MoneyType, Decimal, int, float, str, object]],
        currency: Optional[Union[DefaultCurrencyValue, CurrencyValue, str]] = DefaultCurrency,
        value: Optional[Union[MoneyType, Decimal, int, float, str]] = None,
        currency_code: Optional[str] = None,
        **kwargs: Any,
    ) -> "Rate":
        raise ConversionError("Rates cannot be created from sub units")

    @classmethod
    def from_dict(cls, input_dict: Dict) -> "Rate":
        return cls(**input_dict)

    def __init__(
        self,
Ejemplo n.º 9
0
def calculate_iteratively(steps_number, edge_costs, memory_profiler=None):
    context = decimal.Context(prec=50)
    decimal.setcontext(context)
    recursive_solution = RecursiveSolution(edge_costs, steps_number,
                                           memory_profiler)
    return recursive_solution.calculate_path_sum(steps_number)
Ejemplo n.º 10
0
class Value:
    CTX = decimal.Context(prec=60, Emin=-27, Emax=27)

    def __init__(self,
                 value: Union[Number, str] = 0,
                 unit: str = "",
                 fmt=Format()):
        assert 1 <= fmt.max_nr_digits <= 30
        assert -8 <= fmt.min_offset <= fmt.max_offset <= 8
        assert fmt.parse_clamp_min < fmt.parse_clamp_max
        assert fmt.printable_min < fmt.printable_max
        self._unit = unit
        self.fmt = fmt
        if isinstance(value, str):
            self._value = math.nan
            self.parse(value)
        else:
            self._value = decimal.Decimal(value, context=Value.CTX)

    def __repr__(self) -> str:
        return (f"{self.__class__.__name__}(" + repr(self._value) +
                f", '{self._unit}', {self.fmt})")

    def __str__(self) -> str:
        fmt = self.fmt
        if fmt.assume_infinity and abs(self._value) >= 10**(
            (fmt.max_offset + 1) * 3):
            return ("-" if self._value < 0 else
                    "") + "\N{INFINITY}" + fmt.space_str + self._unit
        if self._value < fmt.printable_min:
            return fmt.unprintable_under + self._unit
        if self._value > fmt.printable_max:
            return fmt.unprintable_over + self._unit

        if self._value == 0:
            offset = 0
        else:
            offset = clamp_value(int(math.log10(abs(self._value)) // 3),
                                 fmt.min_offset, fmt.max_offset)

        real = float(self._value) / (10**(offset * 3))

        if fmt.max_nr_digits < 3:
            formstr = ".0f"
        else:
            max_digits = fmt.max_nr_digits + (
                (1 if not fmt.fix_decimals and abs(real) < 10 else 0) +
                (1 if not fmt.fix_decimals and abs(real) < 100 else 0))
            formstr = "." + str(max_digits - 3) + "f"

        if self.fmt.allways_signed:
            formstr = "+" + formstr
        result = format(real, formstr)

        if float(result) == 0.0:
            offset = 0

        if self.fmt.allow_strip and "." in result:
            result = result.rstrip("0").rstrip(".")

        return result + fmt.space_str + PREFIXES[offset + 8] + self._unit

    def __int__(self):
        return round(self._value)

    def __float__(self):
        return float(self._value)

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value: Number):
        self._value = decimal.Decimal(value, context=Value.CTX)

    def parse(self, value: str) -> "Value":
        if isinstance(value, Number):
            self.value = value
            return self

        value = value.replace(" ", "")  # Ignore spaces

        if self._unit and (
                value.endswith(self._unit) or
            (self.fmt.parse_sloppy_unit
             and value.lower().endswith(self._unit.lower()))):  # strip unit
            value = value[:-len(self._unit)]

        factor = 1
        if self.fmt.parse_sloppy_kilo and value[-1] == "K":  # fix for e.g. KHz
            value = value[:-1] + "k"
        if value[-1] in PREFIXES:
            factor = 10**((PREFIXES.index(value[-1]) - 8) * 3)
            value = value[:-1]

        if self.fmt.assume_infinity and value == "\N{INFINITY}":
            self._value = math.inf
        elif self.fmt.assume_infinity and value == "-\N{INFINITY}":
            self._value = -math.inf
        else:
            try:
                self._value = (decimal.Decimal(value, context=Value.CTX) *
                               decimal.Decimal(factor, context=Value.CTX))
            except decimal.InvalidOperation:
                raise ValueError
            self._value = clamp_value(self._value, self.fmt.parse_clamp_min,
                                      self.fmt.parse_clamp_max)
        return self

    @property
    def unit(self) -> str:
        return self._unit
Ejemplo n.º 11
0
def process_cpd_blockfeed():
    LATEST_BLOCK_INIT = {
        'block_index': config.BLOCK_FIRST,
        'block_time': None,
        'block_hash': None
    }
    mongo_db = config.mongo_db

    def blow_away_db():
        mongo_db.processed_blocks.drop()
        mongo_db.tracked_assets.drop()
        mongo_db.trades.drop()
        mongo_db.balance_changes.drop()
        mongo_db.asset_market_info.drop()
        mongo_db.asset_marketcap_history.drop()
        mongo_db.pair_market_info.drop()
        mongo_db.btc_open_orders.drop()
        mongo_db.asset_extended_info.drop()
        mongo_db.transaction_stats.drop()
        mongo_db.feeds.drop()
        mongo_db.wallet_stats.drop()
        mongo_db.wallet_messages.drop()

        mongo_db.app_config.update(
            {},
            {
                'db_version': config.DB_VERSION,
                'running_testnet': config.TESTNET,
                'counterpartyd_db_version_major': None,
                'counterpartyd_db_version_minor': None,
                'counterpartyd_running_testnet': None,
                'last_block_assets_compiled': config.
                BLOCK_FIRST,  #for asset data compilation in events.py (resets on reparse as well)
            },
            upsert=True)
        app_config = mongo_db.app_config.find()[0]

        for asset in [config.XCP, config.BTC]:
            base_asset = {
                'asset': asset,
                'owner': None,
                'divisible': True,
                'locked': False,
                'total_issued': None,
                '_at_block':
                config.BLOCK_FIRST,  #the block ID this asset is current for
                '_history': []  #to allow for block rollbacks
            }
            mongo_db.tracked_assets.insert(base_asset)

        mongo_db.wallet_messages.insert({
            '_id': 0,
            'when': calendar.timegm(time.gmtime()),
            'message': None,
        })

        #reinitialize some internal counters
        config.CURRENT_BLOCK_INDEX = 0
        config.LAST_MESSAGE_INDEX = -1
        config.cw_last_message_seq = 0

        return app_config

    def prune_my_stale_blocks(max_block_index):
        assert isinstance(max_block_index, int)
        if max_block_index <= config.BLOCK_FIRST:
            max_block_index = config.BLOCK_FIRST + 1
        if not mongo_db.processed_blocks.find_one(
            {"block_index": max_block_index}):
            raise Exception(
                "Can't roll back to specified block index: %i doesn't exist in database"
                % max_block_index)

        logging.warn("Pruning to block %i ..." % (max_block_index))
        mongo_db.processed_blocks.remove(
            {"block_index": {
                "$gt": max_block_index
            }})
        mongo_db.balance_changes.remove(
            {"block_index": {
                "$gt": max_block_index
            }})
        mongo_db.trades.remove({"block_index": {"$gt": max_block_index}})
        mongo_db.asset_marketcap_history.remove(
            {"block_index": {
                "$gt": max_block_index
            }})
        mongo_db.transaction_stats.remove(
            {"block_index": {
                "$gt": max_block_index
            }})

        #to roll back the state of the tracked asset, dive into the history object for each asset that has
        # been updated on or after the block that we are pruning back to
        assets_to_prune = mongo_db.tracked_assets.find(
            {'_at_block': {
                "$gt": max_block_index
            }})
        for asset in assets_to_prune:
            logging.info(
                "Pruning asset %s (last modified @ block %i, pruning to state at block %i)"
                % (asset['asset'], asset['_at_block'], max_block_index))
            prev_ver = None
            while len(asset['_history']):
                prev_ver = asset['_history'].pop()
                if prev_ver['_at_block'] <= max_block_index:
                    break
            if prev_ver:
                if prev_ver['_at_block'] > max_block_index:
                    #even the first history version is newer than max_block_index.
                    #in this case, just remove the asset tracking record itself
                    mongo_db.tracked_assets.remove({'asset': asset['asset']})
                else:
                    #if here, we were able to find a previous version that was saved at or before max_block_index
                    # (which should be prev_ver ... restore asset's values to its values
                    prev_ver['_id'] = asset['_id']
                    prev_ver['_history'] = asset['_history']
                    mongo_db.tracked_assets.save(prev_ver)

        config.LAST_MESSAGE_INDEX = -1
        config.CAUGHT_UP = False
        latest_block = mongo_db.processed_blocks.find_one(
            {"block_index": max_block_index})
        return latest_block

    def publish_mempool_tx():
        """fetch new tx from mempool"""
        tx_hashes = []
        mempool_txs = mongo_db.mempool.find(projection={'tx_hash': True})
        for mempool_tx in mempool_txs:
            tx_hashes.append(str(mempool_tx['tx_hash']))

        params = None
        if len(tx_hashes) > 0:
            params = {
                'filters': [{
                    'field': 'tx_hash',
                    'op': 'NOT IN',
                    'value': tx_hashes
                }, {
                    'field':
                    'category',
                    'op':
                    'IN',
                    'value': ['sends', 'btcpays', 'issuances', 'dividends']
                }],
                'filterop':
                'AND'
            }
        new_txs = util.call_jsonrpc_api("get_mempool",
                                        params,
                                        abort_on_error=True)

        for new_tx in new_txs['result']:
            tx = {
                'tx_hash': new_tx['tx_hash'],
                'command': new_tx['command'],
                'category': new_tx['category'],
                'bindings': new_tx['bindings'],
                'timestamp': new_tx['timestamp'],
                'viewed_in_block': config.CURRENT_BLOCK_INDEX
            }

            mongo_db.mempool.insert(tx)
            del (tx['_id'])
            tx['_category'] = tx['category']
            tx['_message_index'] = 'mempool'
            logging.debug("Spotted mempool tx: %s" % tx)
            util.store_wallet_message(tx,
                                      json.loads(tx['bindings']),
                                      decorate=False)

    def clean_mempool_tx():
        """clean mempool transactions older than MAX_REORG_NUM_BLOCKS blocks"""
        mongo_db.mempool.remove({
            "viewed_in_block": {
                "$lt": config.CURRENT_BLOCK_INDEX - config.MAX_REORG_NUM_BLOCKS
            }
        })

    config.CURRENT_BLOCK_INDEX = 0
    config.LAST_MESSAGE_INDEX = -1
    config.BLOCKCHAIN_SERVICE_LAST_BLOCK = 0  #simply for printing/alerting purposes
    config.CAUGHT_UP_STARTED_EVENTS = False
    #^ set after we are caught up and start up the recurring events that depend on us being caught up with the blockchain

    #grab our stored preferences, and rebuild the database if necessary
    app_config = mongo_db.app_config.find()
    assert app_config.count() in [0, 1]
    if (app_config.count() == 0 or config.REPARSE_FORCED
            or app_config[0]['db_version'] != config.DB_VERSION
            or app_config[0]['running_testnet'] != config.TESTNET):
        if app_config.count():
            logging.warn(
                "energyblockd database version UPDATED (from %i to %i) or testnet setting changed (from %s to %s), or REINIT forced (%s). REBUILDING FROM SCRATCH ..."
                % (app_config[0]['db_version'], config.DB_VERSION,
                   app_config[0]['running_testnet'], config.TESTNET,
                   config.REPARSE_FORCED))
        else:
            logging.warn(
                "energyblockd database app_config collection doesn't exist. BUILDING FROM SCRATCH..."
            )
        app_config = blow_away_db()
        my_latest_block = LATEST_BLOCK_INIT
    else:
        app_config = app_config[0]
        #get the last processed block out of mongo
        my_latest_block = mongo_db.processed_blocks.find_one(
            sort=[("block_index", pymongo.DESCENDING)])
        if my_latest_block:
            my_latest_block = prune_my_stale_blocks(
                my_latest_block['block_index'])
        else:
            config.CURRENT_BLOCK_INDEX = LATEST_BLOCK_INIT

    while True:
        try:
            running_info = util.call_jsonrpc_api("get_running_info",
                                                 abort_on_error=True)
            if 'result' not in running_info:
                raise AssertionError("Could not contact energypartyd")
            running_info = running_info['result']
        except Exception as e:
            logging.warn(
                str(e) + " -- Waiting 30 seconds before trying again...")
            time.sleep(30)
            continue

        if running_info['last_message_index'] == -1:
            logging.warn(
                "No last_message_index returned. Waiting until energypartyd has messages..."
            )
            time.sleep(30)
            continue

        wipeState = False
        updatePrefs = False
        if    app_config['counterpartyd_db_version_major'] is None \
           or app_config['counterpartyd_db_version_minor'] is None \
           or app_config['counterpartyd_running_testnet'] is None:
            updatePrefs = True
        elif running_info['version_major'] != app_config[
                'counterpartyd_db_version_major']:
            logging.warn(
                "energypartyd MAJOR DB version change (we built from %s, energypartyd is at %s). Wiping our state data."
                % (app_config['counterpartyd_db_version_major'],
                   running_info['version_major']))
            wipeState = True
            updatePrefs = True
        elif running_info['version_minor'] != app_config[
                'counterpartyd_db_version_minor']:
            logging.warn(
                "energypartyd MINOR DB version change (we built from %s.%s, energypartyd is at %s.%s). Wiping our state data."
                %
                (app_config['counterpartyd_db_version_major'],
                 app_config['counterpartyd_db_version_minor'],
                 running_info['version_major'], running_info['version_minor']))
            wipeState = True
            updatePrefs = True
        elif running_info.get(
                'running_testnet',
                False) != app_config['counterpartyd_running_testnet']:
            logging.warn(
                "energypartyd testnet setting change (from %s to %s). Wiping our state data."
                % (app_config['counterpartyd_running_testnet'],
                   running_info['running_testnet']))
            wipeState = True
            updatePrefs = True
        if wipeState:
            app_config = blow_away_db()
        if updatePrefs:
            app_config['counterpartyd_db_version_major'] = running_info[
                'version_major']
            app_config['counterpartyd_db_version_minor'] = running_info[
                'version_minor']
            app_config['counterpartyd_running_testnet'] = running_info[
                'running_testnet']
            mongo_db.app_config.update({}, app_config)

            #reset my latest block record
            my_latest_block = LATEST_BLOCK_INIT
            config.CAUGHT_UP = False  #You've Come a Long Way, Baby

        last_processed_block = running_info['last_block']

        if last_processed_block['block_index'] is None:
            logging.warn(
                "energypartyd has no last processed block (probably is reparsing). Waiting 5 seconds before trying again..."
            )
            time.sleep(5)
            continue

        if my_latest_block['block_index'] < last_processed_block['block_index']:
            #need to catch up
            config.CAUGHT_UP = False

            cur_block_index = my_latest_block['block_index'] + 1
            #get the blocktime for the next block we have to process
            try:
                cur_block = util.call_jsonrpc_api(
                    "get_block_info", {'block_index': cur_block_index},
                    abort_on_error=True)['result']
            except Exception as e:
                logging.warn(
                    str(e) + " Waiting 5 seconds before trying again...")
                time.sleep(5)
                continue
            cur_block['block_time_obj'] = datetime.datetime.utcfromtimestamp(
                cur_block['block_time'])
            cur_block['block_time_str'] = cur_block[
                'block_time_obj'].isoformat()

            try:
                block_data = util.call_jsonrpc_api(
                    "get_messages", {'block_index': cur_block_index},
                    abort_on_error=True)['result']
            except Exception as e:
                logging.warn(
                    str(e) + " Waiting 15 seconds before trying again...")
                time.sleep(15)
                continue

            #parse out response (list of txns, ordered as they appeared in the block)
            for msg in block_data:
                msg_data = json.loads(msg['bindings'])

                if msg['message_index'] != config.LAST_MESSAGE_INDEX + 1 and config.LAST_MESSAGE_INDEX != -1:
                    logging.error(
                        "BUG: MESSAGE RECEIVED NOT WHAT WE EXPECTED. EXPECTED: %s, GOT: %s: %s (ALL MSGS IN get_messages PAYLOAD: %s)..."
                        % (config.LAST_MESSAGE_INDEX + 1, msg['message_index'],
                           msg, [m['message_index'] for m in block_data]))
                    my_latest_block = prune_my_stale_blocks(
                        cur_block_index - config.MAX_FORCED_REORG_NUM_BLOCKS)
                    break
                    #sys.exit(1) #FOR NOW

                if msg['message_index'] <= config.LAST_MESSAGE_INDEX:
                    logging.warn("BUG: IGNORED old RAW message %s: %s ..." %
                                 (msg['message_index'], msg))
                    continue

                logging.info("Received message %s: %s ..." %
                             (msg['message_index'], msg))

                status = msg_data.get('status', 'valid').lower()
                if status.startswith('invalid'):
                    if last_processed_block['block_index'] - my_latest_block[
                            'block_index'] < config.MAX_REORG_NUM_BLOCKS:
                        util.store_wallet_message(msg, msg_data)
                    config.LAST_MESSAGE_INDEX = msg['message_index']
                    continue

                #track message types, for compiling of statistics
                if msg['command'] == 'insert' \
                   and msg['category'] not in ["debits", "credits", "order_matches", "bet_matches",
                       "order_expirations", "bet_expirations", "order_match_expirations", "bet_match_expirations", "bet_match_resolutions"]:
                    try:
                        mongo_db.transaction_stats.insert({
                            'block_index':
                            cur_block_index,
                            'block_time':
                            cur_block['block_time_obj'],
                            'category':
                            msg['category']
                        })
                    except pymongo.errors.DuplicateKeyError as e:
                        logging.exception(e)

                #HANDLE REORGS
                if msg['command'] == 'reorg':
                    logging.warn("Blockchain reorginization at block %s" %
                                 msg_data['block_index'])
                    #prune back to and including the specified message_index
                    my_latest_block = prune_my_stale_blocks(
                        msg_data['block_index'] - 1)
                    config.CURRENT_BLOCK_INDEX = msg_data['block_index'] - 1

                    running_info = util.call_jsonrpc_api(
                        "get_running_info", abort_on_error=True)['result']
                    config.LAST_MESSAGE_INDEX = running_info[
                        'last_message_index']

                    if last_processed_block['block_index'] - my_latest_block[
                            'block_index'] < config.MAX_REORG_NUM_BLOCKS:
                        msg_data[
                            '_last_message_index'] = config.LAST_MESSAGE_INDEX
                        util.store_wallet_message(msg, msg_data)
                        event = util.decorate_message_for_feed(
                            msg, msg_data=msg_data)
                    break  #break out of inner loop

                #track assets
                if msg['category'] == 'issuances':
                    assets.parse_issuance(mongo_db, msg_data, cur_block_index,
                                          cur_block)

                #track balance changes for each address
                bal_change = None
                if msg['category'] in [
                        'credits',
                        'debits',
                ]:
                    actionName = 'credit' if msg[
                        'category'] == 'credits' else 'debit'
                    address = msg_data['address']
                    asset_info = mongo_db.tracked_assets.find_one(
                        {'asset': msg_data['asset']})
                    if asset_info is None:
                        logging.warn(
                            "Credit/debit of %s where asset ('%s') does not exist. Ignoring..."
                            % (msg_data['quantity'], msg_data['asset']))
                        continue
                    quantity = msg_data['quantity'] if msg[
                        'category'] == 'credits' else -msg_data['quantity']
                    quantity_normalized = util_bitcoin.normalize_quantity(
                        quantity, asset_info['divisible'])

                    #look up the previous balance to go off of
                    last_bal_change = mongo_db.balance_changes.find_one(
                        {
                            'address': address,
                            'asset': asset_info['asset']
                        },
                        sort=[("block_index", pymongo.DESCENDING),
                              ("_id", pymongo.DESCENDING)])

                    if     last_bal_change \
                       and last_bal_change['block_index'] == cur_block_index:
                        last_bal_change['quantity'] += quantity
                        last_bal_change[
                            'quantity_normalized'] += quantity_normalized
                        last_bal_change['new_balance'] += quantity
                        last_bal_change[
                            'new_balance_normalized'] += quantity_normalized
                        mongo_db.balance_changes.save(last_bal_change)
                        logging.info(
                            "Procesed %s bal change (UPDATED) from tx %s :: %s"
                            % (actionName, msg['message_index'],
                               last_bal_change))
                        bal_change = last_bal_change
                    else:  #new balance change record for this block
                        bal_change = {
                            'address':
                            address,
                            'asset':
                            asset_info['asset'],
                            'block_index':
                            cur_block_index,
                            'block_time':
                            cur_block['block_time_obj'],
                            'quantity':
                            quantity,
                            'quantity_normalized':
                            quantity_normalized,
                            'new_balance':
                            last_bal_change['new_balance'] +
                            quantity if last_bal_change else quantity,
                            'new_balance_normalized':
                            last_bal_change['new_balance_normalized'] +
                            quantity_normalized
                            if last_bal_change else quantity_normalized,
                        }
                        mongo_db.balance_changes.insert(bal_change)
                        logging.info(
                            "Procesed %s bal change from tx %s :: %s" %
                            (actionName, msg['message_index'], bal_change))

                #book trades
                if (msg['category'] == 'order_matches'
                        and ((msg['command'] == 'update'
                              and msg_data['status'] == 'completed') or
                             ('forward_asset' in msg_data
                              and msg_data['forward_asset'] != config.BTC
                              and msg_data['backward_asset'] != config.BTC))):

                    if msg['command'] == 'update' and msg_data[
                            'status'] == 'completed':
                        tx0_hash, tx1_hash = msg_data[
                            'order_match_id'][:64], msg_data['order_match_id'][
                                64:]
                        order_match = util.call_jsonrpc_api(
                            "get_order_matches", {
                                'filters': [{
                                    'field': 'tx0_hash',
                                    'op': '==',
                                    'value': tx0_hash
                                }, {
                                    'field': 'tx1_hash',
                                    'op': '==',
                                    'value': tx1_hash
                                }]
                            },
                            abort_on_error=False)['result'][0]
                    else:
                        assert msg_data['status'] == 'completed'
                        order_match = msg_data

                    forward_asset_info = mongo_db.tracked_assets.find_one(
                        {'asset': order_match['forward_asset']})
                    backward_asset_info = mongo_db.tracked_assets.find_one(
                        {'asset': order_match['backward_asset']})
                    assert forward_asset_info and backward_asset_info
                    base_asset, quote_asset = util.assets_to_asset_pair(
                        order_match['forward_asset'],
                        order_match['backward_asset'])

                    if    (order_match['forward_asset'] == config.BTC and order_match['forward_quantity'] <= config.ORDER_BTC_DUST_LIMIT_CUTOFF) \
                       or (order_match['backward_asset'] == config.BTC and order_match['backward_quantity'] <= config.ORDER_BTC_DUST_LIMIT_CUTOFF):
                        logging.debug(
                            "Order match %s ignored due to %s under dust limit."
                            % (order_match['tx0_hash'] +
                               order_match['tx1_hash'], config.BTC))
                        continue

                    #take divisible trade quantities to floating point
                    forward_quantity = util_bitcoin.normalize_quantity(
                        order_match['forward_quantity'],
                        forward_asset_info['divisible'])
                    backward_quantity = util_bitcoin.normalize_quantity(
                        order_match['backward_quantity'],
                        backward_asset_info['divisible'])

                    #compose trade
                    trade = {
                        'block_index':
                        cur_block_index,
                        'block_time':
                        cur_block['block_time_obj'],
                        'message_index':
                        msg['message_index'],  #secondary temporaral ordering off of when
                        'order_match_id':
                        order_match['tx0_hash'] + '_' +
                        order_match['tx1_hash'],
                        'order_match_tx0_index':
                        order_match['tx0_index'],
                        'order_match_tx1_index':
                        order_match['tx1_index'],
                        'order_match_tx0_address':
                        order_match['tx0_address'],
                        'order_match_tx1_address':
                        order_match['tx1_address'],
                        'base_asset':
                        base_asset,
                        'quote_asset':
                        quote_asset,
                        'base_quantity':
                        order_match['forward_quantity']
                        if order_match['forward_asset'] == base_asset else
                        order_match['backward_quantity'],
                        'quote_quantity':
                        order_match['backward_quantity']
                        if order_match['forward_asset'] == base_asset else
                        order_match['forward_quantity'],
                        'base_quantity_normalized':
                        forward_quantity if order_match['forward_asset']
                        == base_asset else backward_quantity,
                        'quote_quantity_normalized':
                        backward_quantity if order_match['forward_asset']
                        == base_asset else forward_quantity,
                    }
                    d = D(trade['quote_quantity_normalized']) / D(
                        trade['base_quantity_normalized'])
                    d = d.quantize(EIGHT_PLACES,
                                   rounding=decimal.ROUND_HALF_EVEN,
                                   context=decimal.Context(prec=20))
                    trade['unit_price'] = float(d)

                    d = D(trade['base_quantity_normalized']) / D(
                        trade['quote_quantity_normalized'])
                    d = d.quantize(EIGHT_PLACES,
                                   rounding=decimal.ROUND_HALF_EVEN,
                                   context=decimal.Context(prec=20))
                    trade['unit_price_inverse'] = float(d)

                    mongo_db.trades.insert(trade)
                    logging.info("Procesed Trade from tx %s :: %s" %
                                 (msg['message_index'], trade))

                #broadcast
                if msg['category'] == 'broadcasts':
                    betting.parse_broadcast(mongo_db, msg_data)

                if last_processed_block['block_index'] - my_latest_block[
                        'block_index'] < config.MAX_REORG_NUM_BLOCKS:
                    #send out the message to listening clients
                    util.store_wallet_message(msg, msg_data)
                #this is the last processed message index
                config.LAST_MESSAGE_INDEX = msg['message_index']

            new_block = {
                'block_index': cur_block_index,
                'block_time': cur_block['block_time_obj'],
                'block_hash': cur_block['block_hash'],
            }
            mongo_db.processed_blocks.insert(new_block)
            my_latest_block = new_block
            config.CURRENT_BLOCK_INDEX = cur_block_index
            if config.BLOCKCHAIN_SERVICE_LAST_BLOCK == 0 or config.BLOCKCHAIN_SERVICE_LAST_BLOCK - config.CURRENT_BLOCK_INDEX < config.MAX_REORG_NUM_BLOCKS:
                try:
                    block_height_response = blockchain.getinfo()
                except:
                    block_height_response = None
                config.BLOCKCHAIN_SERVICE_LAST_BLOCK = block_height_response[
                    'info']['blocks'] if block_height_response else 0
            logging.info(
                "Block: %i (message_index height=%s) (blockchain latest block=%s)"
                % (config.CURRENT_BLOCK_INDEX, config.LAST_MESSAGE_INDEX
                   if config.LAST_MESSAGE_INDEX != -1 else '???',
                   config.BLOCKCHAIN_SERVICE_LAST_BLOCK
                   if config.BLOCKCHAIN_SERVICE_LAST_BLOCK else '???'))

            clean_mempool_tx()

        elif my_latest_block['block_index'] > last_processed_block[
                'block_index']:
            logging.error(
                "Very odd: Ahead of energypartyd with block indexes! Pruning back %s blocks to be safe."
                % config.MAX_REORG_NUM_BLOCKS)
            my_latest_block = prune_my_stale_blocks(
                last_processed_block['block_index'] -
                config.MAX_REORG_NUM_BLOCKS)
        else:
            config.CAUGHT_UP = running_info['db_caught_up']

            if config.LAST_MESSAGE_INDEX == -1 or config.CURRENT_BLOCK_INDEX == 0:
                if config.LAST_MESSAGE_INDEX == -1:
                    config.LAST_MESSAGE_INDEX = running_info[
                        'last_message_index']
                if config.CURRENT_BLOCK_INDEX == 0:
                    config.CURRENT_BLOCK_INDEX = running_info['last_block'][
                        'block_index']
                logging.info(
                    "Detected blocks caught up on startup. Setting last message idx to %s, current block index to %s ..."
                    % (config.LAST_MESSAGE_INDEX, config.CURRENT_BLOCK_INDEX))

            if config.CAUGHT_UP and not config.CAUGHT_UP_STARTED_EVENTS:
                logging.debug(
                    "Starting event timer: compile_asset_pair_market_info")
                gevent.spawn(events.compile_asset_pair_market_info)

                logging.debug(
                    "Starting event timer: compile_asset_market_info")
                gevent.spawn(events.compile_asset_market_info)

                logging.debug(
                    "Starting event timer: compile_extended_asset_info")
                gevent.spawn(events.compile_extended_asset_info)

                logging.debug(
                    "Starting event timer: compile_extended_feed_info")
                gevent.spawn(events.compile_extended_feed_info)

                config.CAUGHT_UP_STARTED_EVENTS = True

            publish_mempool_tx()
            time.sleep(30)
Ejemplo n.º 12
0
 def context(self):
     return decimal.Context(prec=self.max_digits)
import decimal

print(decimal.Decimal(355) / decimal.Decimal(113))

with decimal.localcontext(decimal.Context(prec=50)):
    print(decimal.Decimal(355) / decimal.Decimal(113))

print(decimal.Decimal(355) / decimal.Decimal(113))
Ejemplo n.º 14
0
_CTX_OPTIONS = {
    'prec': _MAX_DIGITS,
    'rounding': decimal.ROUND_HALF_EVEN,
    'Emin': _EXPONENT_MIN,
    'Emax': _EXPONENT_MAX,
    'capitals': 1,
    'flags': [],
    'traps': [decimal.InvalidOperation, decimal.Overflow, decimal.Inexact]
}

if _PY3:
    _CTX_OPTIONS['clamp'] = 1
else:
    _CTX_OPTIONS['_clamp'] = 1

_DEC128_CTX = decimal.Context(**_CTX_OPTIONS.copy())


def create_decimal128_context():
    """Returns an instance of :class:`decimal.Context` appropriate
    for working with IEEE-754 128-bit decimal floating point values.
    """
    opts = _CTX_OPTIONS.copy()
    opts['traps'] = []
    return decimal.Context(**opts)


def _decimal_to_128(value):
    """Converts a decimal.Decimal to BID (high bits, low bits).

    :Parameters:
Ejemplo n.º 15
0
 def set_pf(o, logq):
     o['free_energy'] = logq / -beta
     o['pfunc'] = decimal.Context(prec=10).create_decimal(
         decimal.Decimal(logq).exp())
Ejemplo n.º 16
0
import decimal, numbers
"""
decimal: 定点和浮点运算
    |- 实现了精度更高的算法
    |- 想实现高精度的算法请不要使用int,float,请使用Decimal高精度类型
    |- 这是真牛逼(Decimal)
    
e = float('12.44444444444444444423234234232352352')
print(e)        # float是无法表示这么高的精度的(12.444444444444445)这么多位
"""

# 设置一个精度    设置四舍五入                 最大指数   最小只是
ctx = decimal.Context(prec=4,
                      rounding=decimal.ROUND_CEILING,
                      Emax=100,
                      Emin=-100,
                      capitals=1,
                      clamp=True)
a = decimal.Decimal('12.44444444444444444423234234232352352')
# print(a)
b = decimal.Decimal('33.143141434124342342342342342342323323')
print(a + b)
print(isinstance(b, numbers.Number))  # True

# ctx = decimal.getcontext()
# print(ctx.prec)     # 夹紧
# print(ctx.rounding)
# print(ctx.flags)    # 每次运算产生的标记
# print(ctx.traps)    # 设置的标记
# print(ctx.Emin)     # 最小指数
# print(ctx.Emax)     # 最大指数
Ejemplo n.º 17
0
import decimal

abi_decimal_context = decimal.Context(prec=999)

ZERO = decimal.Decimal(0)
TEN = decimal.Decimal(10)


def ceil32(x):
    return x if x % 32 == 0 else x + 32 - (x % 32)


def compute_unsigned_integer_bounds(num_bits):
    return (
        0,
        2**num_bits - 1,
    )


def compute_signed_integer_bounds(num_bits):
    return (
        -1 * 2**(num_bits - 1),
        2**(num_bits - 1) - 1,
    )


def compute_unsigned_fixed_bounds(num_bits, frac_places):
    int_upper = compute_unsigned_integer_bounds(num_bits)[1]

    with decimal.localcontext(abi_decimal_context):
        upper = decimal.Decimal(int_upper) * TEN**-frac_places
Ejemplo n.º 18
0
 class MockObject(object):
     field = txn.AmountField(decimal_context=decimal.Context(rounding=decimal.ROUND_DOWN))
Ejemplo n.º 19
0
To run the tests, simply run this file::

    python test_runner.py

"""

import decimal
import locale
import os
import sys
import unittest

# Set standard thread-wide locale and decimal rounding settings
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
decimal.setcontext(decimal.Context(rounding=decimal.ROUND_HALF_UP))

if __name__ == '__main__':
    test_dir = os.path.dirname(os.path.abspath(__file__))
    package_dir = os.path.normpath(
        os.path.join(test_dir, os.pardir, 'blingalytics'))
    sys.path = [test_dir, package_dir] + sys.path

    suite = unittest.TestLoader().loadTestsFromNames([
        'test_base',
        'test_helpers',
        'sources.test_base',
        'sources.test_database',
        'sources.test_derived',
        'sources.test_merge',
        'sources.test_static',
Ejemplo n.º 20
0
from datetime import datetime
import logging
import decimal
import base64
import json
import time

from counterblock.lib import cache, config, util

decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
D = decimal.Decimal
logger = logging.getLogger(__name__)

sogassets = ["FDCARD",
                    "SJCXCARD",
                    "GEMZCARD",
                    "XCPCARD",
                    "SWARMCD",
                    "ETHEREUMCARD",
                    "SATOSHICARD",
                    "CLEFCARD",
                    "GENESISCARD",
                    "SHUMAICARD",
                    "CNPCARD",
                    "SHAPESHIFTCD",
                    "RIPPLECARD",
                    "BLOCKSIZECD",
                    "ETHXCPCARD",
                    "BEARWHALECD",
                    "LTBCARD",
                    "ZAIFCARD",
Ejemplo n.º 21
0
    def test_urls_access(self):

        context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
        decimal.setcontext(context)

        shop = Shop.objects.all()[0]
        category = MarketCategory.objects.all()[0]
        HTTP_HOST = shop.default_dns

        now = datetime.datetime.now()
        tomorrow = now + datetime.timedelta(days=1)
        auction = AuctionSession(shop=shop,
                                 title="Auction Session Nr 0",
                                 description="-- no desc --",
                                 start=now,
                                 end=tomorrow)
        auction.save()

        lot = Lot(shop=shop,
                  title="Coin From Egypt 1905 (PCGS 60)",
                  description="rare coin",
                  category=category,
                  date_time=now,
                  weight="5",
                  session=auction,
                  starting_bid=decimal.Decimal("10.00"),
                  reserve=decimal.Decimal("0.00"))
        lot.save()

        item = Item(shop=shop,
                    title="Coin From Rusia 1917 (PCGS 60)",
                    description="rare coin",
                    category=category,
                    date_time=now,
                    weight="5",
                    qty="10",
                    price=decimal.Decimal("150"))
        item.save()

        user = shop.admin
        #        response = self.client.get(reverse("bidding_view_lot", args=[lot.id]), HTTP_HOST=HTTP_HOST)
        #        self.assertEqual(response.status_code, 200, "Failed when trying to view lot")
        #
        success = self.client.login(username=user.username, password="******")
        self.assertEqual(success, True, "Login failed")

        ############# CUSTOMERS ################
        response = self.client.get(reverse("home_admin"), HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach home_admin")

        response = self.client.get(reverse("customers"), HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach customers")

        response = self.client.get(reverse("customers_overview"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach customers_overview")

        response = self.client.get(reverse("customers_profiles"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach customers_profiles")

        response = self.client.get(reverse("customers_sold_items"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach customers_sold_items")

        response = self.client.get(reverse("customers_payments"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach customers_payments")

        response = self.client.get(reverse("customers_shipments"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach customers_shipments")

        response = self.client.get(reverse("customers_wish_lists"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach customers_wish_list")

        #        response = self.client.get(reverse("customers_send_notification"), HTTP_HOST=HTTP_HOST)
        #        self.assertEqual(response.status_code, 200, "Failed when trying to bid a valid amount")

        response = self.client.get(reverse("customers_mailing_list"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach customers_mailing_list")

        response = self.client.get(reverse("customers_export_mailinglist"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(
            response.status_code, 200,
            "Failed when trying to reach customers_export_mailinglist")

        ######### WEBSTORE ############
        response = self.client.get(reverse("web_store"), HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach web_store")

        response = self.client.get(reverse("web_store_overview"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach web_store_overview")

        response = self.client.get(reverse("web_store_marketing"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach web_store_marketing")

        response = self.client.get(reverse("web_store_shows"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach web_store_shows")

        #        response = self.client.get(reverse("web_store_theme"), HTTP_HOST=HTTP_HOST)
        #        self.assertEqual(response.status_code, 200, "Failed when trying to reach web_store_theme")

        response = self.client.get(reverse("web_store_pages"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach web_store_pages")

        response = self.client.get(reverse("web_store_blogs"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach web_store_blogs")

        response = self.client.get(reverse("web_store_navigation"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach web_store_navigation")

        #        response = self.client.get(reverse("web_store_show_go"), HTTP_HOST=HTTP_HOST)
        #        self.assertEqual(response.status_code, 200, "Failed when trying to bid a valid amount")
        #
        #        response = self.client.get(reverse("web_store_show_not_go"), HTTP_HOST=HTTP_HOST)
        #        self.assertEqual(response.status_code, 200, "Failed when trying to bid a valid amount")
        #
        #        response = self.client.get(reverse("web_store_theme"), HTTP_HOST=HTTP_HOST)
        #        self.assertEqual(response.status_code, 200, "Failed when trying to bid a valid amount")

        ######### INVENTORY ##########
        response = self.client.get(reverse("inventory"), HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach inventory")

        response = self.client.get(reverse("inventory_overview"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach inventory_overview")

        response = self.client.get(reverse("inventory_items"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach inventory_items")

        response = self.client.get(reverse("inventory_items_import"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach inventory_items_import")

        response = self.client.get(reverse("inventory_lots"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach inventory_lots")

        response = self.client.get(reverse("inventory_auctions"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach inventory_auctions")

        response = self.client.get(reverse("inventory_categorize"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach inventory_categorize")

        ######## ACCOUNT #########
        response = self.client.get(reverse("account"), HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach account")

        response = self.client.get(reverse("account_profile"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach account_profile")

        response = self.client.get(reverse("account_password"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach account_password")

        response = self.client.get(reverse("add_profile_photo"),
                                   HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 302,
                         "Failed when trying to reach add_profile_photo")

        response = self.client.get(reverse("preferences"), HTTP_HOST=HTTP_HOST)
        self.assertEqual(response.status_code, 200,
                         "Failed when trying to reach preferences")
Ejemplo n.º 22
0
NUMBER = "N"
BINARY = "B"
BOOLEAN = "BOOL"
MAP = "M"
LIST = "L"

PRIMITIVES = {"S", "N", "B"}
SETS = {"SS", "NS", "BS"}
DOCUMENTS = {"L", "M"}
ALL = {*PRIMITIVES, *SETS, *DOCUMENTS, BOOLEAN}

# Dynamo takes numbers as strings to reduce inter-language problems
DYNAMODB_CONTEXT = decimal.Context(
    Emin=-128, Emax=126, rounding=None, prec=38,
    traps=[
        decimal.Clamped, decimal.Overflow, decimal.Inexact,
        decimal.Rounded, decimal.Underflow
    ]
)

SUPPORTED_OPERATIONS = {
    "==": ALL,
    "!=": ALL,
    "<": PRIMITIVES,
    ">": PRIMITIVES,
    "<=": PRIMITIVES,
    ">=": PRIMITIVES,
    "begins_with": {STRING, BINARY},
    "between": PRIMITIVES,
    "contains": {*SETS, STRING, BINARY, LIST},
    "in": ALL
Ejemplo n.º 23
0
def test_day_frac_harmless(i, f):
    with decimal.localcontext(decimal.Context(prec=40)):
        a = Decimal(i) + Decimal(f)
        i_d, f_d = day_frac(i, f)
        a_d = Decimal(i_d) + Decimal(f_d)
        assert_almost_equal(a, a_d, atol=Decimal(tiny), rtol=Decimal(0))
Ejemplo n.º 24
0
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
import base64
import decimal

from magnetodb.storage import models
from magnetodb.storage.models import IndexDefinition
from magnetodb.common.exception import MagnetoError


#init decimal context to meet DynamoDB number type behaviour expectation
DECIMAL_CONTEXT = decimal.Context(
    prec=38, rounding=None,
    traps=[],
    flags=[],
    Emax=126,
    Emin=-128
)

TYPE_STRING = "S"
TYPE_NUMBER = "N"
TYPE_BLOB = "B"
TYPE_STRING_SET = "SS"
TYPE_NUMBER_SET = "NS"
TYPE_BLOB_SET = "BS"


class Props():
    TABLE_NAME = "TableName"
    ATTRIBUTE_DEFINITIONS = "AttributeDefinitions"
Ejemplo n.º 25
0
def requires_lossy_conversion(d):
    return d - decimal.Context(prec=sys.float_info.dig).create_decimal(d) != 0
Ejemplo n.º 26
0
# 保留小数点后 n 位数

num = 11.256823
print(round(num, 3))
print(round(num, 2))

# 拆分成元角分输出
money = 110.567
print(int(money), "元")
print(int(money * 10) % 10, "角")
print(int(round(money * 100) % 10), "分")
print(9 % 6)

# 引入decimal模块 计算实数的精度
# 使用 decimal下的 Context函数中的参数prec(用来显示最终的数值,长度包含整数位和小数位)
# 和rounding参数 赋值decimal.ROUND_HALF_UP算法 计算四舍五入
# create_decimal函数 参数传入字符串
import decimal
x = 123.4554
y = decimal.Decimal(x)
print(y)

# 在context 环境下场景一个decimal实例
a = decimal.Context(prec=8, rounding=decimal.ROUND_HALF_UP).create_decimal(
    str(x))  # prec=取值包含整数位
print(a)

# 四舍五入
a = round(x, 2)
print(a)
Ejemplo n.º 27
0
import dendropy
import os
import decimal
result = "[TYPE] NUCLEOTIDE 1\n"
path = "/home/qikaiy2/Downloads/reu2019-tutorials/qikaiy2_project_1/output_data/trees/GTRCAT"
path1 = "/home/qikaiy2/Downloads/reu2019-tutorials/qikaiy2_project_1/output_data/trees/R_GTRCAT"
files = os.listdir(path)
# The below codes come from this blog and the copyright belongs to the blogger:
# https://codeday.me/bug/20171224/112503.html------------
# create a new context for this task
ctx = decimal.Context()

# 20 digits should be enough for everyone :D
ctx.prec = 20


def float_to_str(f):
    """
    Convert the given float to a string,
    without resorting to scientific notation
    """
    d1 = ctx.create_decimal(repr(f))
    return format(d1, 'f')


#-----------------------------------------------------------------------------------------


def filter(strr):
    if ((strr[0:14] == "RAxML_bestTree")):
        return 1
Ejemplo n.º 28
0
def parse_trade_book(msg, msg_data):
    # book trades
    if (msg['category'] == 'order_matches' and
        ((msg['command'] == 'update' and msg_data['status'] == 'completed')
         or  # for a trade with BTC involved, but that is settled (completed)
         ('forward_asset' in msg_data
          and msg_data['forward_asset'] != config.BTC
          and msg_data['backward_asset'] != config.BTC))
        ):  # or for a trade without BTC on either end

        if msg['command'] == 'update' and msg_data['status'] == 'completed':
            # an order is being updated to a completed status (i.e. a BTCpay has completed)
            tx0_hash, tx1_hash = msg_data['order_match_id'][:64], msg_data[
                'order_match_id'][65:]
            # get the order_match this btcpay settles
            order_match = util.jsonrpc_api("get_order_matches", {
                'filters': [{
                    'field': 'tx0_hash',
                    'op': '==',
                    'value': tx0_hash
                }, {
                    'field': 'tx1_hash',
                    'op': '==',
                    'value': tx1_hash
                }]
            },
                                           abort_on_error=False)['result'][0]
        else:
            assert msg_data[
                'status'] == 'completed'  # should not enter a pending state for non BTC matches
            order_match = msg_data

        forward_asset_info = config.mongo_db.tracked_assets.find_one(
            {'asset': order_match['forward_asset']})
        backward_asset_info = config.mongo_db.tracked_assets.find_one(
            {'asset': order_match['backward_asset']})
        assert forward_asset_info and backward_asset_info
        base_asset, quote_asset = util.assets_to_asset_pair(
            order_match['forward_asset'], order_match['backward_asset'])

        # don't create trade records from order matches with BTC that are under the dust limit
        if ((order_match['forward_asset'] == config.BTC
             and order_match['forward_quantity'] <=
             config.ORDER_BTC_DUST_LIMIT_CUTOFF)
                or (order_match['backward_asset'] == config.BTC
                    and order_match['backward_quantity'] <=
                    config.ORDER_BTC_DUST_LIMIT_CUTOFF)):
            logger.debug("Order match %s ignored due to %s under dust limit." %
                         (order_match['tx0_hash'] + order_match['tx1_hash'],
                          config.BTC))
            return 'ABORT_THIS_MESSAGE_PROCESSING'

        # take divisible trade quantities to floating point
        forward_quantity = blockchain.normalize_quantity(
            order_match['forward_quantity'], forward_asset_info['divisible'])
        backward_quantity = blockchain.normalize_quantity(
            order_match['backward_quantity'], backward_asset_info['divisible'])

        # compose trade
        trade = {
            'block_index':
            config.state['cur_block']['block_index'],
            'block_time':
            config.state['cur_block']['block_time_obj'],
            'message_index':
            msg['message_index'],  # secondary temporaral ordering off of when
            'order_match_id':
            order_match['tx0_hash'] + '_' + order_match['tx1_hash'],
            'order_match_tx0_index':
            order_match['tx0_index'],
            'order_match_tx1_index':
            order_match['tx1_index'],
            'order_match_tx0_address':
            order_match['tx0_address'],
            'order_match_tx1_address':
            order_match['tx1_address'],
            'base_asset':
            base_asset,
            'quote_asset':
            quote_asset,
            'base_quantity':
            order_match['forward_quantity'] if order_match['forward_asset']
            == base_asset else order_match['backward_quantity'],
            'quote_quantity':
            order_match['backward_quantity'] if order_match['forward_asset']
            == base_asset else order_match['forward_quantity'],
            'base_quantity_normalized':
            forward_quantity if order_match['forward_asset'] == base_asset else
            backward_quantity,
            'quote_quantity_normalized':
            backward_quantity if order_match['forward_asset'] == base_asset
            else forward_quantity,
        }
        d = D(trade['quote_quantity_normalized']) / D(
            trade['base_quantity_normalized'])
        d = d.quantize(EIGHT_PLACES,
                       rounding=decimal.ROUND_HALF_EVEN,
                       context=decimal.Context(prec=30))
        trade['unit_price'] = float(d)

        d = D(trade['base_quantity_normalized']) / D(
            trade['quote_quantity_normalized'])
        d = d.quantize(EIGHT_PLACES,
                       rounding=decimal.ROUND_HALF_EVEN,
                       context=decimal.Context(prec=30))
        trade['unit_price_inverse'] = float(d)

        config.mongo_db.trades.insert(trade)
        logger.info("Procesed Trade from tx %s :: %s" %
                    (msg['message_index'], trade))
Ejemplo n.º 29
0
"""Calculates Pi to a certain degree of accuracy using the Nilakantha series.
By Ted Silbernagel
"""

import decimal

# Set maximum decimal places
decimal.setcontext(decimal.Context(prec=100))


def nilakantha(precision: int) -> decimal.Decimal:
    calculated_pi = decimal.Decimal(3.0)
    last_num = decimal.Decimal(2.0)

    for i in range(1, precision + 1):
        if not i % 100000:
            print(f'\rCalculating: ({i}/{precision})', end='')

        num_to_change = (decimal.Decimal(4.0) /
                         (last_num * (last_num + decimal.Decimal(1.0)) *
                          (last_num + decimal.Decimal(2.0))))

        if i % 2:
            calculated_pi += num_to_change
        else:
            calculated_pi -= num_to_change

        last_num += decimal.Decimal(2.0)

    print('\n')
Ejemplo n.º 30
0
 def __init__(self):
     self.ulpdiff = 0
     self.powmod_zeros = 0
     self.maxctx = P.Context(Emax=10**18, Emin=-10**18)