def sell(self, pair): for rate in Infos().ticker(pair): rate = rate['buy'] if 'btc' in pair.split('_'): amount = amount_to_trade * Infos().funds(pair)['btc'] else: amount = amount_to_trade * Infos().funds(pair).values()[0] * rate thread = MyThread("%g:%s:%g" % (d(amount), pair, d(rate))) try: debug('Selling %g of %s @ %g...' % (amount, pair, rate)) return self.tapi.call('Trade', pair=pair, type='sell', amount=amount, rate=rate), thread.start() except: try: debug('Selling %g of %s @ %g...' % (amount_to_trade, pair, rate)) return self.tapi.call('Trade', pair=pair, type='sell', amount=minimum_to_trade, rate=rate), thread.start() except btcelib.APIError: debug('Not enough funds. Passing...') pass
def stockAction(request, action): response = {} p = request.POST['price'] qty = request.POST['qty'] userProfile = UserProfile.objects.get(user = request.user) avail_b = userProfile.available_balance if not qty: response['msg']='Please Enter a number to %s stocks' %(action) response['status'] = 0 return HttpResponse(json.dumps(response)) price = int(qty) * d(p) if action == 'buy': if d(price) > (avail_b): msg = 'You cureent balance is low so you cannot buy '+qty+' number of stocks' response['msg'] = msg response['status'] = 0 return HttpResponse(json.dumps(response)) new_avail_balance = userProfile.available_balance - d(price) userProfile.available_balance = new_avail_balance userProfile.save() response['price'] = float(new_avail_balance) response['status'] = 1 return HttpResponse(json.dumps(response)) if action == 'sell': new_avail_balance = userProfile.available_balance + d(price) userProfile.available_balance = new_avail_balance userProfile.save() response['price'] = float(new_avail_balance) response['status'] = 1 return HttpResponse(json.dumps(response))
def test_none_emission_matrix(self): log_pi, log_a, log_b = self._testing_parameters_generator(2, 3) log_alpha = np.array([[d(1)]*3]*2, dtype=object) log_beta = np.array([[d(1)]*3]*2, dtype=object) log_b = None with self.assertRaises(TypeError): self.model._compute_logeta(log_a, log_b, log_alpha, log_beta)
def test_mismatch_size_transition_and_emission_matrix(self): log_a = np.array([ [d(1).ln(), d(2).ln()], [d(3).ln(), d(4).ln()]]) log_b = np.array([[d(1).ln()]]) with self.assertRaises(ValueError): self.model._compute_logbeta(log_a, log_b)
def test_empty_transtition_matrix(self): log_pi, log_a, log_b = self._testing_parameters_generator(2, 3) log_alpha = np.array([[d(1)]*3]*2, dtype=object) log_beta = np.array([[d(1)]*3]*2, dtype=object) log_a = np.empty((0, 0)) with self.assertRaises(ValueError): self.model._compute_logeta(log_a, log_b, log_alpha, log_beta)
def test_one_time(self): log_pi, log_a, log_b = self._testing_parameters_generator(3, 1) log_alpha = np.array([[d(1)]*1]*3, dtype=object) log_beta = np.array([[d(1)]*1]*3, dtype=object) result = self.model._compute_logeta(log_a, log_b, log_alpha, log_beta) expected_result = self._expected_logeta(3, 1) np.testing.assert_array_equal(result, expected_result)
def test_get_data(hdf_project): h = hdf_project group_name = "Project Data" assert ( h.get_sdcube(group_name).get_data({"first": d("1"), "test": d("3.0"), "another": d("1"), "second": "c"})[0] == 32 )
def test_mismatch_size_transition_and_emission_matrix(self): log_a = np.array([[d(1).ln()]*3]*3) log_b = np.array([[d(1).ln()]*4]) log_alpha = np.array([[d(1)]*3]*2, dtype=object) log_beta = np.array([[d(1)]*3]*2, dtype=object) with self.assertRaises(ValueError): self.model._compute_logeta(log_a, log_b, log_alpha, log_beta)
def test_mismatch_size_log_alpha_and_log_beta(self): log_a = np.array([[d(1).ln()]*2]*2) log_b = np.array([[d(1).ln()]*3]*2) log_alpha = np.array([[d(1)]*3]*3, dtype=object) log_beta = np.array([[d(1)]*3]*4, dtype=object) with self.assertRaises(ValueError): self.model._compute_logeta(log_a, log_b, log_alpha, log_beta)
def calc_change(s_open: str, s_close: str) -> tuple: ''' calculates difference of s_close minus s_open and percentage change (s_close - s_open ) / s_open if s_open is zero percentage change is zero invalid input results in out ('0', '0') Arguments: s_open, s_close: string Returns: tuple (s_change: str, s_change_pct: str) ''' try: s_open = d(s_open) s_close = d(s_close) s_change = s_close - s_open if s_open == 0: s_change_pct = '0' else: s_change_pct = s_change / s_open * d('100') s_change = str(s_change) s_change_pct = str(s_change_pct) except decimal.InvalidOperation: s_change = '0' s_change_pct = '0' return s_change, s_change_pct
def main(): # basic numeric data types in python print(type(6)) print(type(6.5)) print(type(6 + 7j)) num = 6 + 7j print(isinstance(num, complex)) #operations using binary, octal, hexadecimal print(0b100010010) print(0b100010010 + 0o15) print(0b100010010 + 0xFB) #python casting print(int(63.7)) print(float(63)) print(float('63.26')) #using Decimal module to get more precise values print(0.1) print(d(0.1)) print(d(202.5624) * d(1235.984316)) #using fractions module print(f('1.1') + f(12, 10)) print(f(-3, 5) > 0) #using math module print(math.pi) print(math.cos(math.pi)) print(math.factorial(26)) print(math.cos(math.pi) + math.sin(math.pi))
def factorial(n): res = d('1') if n == 1 or n == 0: return 1 for i in range(1, n + 1): res *= d(str(i)) return res
def calc_confi(val, list): n = count(list) mean = calc_mean(list) tmp = [ d((d(x) - mean)**2) for x in list ] std_abw = d(d(1/n)*sum(tmp)).sqrt() # maximum like-lihood std_err = d(std_abw / n.sqrt()) return val * std_err
def test_invalid_size_emission_matrix(self): log_pi, log_a, log_b = self._testing_parameters_generator(2, 3) log_alpha = np.array([[d(1)]*3]*2, dtype=object) log_beta = np.array([[d(1)]*3]*2, dtype=object) log_b = np.ones((1, 1, 1)) with self.assertRaises(ValueError): self.model._compute_logeta(log_a, log_b, log_alpha, log_beta)
def test_set_too_big_data(filled_sdcube): data = arange(3*3*4).reshape((3,3,4)) try: filled_sdcube.set_data({'x':d('1'), 'y':'a', 'z':d('1.0')}, data) assert False except ValueError: assert True
def test_one_time(self): log_alpha = np.array([[d(1)]*1]*3, dtype=object) log_beta = np.array([[d(1)]*1]*3, dtype=object) result = self.model._compute_loggamma(log_alpha, log_beta) expected_result = self._expected_gamma(3, 1) np.testing.assert_almost_equal( result, expected_result, decimal=self.num_precision-1)
def test_set_data_to_nonexisting_dataset(simple_sdcube): data = arange(3*3*3).reshape((3,3,3)) try: simple_sdcube.set_data({'x':d('1'), 'y':'a', 'z':d('1.0')}, data) assert False except ValueError: assert True
def test_invalid_size_initial_states(self): initial_states = np.array([ [d(1), d(2)], [d(3), d(4)]]) with self.assertRaises(ValueError): self.model.initial_states = initial_states
def test_get_data_complex(filled_complicated_sdcube): cube = filled_complicated_sdcube # And this is what it looks like # Note: the datasets are seperated # y # a b c d e f # #----------------------# # |1| 0 1 2 15 16 # # |2| 3 4 5 17 18 # #x|3| 7 8 9 11 12 13# # |5| 19 20 # ######################## expected_data = ( [array([[0], [3]]), array([[ 7]])], [array([[ 1], [ 4]]), array([[ 8]])], [array([[2],[5]]), array([[9]])], [array([[11]]), array([[15], [17], [19]])], [array([[12]]), array([[16], [18], [20]])], [array([[13]])]) for i, char in enumerate(['a', 'b', 'c', 'd', 'e', 'f']): for j, data in enumerate(cube.get_data(items={'y':char})): assert all(x == y for x, y in zip(expected_data[i][j], data)) expected_data = ( [array([[0, 1, 2]]), array([[ 15, 16]])], [array([[ 3, 4, 5]]), array([[ 17, 18]])], [array([[7, 8, 9]]), array([[11, 12, 13]])], [array([[19, 20]])]) for i, char in enumerate([d('1'), d('2'), d('3'), d('5')]): for j, data in enumerate(cube.get_data(items={'x':char})): assert all([x == y for x, y in zip(expected_data[i][j], data)][0])
def test_one_state(self): log_gamma = np.array([ [d(1).ln(), d(2).ln(), d(3).ln()]]) result = self.model._recompute_log_initial_states(log_gamma) expected_result = np.array( [d(1).ln()]) np.testing.assert_array_equal(result, expected_result)
def pytest_funcarg__simple_hdf_project(request): ''' Set up a project, create one dataset with two dimensions (4x4 (filled with the numbers from 0 to 4x4 = 15)) ''' if os.path.exists('collapse.hdf5'): os.remove('collapse.hdf5') hdf = Hdf5('collapse') # Create dset 1 two_d_name_1 = '2D_1' name = hdf.add_sdcube(['x', 'y'], name=two_d_name_1) sdcube1 = hdf.get_sdcube(name) sdcube1.create_dataset({'x':[d('1'), d('2'), d('3'), d('4')], 'y':['a', 'b', 'c', 'd']}) sdcube1.set_data({'x':d('1'), 'y':'a'}, arange(4*4).reshape((4, 4))) # And this is what it looks like # y # a b c d # #-----------------# # |1 0 1 2 3 # # |2 4 5 6 7 # #x|3 8 9 10 11 # # |4 12 13 14 15 # ################### return hdf
def test_very_small_positive_x_and_y(self): x, y = d('1e-20'), d('1e-20') result = self.model._elnproduct(x, y) expected_result = x + y self.assertEqual(result, expected_result) expected_result = x + y self.assertEqual(result, expected_result)
def test_numerical_stability_if_increased_number_of_states(self): for i in xrange(0, 5): log_alpha = np.array([[d(1)]*2]*(8**i), dtype=object) log_beta = np.array([[d(1)]*2]*(8**i), dtype=object) result = self.model._compute_loggamma(log_alpha, log_beta) expected_result = self._expected_gamma(8**i, 2) np.testing.assert_almost_equal( result, expected_result, decimal=self.num_precision-((i//2)+1))
def test_mismatch_size_transition_and_emission_matrix(self): log_pi, log_a, log_b = self._testing_parameters_generator(5, 3) log_a = np.array([ [d(1).ln(), d(2).ln()], [d(3).ln(), d(4).ln()]]) log_b = np.array([[d(1).ln()]]) with self.assertRaises(ValueError): self.model._compute_logdelta(log_pi, log_a, log_b)
def _testing_parameters_generator( cls, N, T, log_pi_val=d(1).ln(), log_a_val=d(1).ln(), log_b_val=d(1).ln()): initial_states = np.array([log_pi_val]*N, dtype=object) transition_matrix = np.array([[log_a_val]*N]*N, dtype=object) emission_matrix = np.array([[log_b_val]*T]*N, dtype=object) return initial_states, transition_matrix, emission_matrix
def midSolve(a, K, b): n, m = len(a), len(b) if n >= m or n <= 1 or m <= 1: return b diff = m - n K = min(K, diff) strDif = str(d(b[1:]) - d(a[1:])) return a[0] + strDif[:K] + a[1:]
def test_very_huge_negative_x_and_y(self): x, y = d('-1e20'), d('-1e20') result = self.model._elnproduct(x, y) expected_result = x + y self.assertEqual(result, expected_result) expected_result = x + y self.assertEqual(result, expected_result)
def test_mismatch_size_observed_states_and_symbols(self): log_gamma = np.array([[d(1).ln()]*3]*2) observed_states = np.array([d(1)]*4) symbols = np.array([d(1)]*5) with self.assertRaises(ValueError): self.model._recompute_log_emissions(log_gamma, observed_states, symbols)
def test_very_huge_negative_x_and_y(self): x, y = d('-1e20'), d('-1e20') result = self.model._elnsum(x, y) expected_result = x + (d(1) + (y - x).exp()).ln() self.assertEqual(result, expected_result) expected_result = y + (d(1) + (x - y).exp()).ln() self.assertEqual(result, expected_result)
def test_set_wrong_dimension_data(hdf_project): group_name = "Project Data" indices = {"first": d("1"), "second": "a", "test": d("1.0"), "another": d("1")} try: hdf_project.get_sdcube(group_name).set_data(indices, arange(1)) assert False except ValueError: assert True
def test_very_small_positive_x_and_y(self): x, y = d('1e-20'), d('1e-20') result = self.model._elnsum(x, y) expected_result = x + (d(1) + (y - x).exp()).ln() self.assertEqual(result, expected_result) expected_result = y + (d(1) + (x - y).exp()).ln() self.assertEqual(result, expected_result)
def output(title, data_list): tmp_tks_ns = d(0) c = 0 for row in data_list: count, min_s, min_ns, min_tks, max_s, max_ns, max_tks, av_s, av_ns, av_tks = row tmp_tks_ns += d(av_tks)/ctks*1000000000 c += 1 value = (tmp_tks_ns / d(c)) - old_overheads_measuring_error_ns print title, d_round(value), 'ns'
def test_numerical_stability_if_increased_number_of_states(self): for i in xrange(0, 4): log_pi, log_a, log_b = self._testing_parameters_generator(8**i, 2) log_alpha = np.array([[d(1)]*2]*(8**i), dtype=object) log_beta = np.array([[d(1)]*2]*(8**i), dtype=object) result = self.model._compute_logeta(log_a, log_b, log_alpha, log_beta) expected_result = self._expected_logeta(8**i, 2) np.testing.assert_almost_equal( result, expected_result, decimal=self.num_precision-(i+1))
def slotToNum(slots): total = len(slots) value = d(0) for slot in slots: value += (slot * fact(total)) // 1 total -= d(1) return value
def test_one_state(self): transition_matrix = np.array([ [d(1)]]) log_transition_matrix = np.array([ [d(1).ln()]]) self.model.transition_matrix = transition_matrix result = self.model._log_transition_matrix expected_result = log_transition_matrix np.testing.assert_array_equal(result, expected_result)
def test_one_state(self): initial_states = np.array( [d(1)]) log_initial_states = np.array( [d(1).ln()]) self.model.initial_states = initial_states result = self.model._log_initial_states expected_result = log_initial_states np.testing.assert_array_equal(result, expected_result)
def mm(x): x = x.replace("<starth>", realtime(d(getnum(sv.get())))) x = x.replace("<start>", uTime(d(getnum(sv.get())))) x = x.replace("<starts>", str(getnum(sv.get()))) x = x.replace("<endh>", realtime(d(getnum(ev.get())))) x = x.replace("<end>", uTime(d(getnum(ev.get())))) x = x.replace("<ends>", str(getnum(sv.get()))) x = x.replace("<result>", tv.get()) x = x.replace("<framerate>", fv.get()) x = x.replace("<modifier>", mv.get()) return x
def euler104(): from decimal import Decimal as d fib=[0,1] flag=True phi=(1+5**d(0.5))/2 while flag: fib.append((fib[-1]+fib[-2])%10000000000) if sorted(str(fib[-1])[-9:])==list("123456789"): if sorted(str(int(phi**(len(fib)-1)/(5**d(0.5))))[::-1][-9:])==list("123456789"): print len(fib)-1; flag=False if len(fib)%10000==0: print len(fib) print len(fib)-1
def numtime(x): for each in x: if each not in [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'h', 'm', 's', ' ', '-', '.' ]: raise neg = d(x[0] == '-') * d(-2) + d(1) if neg < 0: x = x[1:] x = ' ' + x.replace('ms', 'n') sp = findOccurrences(x, ' ') hri = x.find('h') for each in sp: if each < hri - 1: hrs = each try: h = d(x[hrs + 1:hri]) * d(3600) except: h = 0 mni = x.find('m') for each in sp: if each < mni - 1: mns = each try: m = d(x[mns + 1:mni]) * d(60) except: m = 0 sei = x.find('s') for each in sp: if each < sei - 1: ses = each try: s = d(x[ses + 1:sei]) except: s = 0 msi = x.find('n') for each in sp: if each < msi - 1: mss = each try: ms = d(x[mss + 1:msi]) * d(0.001) except: ms = 0 return (neg * (h + m + s + ms))
def cTime(a, f): #converts x:xx:xx.xxx to xxxxxx.xxx x = d(0) n = d(1) if a[0] == '-': n = d(-1) a = a[1:] try: c = d(a.split(";")[1]) / d(f) except: c = d(0) b = a.split(";")[0].split(":") for i in range(len(b)): x += d(60)**d(i) * d(b[-(i + 1)]) return n * (d(x) + c)
def pick_random(edges): """ Picks a random edge according to its weight. :param edges: A list of edges together with their edge context :return: """ # # # Here's how it works: # # First we compute the probability of each element. # This is its weight divided by the sum of all weights # # Now we imagine all these weights summed up in the [0,1] interval. # # It looks something like this: # # ++++++++++++++++++++++++++++++++++++++++ # | 0.5 | 0.25 | 0.25 | # ++++++++++++++++++++++++++++++++++++++++ # 0 1 # # If we now randomly pick a number in the interval, # the probility that the number is in a certain interval is # exactly the probability of the corresponidng element # # ++++++++++++++++++++++++++++++++++++++++ # | 0.5 | 0.25 | 0.25 | # ++++++++++++++++++++++++++++++++++++++++ # 0 ^ 1 # | # With p=0.5 we pick a point from the first element's interval # Sum of all weights sum_weights = sum([d(ctx.attractiveness) for u, v, ctx in edges]) # Variable that stores the cumulative Probability cum_prob = 0 # Generate a random number between 0 and 1 r = random.random() # Iterate over all edges, order does not matter for u, v, ctx in edges: # Increase cumulative cum_prob += ctx.attractiveness / sum_weights # Check if value is in interval if cum_prob >= r: # Return edge return u, v, ctx # Continue otherwise # We may reach this point due to rounding errors # Just return a random element return random.choice(edges)
def test_items_creation_no_date(self): Category.objects.create(name='tom', color='ffffff') DateEntry.objects.create(date=datetime(2019, 12, 11)) entrys = [] items = (('Kostka do gry', d(5.20)), ('Cyna', d(21.33)), ('Pudełko', d(34))) for name, price in items: entrys.append( CostItem(category=None, date=None, name=name, value=Decimal(5.20))) CostItem.objects.bulk_create(entrys) assert CostItem.objects.count() == 3
def uTime(a): #inverse of cTime a = a.quantize(d('1.111'), rounding=ROUND_HALF_UP) t1, t0 = divmod(a, 1) t2, t1 = divmod(t1, 60) t3, t2 = divmod(t2, 60) t0 = round(t0 * 1000) if t0 == 0: t4, t3 = divmod(t3, 60) else: t4 = 0 if t4 != 0: #formatting :( return ("%d:%02d:%02d:%02d" % (t4, t3, t2, t1)) elif t3 != 0 and t0 != 0: # despite similarities, realtime and uTime can't be merged into #the same function because :::. and h/m/s/ms are read differently return ("%d:%02d:%02d.%03d" % (t3, t2, t1, t0)) elif t3 != 0 and t0 == 0: return ("%d:%02d:%02d" % (t3, t2, t1)) elif t2 != 0 and t0 != 0: return ("%d:%02d.%03d" % (t2, t1, t0)) elif t2 != 0 and t0 == 0: return (("%d:%02d" % (t2, t1))) elif t0 != 0: return ("%d.%03d" % (t1, t0)) else: return (str(int(t1)))
def leftSolve(a, K, b): n, m = len(a), len(b) if n >= m: # Already greater return b diff = m - n K = min(K, diff) if K < diff: return '9' * K + a else: upper = b[-n:] if d(upper) < d(a): thatDig = oneUp(b[-n - 1]) else: thatDig = b[-n - 1] return b[:m - n - 1] + thatDig + a[:]
def calculate_stocks_value(cls, stocks): total_value = d('0') total_value_change = d('0') for stock in stocks: try: total_value += d(stock['value']) except decimal.InvalidOperation: pass try: total_value_change += d(stock['value_change']) except decimal.InvalidOperation: pass return str(total_value), str(total_value_change)
def __init__(self): self.state = None self.observation_space = [[15, 24], [-.05, .05]] self.desiredTemp = GetDesiredTemp( ) #Get from dataset based on time (userinput values) self.currTemp = 16 #Get from dataset based on time (imaginary sensor) self.change = round(d(.05), 2) self.heatingState = "UpTowardsGoal" self.tick = 0
def calculate_interest_of_savings_account(): savings_accounts = SavingsAccount.objects.filter(status='Approved') for savings_account in savings_accounts: current_date = datetime.now().date() year_days = 366 if calendar.isleap(current_date.year) else 365 daily_interest_rate_charged = ( savings_account.savings_balance * savings_account.annual_interest_rate) / (d(year_days) * 100) savings_account.savings_balance += daily_interest_rate_charged savings_account.save()
def evaporate(self, rho): """ Reduces pheromone by factor rho :param rho: a real number between 0 and 1 (inclusive) """ assert 0 <= rho <= 1 self._tau = d(rho) * self._tau self._updateAttractiveness()
def getnum(v): var = "x" vtext = v.split(',') #start point for i in range(len(vtext)): if vtext[i][4:7] == 'cmt': var = d(vtext[i].split('"')[-2]) #crops out the useless stuff var = d(var - var % (d(1) / fr)) #rounds down the time to the start of a frame if var == "x": try: var = cTime(v, fr) except: try: var = numtime(v) except: var = "x" return var
def get_ln2_differences(offset=10, base=1, pc=5, pd=getcontext().prec, check_rep=False, v=True): """ List the `{offset}` last values in the sequence of `10**({pc} + 1)`. `pc` and `pd` relate to the exponents ("powers") of `c` and `d` respectively, and these may be non-integer (i.e. floats). """ base = d(base) # exponents and subtrahends do not need to be Decimal type c = d(10)**d(pc + 1) # value beyond which to "continue" the sequence frac_list = [] sum_list = [] assert offset < c, ValueError("Decrease offset or increase pc") vals = [] x_range = range(int(c) - offset, int(c)) for x in x_range: sign = [-1, 1][x % 2] frac = base * sign / x frac_list.append(frac) frac_sum = sum(frac_list) sum_list.append(frac_sum) #print(frac, "--->", frac_sum) val = d(10)**pd * abs(log_two - sum(sum_list[-2:]) / 2) if v: print(f"{x}:", val, file=stderr) vals.append(val) arr = np.array([x_range, vals]).T if check_rep: diffs_consec = np.ediff1d(arr[:, 1]) diffs_even = np.ediff1d(arr[:, 1][::2]) diffs_odd = np.ediff1d(arr[1:, 1][::2]) checked = 0 in np.hstack([diffs_consec, diffs_even, diffs_odd]) if v: result_check_message(check_bool=checked) return checked else: return arr
def my_tracer(a, b, c): # traced variables send 3 arguments to this global fr try: fr = d(fv.get()) except: try: fr = frac(fv.get()) except: fr = 1000 #by default, no rounding happens. not recommended if fr == 0: fr = 1000 try: mod = cTime(mv.get(), fr) #print('c',mod) except: #the modifier, added to the resulting time try: mod = frac(mv.get()) #print('f',mod) except: try: mod = numtime(mv.get()) # yes #print('n',mod) except: mod = d(0) #print('0',mod) start = getnum(sv.get()) end = getnum(ev.get()) try: # if youtube debug info is entered correctly, displays time as h m s ms if end - start + mod < 0: negative = True # if start > end, a negative is put in front of the absolute value of #the result else: negative = False new_text = negative * "- " + realtime(abs(end - start + mod)) except: new_text = "" tv.set(new_text)
def get_portfolio_stock_info(cls, portfolio, base_currency): symbols_quantities = { stock.stock.symbol_ric: stock.quantity for stock in portfolio.stocks.all() } list_symbols = list(symbols_quantities.keys()) stock_trade_info = cls.get_stock_trade_info( list_symbols[0:MAX_SYMBOLS_ALLOWED]) stock_trade_info += cls.get_stock_trade_info( list_symbols[MAX_SYMBOLS_ALLOWED:2 * MAX_SYMBOLS_ALLOWED]) if len(list_symbols) > 2 * MAX_SYMBOLS_ALLOWED: logger.warning(f'number of symbols in portfolio exceed ' f'maximum of {2 * MAX_SYMBOLS_ALLOWED}') exchange_rate_euro = Currency.objects.get( currency='EUR').usd_exchange_rate stock_info = [] for stock in stock_trade_info: stock['quantity'] = symbols_quantities[stock['symbol']] exchange_rate = Currency.objects.get( currency=stock['currency']).usd_exchange_rate try: value = d(stock["quantity"]) * d( stock["price"]) / d(exchange_rate) value_change = (d(stock["quantity"]) * d(stock["day_change"]) / d(exchange_rate)) except (NameError, decimal.InvalidOperation): value = 'n/a' value_change = 'n/a' if base_currency == 'USD' or value == 'n/a': pass elif base_currency == 'EUR': value *= d(exchange_rate_euro) value_change *= d(exchange_rate_euro) else: logger.warning(f'Invalid base currency {base_currency}') stock['value'] = str(value) stock['value_change'] = str(value_change) stock_info.append(stock) return stock_info
def fact(n): n = d(n) n //= d(1) if (n == d(0)): return d(1) total = d(1) step = d(1) while step <= n: total *= step step += d(1) return total
def __init__(self, distance, alpha, beta): #Set distance self._distance = distance # Set alpha self._alpha = alpha # Set beat self._beta = d(beta) # Set initial TAU self._tau = TAU_INITIAL # Compute eta self._eta = d(1) / self.distance self._phi = self._eta # Compute initial attractiveness self._updateAttractiveness()
def test_items_creation(self): Category.objects.create(name='tom', color='ffffff') DateEntry.objects.create(date=datetime(2019, 12, 11)) entrys = [] items = (('Kostka do gry', d(5.20)), ('Cyna', d(21.33)), ('Pudełko', d(34))) for name, price in items: entrys.append( CostItem(category=Category.objects.get(), date=DateEntry.objects.get(), name=name, value=Decimal(5.20))) CostItem.objects.bulk_create(entrys) cat = Category.objects.get() print(cat.cost_items.all()) print(cat.cost_items.all_costs()) print(cat.income_items.all()) assert cat.cost_items.count() == 3 assert cat.income_items.count() == 0
def __init__(self, numbers): self.e = [] n = len(numbers) if (n & (n - 1)) != 0: x = ceil(log(n, 2)) self.n = 2**x while n != self.n: numbers.append(d('Infinity')) n += 1 else: self.n = n temp = numbers[::-1] for i in range(0, 2 * (self.n - 1), 2): temp.append(min(temp[i], temp[i + 1])) temp.append(d('Infinity')) self.e = temp[::-1] self.size = len(temp)
def assertBiggerZero(n): """ Checks if the given value is bigger than 0. If it is, it returns the value, otherwise the next bigger value :param n: A number or Decimal :return: n, is n > d(0) n.next_plus(), otherwise """ # Assert that n is Decimal n = d(n) # Check if zero if n == d(0): # Return the next bigger number, # Actual step size is defined by Decimal.Context return n.next_plus() else: return n
def orderToSlot(order): if verifyOrder(order) != True: raise Exception("Invalid order list") total = len(order) items = list(range(total)) slots = [] for _ in range(total - 1): slots.append(items.index(int(order[0]))) items.pop(items.index(int(order[0]))) order.pop(0) return [d(slot) for slot in slots]
def numToSlot(value, total): total = d(int(abs(total))) value = d(value) max = fact(total) # calculate max combinations slotNum = total # slot column number, starting with highest value and decrements slot = value # slot value carried within loop for calculations slots = [] # slot numbers to return # kill if value is out of bounds if (value > max) or (value < d(0)): raise ValueError("Value too big to store") # loop until all necessary slots filled (total number of items shuffled - 1) for _ in range(int(total) - 1): max /= slotNum # reduce factorial by 1. (e.g. 4!/4 = 3!) slotNum -= d(1) # decrement slot number slots.append( slot // max ) # add slot number as rounded-down quotient of the now reduced max and value slot %= max # get the remainder for next calculation return slots
def format_totals_values(total_value, total_value_change): ''' returns a dict for totals for context display''' try: if abs(float(d(total_value_change))) < 0.1: color = 'black' caret = CARET_NO_CHANGE elif float(d(total_value_change)) < 0: color = 'red' caret = CARET_DOWN else: color = 'green' caret = CARET_UP except decimal.InvalidOperation: color = 'black' caret = CARET_NO_CHANGE total_value = format_decimal_number(total_value) total_value_change = format_decimal_number(total_value_change) return {'value': total_value, 'value_change': total_value_change, 'caret': caret, 'color': color}