本文整理匯總了Python中decimal.InvalidOperation方法的典型用法代碼示例。如果您正苦於以下問題:Python decimal.InvalidOperation方法的具體用法?Python decimal.InvalidOperation怎麽用?Python decimal.InvalidOperation使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類decimal
的用法示例。
在下文中一共展示了decimal.InvalidOperation方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_arith_series_with_array
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def test_arith_series_with_array(self, data, all_arithmetic_operators):
op_name = all_arithmetic_operators
s = pd.Series(data)
context = decimal.getcontext()
divbyzerotrap = context.traps[decimal.DivisionByZero]
invalidoptrap = context.traps[decimal.InvalidOperation]
context.traps[decimal.DivisionByZero] = 0
context.traps[decimal.InvalidOperation] = 0
# Decimal supports ops with int, but not float
other = pd.Series([int(d * 100) for d in data])
self.check_opname(s, op_name, other)
if "mod" not in op_name:
self.check_opname(s, op_name, s * 2)
self.check_opname(s, op_name, 0)
self.check_opname(s, op_name, 5)
context.traps[decimal.DivisionByZero] = divbyzerotrap
context.traps[decimal.InvalidOperation] = invalidoptrap
示例2: currency
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return ""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency or CURRENCY,
'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
}
return format_currency(value, **kwargs)
示例3: currency_formatter
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def currency_formatter(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return ""
# Using Babel's currency formatting
# http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency
currency = currency or settings.ACCOUNTING_DEFAULT_CURRENCY
kwargs = {
'currency': currency,
'format': getattr(settings, 'CURRENCY_FORMAT', None),
'locale': to_locale(get_language()),
}
return format_currency(value, **kwargs)
示例4: add_local_summary_statistics
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def add_local_summary_statistics(run_set_result, run_set_stats):
"""
Fill in the "local" values of ColumnStatistics instances in result of
get_stats_of_run_set
"""
for column, column_stats in zip(run_set_result.columns, run_set_stats):
if (
column.is_numeric()
and column.title in run_set_result.summary
and run_set_result.summary[column.title] != ""
):
try:
column_stats.local = StatValue(
util.to_decimal(run_set_result.summary[column.title])
)
except InvalidOperation:
pass
示例5: _percent_delta
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def _percent_delta(self, a, b):
"""Calculate a percent delta.
Args:
a (int or float or Decimal) the current value
b (int or float or Decimal) the previous value
Returns:
(Decimal) (a - b) / b * 100
Returns Decimal(0) if b is zero.
"""
try:
return Decimal((a - b) / b * 100)
except (DivisionByZero, ZeroDivisionError, InvalidOperation):
return None
示例6: _convert_value
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def _convert_value(self, value, column_type):
"""Convert a single value to the specified column type.
Args:
value (var): A value of any type
column_type (type) A Python type
Returns:
(var): The variable converted to type or None if conversion fails.
"""
if column_type == Decimal:
try:
value = Decimal(value).quantize(Decimal(self.decimal_precision))
except InvalidOperation:
value = None
else:
try:
value = column_type(value)
except ValueError as err:
LOG.warning(err)
value = None
return value
示例7: _focusout_validate
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def _focusout_validate(self, **kwargs):
valid = True
value = self.get()
min_val = self.cget('from')
max_val = self.cget('to')
try:
value = Decimal(value)
except InvalidOperation:
self.error.set('Invalid number string: {}'.format(value))
return False
if value < min_val:
self.error.set('Value is too low (min {})'.format(min_val))
valid = False
if value > max_val:
self.error.set('Value is too high (max {})'.format(max_val))
return valid
##################
# Module Classes #
##################
示例8: safe_div
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def safe_div(x, y, eps=(dec_eps, 1e-8)):
try:
out = dec_con.divide(x, y)
except DivisionByZero:
out = dec_con.divide(x, y + eps[0])
except InvalidOperation:
out = dec_con.divide(x, y + eps[0])
except TypeError:
try:
out = x / y
except ZeroDivisionError:
out = x / (y + eps[1])
except TypeError:
out = float(x) / (float(y) + eps[1])
return out
示例9: array_normalize
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def array_normalize(x, float=True):
out = convert_to.decimal(x)
try:
out /= out.sum()
except DivisionByZero:
out /= (out.sum() + dec_eps)
except InvalidOperation:
out /= (out.sum() + dec_eps)
out[-1] += dec_con.create_decimal('1.00000000') - out.sum()
if float:
return np.float64(out)
else:
return out
示例10: parse_value
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def parse_value(lexer, symbol=None, pos=0):
try:
if symbol is None:
pos, symbol = next(lexer)
if symbol == 'null':
yield ('null', None)
elif symbol == 'true':
yield ('boolean', True)
elif symbol == 'false':
yield ('boolean', False)
elif symbol == '[':
for event in parse_array(lexer):
yield event
elif symbol == '{':
for event in parse_object(lexer):
yield event
elif symbol[0] == '"':
yield ('string', unescape(symbol[1:-1]))
else:
try:
yield ('number', common.number(symbol))
except decimal.InvalidOperation:
raise UnexpectedSymbol(symbol, pos)
except StopIteration:
raise common.IncompleteJSONError('Incomplete JSON data')
示例11: _type_convert
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def _type_convert(self, value):
"""
Converts the value returned by the XMl parse into the equivalent
Python type
"""
if value is None:
return value
try:
return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
except ValueError:
pass
try:
return int(value)
except ValueError:
pass
try:
return decimal.Decimal(value)
except decimal.InvalidOperation:
pass
return value
示例12: stocktake
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def stocktake(self, count, user, notes=''):
""" Perform item stocktake.
When the quantity of an item is counted,
record the date of stocktake
"""
try:
count = Decimal(count)
except InvalidOperation:
return False
if count < 0 or self.infinite:
return False
self.stocktake_date = datetime.now().date()
self.stocktake_user = user
if self.updateQuantity(count):
self.addTransactionNote('Stocktake - counted {n} items'.format(n=count),
user,
notes=notes,
system=True)
return True
示例13: take_stock
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def take_stock(self, quantity, user, notes=''):
""" Remove items from stock
"""
# Cannot remove items from a serialized part
if self.serialized:
return False
try:
quantity = Decimal(quantity)
except InvalidOperation:
return False
if quantity <= 0 or self.infinite:
return False
if self.updateQuantity(self.quantity - quantity):
self.addTransactionNote('Removed {n} items from stock'.format(n=quantity),
user,
notes=notes,
system=True)
return True
示例14: strip_converter
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def strip_converter(text):
"""http://stackoverflow.com/questions/13385860"""
try:
text = text.strip()
if not text:
return ""
val = clean_value(text, max_dgts=6)
return str(Decimal(val))
except InvalidOperation:
return text
示例15: parts
# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import InvalidOperation [as 別名]
def parts(request, pk, order_id, queue_id):
"""
Lists available parts for this device/order
taking into account the order's queues GSX Sold-To
and the Location's corresponding GSX account
"""
from decimal import InvalidOperation
device = get_object_or_404(Device, pk=pk)
order = device.order_set.get(pk=order_id)
try:
# remember the right GSX account
act = GsxAccount.default(request.user, order.queue)
request.session['gsx_account'] = act.pk
products = device.get_parts()
except gsxws.GsxError as message:
return render(request, "search/results/gsx_error.html", locals())
except AttributeError:
message = _('Invalid serial number for parts lookup')
return render(request, "search/results/gsx_error.html", locals())
except InvalidOperation:
message = _('Error calculating prices. Please check your system settings.')
return render(request, "search/results/gsx_error.html", locals())
return render(request, "devices/parts.html", locals())