예제 #1
0
def _format_number(n: Number) -> str:
    if n == 0:
        return "0"
    power = int(numpy.log10(abs(n)))
    if power >= 6:
        n = n / 1000000
        if n >= 10:
            n = str(int(n))
        else:
            n = "%.1f" % n
            if n.endswith("0"):
                n = n[:-2]
        suffix = "M"
    elif power >= 3:
        n = n / 1000
        if n >= 10:
            n = str(int(n))
        else:
            n = "%.1f" % n
            if n.endswith("0"):
                n = n[:-2]
        suffix = "K"
    else:
        n = str(n)
        suffix = ""
    return n + suffix
예제 #2
0
    def visit_ForNode(self, node, context):
        res = RTResult()

        start_value = res.register(self.visit(node.start_value, context))
        if res.error: return res

        end_value = res.register(self.visit(node.end_value, context))
        if res.error: return res

        if node.step_value:  
            step_value = res.register(self.visit(node.step_value, context))
            if res.error: return res
        else:
            step_value = Number(1)

        i = start_value.value

        if step_value.value >= 0:
            condition = lambda: i < end_value.value
        else:
            condition = lambda: i > end_value.value

        while condition():
            context.symbol_table.set(node.var_name.value, Number(i))
            i += step_value.value

            res.register(self.visit(node.body, context))
            if res.error: return res
        
        return res.success(None)
예제 #3
0
파일: proxy.py 프로젝트: aurora1625/nboost
 def update_averages(self, **stats: Number):
     for key, value in stats.items():
         self.averages.setdefault(key, {'count': 0, 'sum': 0})
         item = self.averages[key]
         item['count'] += 1
         item['sum'] += value
         self.status['average_' + key] = item['sum'] / item['count']
예제 #4
0
    def encode_numeric(value: Number) -> JsonType:
        """ Encoding for numeric types.

        This will do nothing to naturally serializable types (bool, int, float)
          but will perform custom encoding for non-supported types (complex).
        This will convert Decimal values to their tuple encodings.
            See: https://docs.python.org/3.9/library/decimal.html#decimal.Decimal.as_tuple
        The custom encoding follows the template:
            {
              NUMERIC_KEY: <type-as-a-string>,
              NUMERIC_VALUE_KEY: <value>
            }
        The values for the NUMERIC_KEY and NUMERIC_VALUE_KEY constants are attributes
          to the `snappiershot.serializers.constants.CustomEncodedNumericTypes` class.

        Raises:
            NotImplementedError - If encoding is not implement for the given numeric type.
        """
        if isinstance(value, (bool, int, float)):
            # These types are by default supported by the JSONEncoder base class.
            return value
        if isinstance(value, complex):
            encoded_value: List[float] = [value.real, value.imag]
            return CustomEncodedNumericTypes.complex.json_encoding(
                encoded_value)
        if isinstance(value, Decimal):
            encode_value: Dict[str, Any] = value.as_tuple()._asdict()
            return CustomEncodedNumericTypes.decimal.json_encoding(
                encode_value)
        raise NotImplementedError(
            f"No encoding implemented for the following numeric type: {value} ({type(value)})"
        )
예제 #5
0
 def test_is_scalar_builtin_scalars(self):
     assert is_scalar(None)
     assert is_scalar(True)
     assert is_scalar(False)
     assert is_scalar(Number())
     assert is_scalar(Fraction())
     assert is_scalar(0.0)
     assert is_scalar(np.nan)
     assert is_scalar("foobar")
     assert is_scalar(b"foobar")
     assert is_scalar(datetime(2014, 1, 1))
     assert is_scalar(date(2014, 1, 1))
     assert is_scalar(time(12, 0))
     assert is_scalar(timedelta(hours=1))
     assert is_scalar(pd.NaT)
예제 #6
0
    def request_account_tx(self, options):
        data = []
        request = Request(self, 'account_tx', None)
        if not isinstance(options, object):
            request.message['type'] = Exception('invalid options type')
            return request

        if not Wallet.is_valid_address(options['account']):
            request.message['account'] = Exception(
                'account parameter is invalid')
            return request

        request.message['account'] = options['account']

        if options.__contains__('ledger_min') and Number(
                options['ledger_min']):
            request.message['ledger_index_min'] = Number(options['ledger_min'])
        else:
            request.message['ledger_index_min'] = 0
        if options.__contains__('ledger_max') and Number(
                options['ledger_max']):
            request.message['ledger_index_max'] = Number(options['ledger_max'])
        else:
            request.message['ledger_index_max'] = -1

        if options.__contains__('limit') and isinstance(options['limit'], int):
            if options['limit'] > 0:  # limit must be positive
                request.message['limit'] = options['limit']

        if options.__contains__('offset') and Number(options['offset']):
            request.message['offset'] = Number(options['offset'])

        if options.__contains__('marker') and isinstance(
                options['marker'], 'object') and Number(
                    options.marker['ledger']) != None and Number(
                        options['marker']['seq']) != None:
            request.message['marker'] = options['marker']

        if options.__contains__('forward') and isinstance(
                options['forward'], 'boolean'):
            request.message['forward'] = options['forward']

        return request
예제 #7
0
    def visit_UnaryOpNode(self, node, context):
        res = RTResult()

        number = res.register(self.visit(node.node, context))

        if res.error: return res

        error = None 

        if node.op_tok.type == TT_MINUS:
            number, error = number.mult_by(Number(-1))
        elif node.op_tok.type.matches(TT_KEYWORD, 'NOT'):
            number, error = number.notted()

        if error: 
            return res.failure(error)
        else: 
            return res.success(number.set_pos(node.pos_start, node.pos_end))
예제 #8
0
 def test_isNumber(self):
     self.assertEqual('123', Number(), '123')
예제 #9
0
파일: search.py 프로젝트: nulpunkt/euler
from numbers import Number

i = 286
number = Number()
while True:
	n = number.triangle(i)
	if (number.isPantagonal(n) and number.isHexagonal(n)):
		print n
		break

	i += 1
예제 #10
0
##################################
# IMPORTS
##################################

from numbers import Number
from symbols import SymbolTable
from lexer import Lexer
from parse import Parser
from interpreter import Interpreter
from context import Context

##################################
# RUN
##################################
global_symbol_table = SymbolTable()
global_symbol_table.set('NULL', Number(0))
global_symbol_table.set('TRUE', Number(1))
global_symbol_table.set('FALSE', Number(0))


def run(fn, text):
    lexer = Lexer(fn, text)
    tokens, error = lexer.make_tokens()
    if error: return None, error

    #Generate Abstract Syntax Tree
    parser = Parser(tokens)
    ast = parser.parse()
    if ast.error: return None, ast.error

    #Run the AST through the Interpreter
예제 #11
0
 def visit_NumberNode(self, node, context):
     return RTResult().success(
         Number(node.tok.value).set_context(context).set_pos(node.pos_start, node.pos_end))
예제 #12
0
파일: mod.py 프로젝트: hfwittmann/mod
    def __rfloordiv__(self, other):
        converted = self._convert(other)
        if converted is None:
            return other // self._value

        return converted * self.inverse

    def __pow__(self, other):
        converted = self._convert(other)
        if converted is None:
            return self._value**other

        if isinstance(other, Mod):
            result = pow(self._value, other._value, self._modulus)
        else:
            result = pow(self._value, other, self._modulus)

        return Mod(result, self._modulus)

    def __rpow__(self, other):
        converted = self._convert(other)
        if converted is None:
            return pow(other, self._value, self._modulus)

        result = pow(converted._value, self._value, self._modulus)
        return Mod(result, self._modulus)


Number.register(Mod)
예제 #13
0
 def update(self, loss: Number) -> 'EearlyStopping':
     if hasattr(loss, 'numpy'):
         loss = loss.numpy()
     self._losses.append(loss)
     return self
예제 #14
0
from numbers import Number

n = input("Type in the number: ")
number = Number()
data = number.run(n)

if data:
    for k, v in data.items():
        if v:
            print("{0}: {1}".format(k, v))
예제 #15
0
 def adjust(self, **adjustments: Number) -> MorphologySelection:
     for name, adjust in adjustments.items():
         for elem in self.selected:
             value = getattr(elem, name) + adjust
             setattr(elem, name, value)
     return self