def register(self, confirm_pass): if self.is_value_exists(self.nickname, 'nickname'): print('{} can\'t register. Username already exists'.format( self.__class__.__name__)) elif self.is_value_exists(self.email, 'email'): print('{} can\'t register. Email already exists'.format( self.__class__.__name__)) elif self.password != confirm_pass: print('Confirmed password isn\'t correct') else: print('{} successfully registered'.format(self.__class__.__name__)) self.currency = { Currency.GOLD_ID: Currency(Currency.GOLD_ID, 'Gold', value=0), Currency.SILVER_ID: Currency(Currency.SILVER_ID, 'Silver', value=50), Currency.BRONZE_ID: Currency(Currency.BRONZE_ID, 'Bronze'), } self.progresses = { Progress.EXPERIENCE_ID: Progress(Progress.EXPERIENCE_ID, 'Experience'), Progress.SOME_PROGRESS_ID: Progress(Progress.SOME_PROGRESS_ID, 'Some_Progress2'), } self.achievements = {} self.save_to_db()
def test_add_two_currencies(): one_dollar = Currency('USD', 1) two_dollars = Currency('USD', 2) result = one_dollar + two_dollars assert result.value == 3 assert result.currency_type == 'USD' assert isinstance(result, Currency)
def test_conversion(): dict_rates = {'USD': 1.0, 'EUR': 0.94, 'GBP': 0.80} c = CurrencyConverter(dict_rates) assert c.convert(a, "USD") == Currency("5.00", "USD") assert c.convert(d, "EUR") == Currency(0.94, "EUR") assert c.convert(i, "USD") == Currency(1, "USD") assert c.convert(j, "USD") != Currency(1, "USD")
def __init__(self, cli_data, cache, ver, user, symbol, amount, price): super().__init__() self.ver = ver self.cli_data = cli_data self.cache = cache self.user = user self.symbol = symbol self.amount = Currency(amount) self.price = Currency(price) self.stopevent = threading.Event()
def test_currency_equivalence_to_zero(): zero_bound1 = Currency(0.0) zero_bound2 = Currency(0) assert zero_bound1.dollars == 0 assert zero_bound1.cents == 0 assert zero_bound1 == 0.0 assert zero_bound1 == 0 assert zero_bound1 == zero_bound2 assert isinstance(zero_bound1.dollars, int) assert isinstance(zero_bound1.cents, int) assert str(zero_bound1) == "0.00" assert float(zero_bound1) == 0.0 assert -0.01 < zero_bound1 < 0.01
def change_year(self): if self.now_year != self.last_year + 1: str_now = str(self.now_year) if self.now_year != 2016: self.EURUSD = Currency('EURUSD', str_now + '-1', str_now + '-12') else: self.EURUSD = Currency('EURUSD', str_now + '-1', str_now + '-7') self.now_year += 1 return True else: return False
def test_currency_equivalence_negative(): neg_low_bound1 = Currency(-0.01) neg_low_bound2 = Currency(-1) neg_low_bound3 = Currency("-0.01") assert neg_low_bound1.dollars == 0 assert neg_low_bound1.cents == -1 assert neg_low_bound1 == -0.01 assert neg_low_bound2 == neg_low_bound1 - 0.99 assert neg_low_bound1 == neg_low_bound3 assert neg_low_bound1 != neg_low_bound2 assert isinstance(neg_low_bound1.dollars, int) assert isinstance(neg_low_bound1.cents, int) assert str(neg_low_bound1) == "-0.01" assert float(neg_low_bound1) == -0.01 assert 0.0 > neg_low_bound1 > -0.02
def test_currency_equivalence_low_positive(): pos_low_bound1 = Currency(0.01) pos_low_bound2 = Currency(1) pos_low_bound3 = Currency("0.01") assert pos_low_bound1.dollars == 0 assert pos_low_bound1.cents == 1 assert pos_low_bound1 == 0.01 assert pos_low_bound2 == pos_low_bound1 + 0.99 assert pos_low_bound1 == pos_low_bound3 assert pos_low_bound1 != pos_low_bound2 assert isinstance(pos_low_bound1.dollars, int) assert isinstance(pos_low_bound1.cents, int) assert str(pos_low_bound1) == "0.01" assert float(pos_low_bound1) == 0.01 assert 0.0 < pos_low_bound1 < 0.02
def Init(): """ [Required] Initialize Data (Only called on load) """ # settings initialization global settings settings = MySettings(config_file) settings.save() # database initialization global currency, db db = InstancedDatabase(database_file) currency = Currency(Parent, db, settings.name, settings.frequency * 60, settings.quantity) currency.only_subs = settings.only_subs currency.exclude_users = settings.exclude_users # streamlabs notifies global streamlabs_api streamlabs_api = SLNotifies(Parent, currency, settings.streamlabs_bits) if settings.streamlabs_apikey: streamlabs_api.connect(settings.streamlabs_apikey) # loot initialization global loot loot = Loot(Parent, db) return
def convert(self, currency_obj, code_to_convert): if currency_obj.code in self.dict_rates and code_to_convert in self.dict_rates: return Currency( currency_obj.amount * (self.dict_rates[code_to_convert]) / self.dict_rates[currency_obj.code], code_to_convert) else: raise UnknownCurrencyCodeError
def value2object(value, stringtypes): if value is None: return None if stringtypes == "int": return int(value) elif stringtypes == "float": return float(value) elif stringtypes == "Decimal": return Decimal(value) elif stringtypes == ["datetime", "date", "time"]: return value elif stringtypes in ["EUR", "USD"]: try: from currency import Currency return Currency(value, "EUR") except ImportError: raise NotImplementedError( "You need https://github.com/turulomio/reusingcode/python/currency.py to use this function." ) elif stringtypes == "Percentage": try: from percentage import Percentage return Percentage(value, 1) except ImportError: raise NotImplementedError( "You need https://github.com/turulomio/reusingcode/python/currency.py to use this function." ) return value
def check_money(self, user): try: account = self.get_current_funds(user) except KeyError: response = self.new_user(user) account = Currency(0.0) return account
def load_from_db(self, nickname): sql_data = {'nickname': nickname} sql_query = """SELECT id, role, nickname, email, password, banned, description FROM user WHERE nickname=%(nickname)s""" with self.connect: cur = self.connect.cursor() cur.execute(sql_query, sql_data) result = cur.fetchone() if not result: return False user = UserFactory.create_user(result) achievements = Achievement.load_from_db(user.user_id, self.connect) user.achievements = {} for achievement in achievements: user.achievements[achievement[1]] = Achievement( achievement[1], achievement[0]) currencies = Currency.load_from_db(user.user_id, self.connect) user.currency = {} for currency in currencies: user.currency[currency[2]] = Currency(currency[2], currency[0], currency[1]) progresses = Progress.load_from_db(user.user_id, self.connect) user.progresses = {} for progress in progresses: user.progresses[progress[0]] = Progress(progress[0], progress[1], progress[2], progress[3]) return user
def __init__(self): self.client = zulip.Client(site="https://fazeup.zulipchat.com/api/") self.subscribe_all() self.hacknews = Hackernews() self.trans = Translate() self.movie = Movie() self.lyrics = Lyrics() self.holiday = Holiday() self.currency = Currency() self.cricket = Cricket() # self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() # self.tw = Twimega() # self.motivate = Motivate() self.shortenedurl = Urlshortener() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() print("done init") self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl", "movie", "currency", "holiday", "lyrics" ]
def test_new_currency(self): currency = Currency('EURUSD', '2003-5', '2006-5') while True: data = currency.get_data() if data == False: break print(data)
def convert(self, other, conversion_unit): if other.code in self.rates and conversion_unit in self.rates: new_amount = (other.amount * self.rates[conversion_unit]) / self.rates[other.code] return Currency(round(new_amount, 2), conversion_unit) else: raise UnknownCurrencyCodeError
def test_currency_json_encoding(): import json unencoded = Currency(12.34) user_dict = {"acc": unencoded, "stk": 34.56, "empty_list": []} assert json.dumps( user_dict, cls=Currency) == '{"acc": 12.34, "stk": 34.56, "empty_list": []}'
def convert(self, from_currency, to_currency_code): try: rate = (self.conversion_dict[to_currency_code] / self.conversion_dict[from_currency.currency_code]) raw_value = rate * from_currency.value rounded_value = round(raw_value, 2) return Currency(to_currency_code, rounded_value) except: raise UnkownCurrencyCodeError()
def process_currency(raw_json, currency_to_process): currency_info = raw_json[currency_to_process] return Currency( currency_to_process, "Updated: " + currency_info[BUY_RATE_KEY][DATE_KEY], fixed_digits(float(currency_info[BUY_RATE_KEY][RATE_KEY])), fixed_digits(float(currency_info[SELL_RATE_KEY][RATE_KEY])))
def value2object(value, stringtypes): if value is None: return None if stringtypes == "int": return int(value) elif stringtypes == "float": return float(value) elif stringtypes == "Decimal": return Decimal(value) elif stringtypes == ["datetime", "date", "time"]: return value elif stringtypes in ["EUR", "€"]: return Currency(value, "EUR") elif stringtypes in ["USD", "$"]: return Currency(value, "EUR") elif stringtypes == "Percentage": return Percentage(value, 1) return value
def __init__(self): self.money = 100000 self.account = Account(self.money) self.account.set_stop(0, 10000) self.currency_string = 'EURUSD' self.currency = Currency(self.currency_string, '2015-1', '2015-2') self.multiple = 10 self.main() print_earn(self.account)
def __init__(self): try: with open(self.FILE_NAME, 'r') as f: currencies_json = json.load(f) self.__currencies = { Currency(int(currency)): count for currency, count in currencies_json.items() } except: self.__currencies = self.__default_currency_stock()
def quote(self, symbol, user): val = [] try: response = requests.get( f"{self.quote_cache_server_url}/{QuoteCacheUrls.GET_QUOTE}/{symbol}" ).json() if (response["status"] != "SUCCESS" or (time.time() - float(response["data"]["quote_time"])) >= 60): val = self.new_quote(symbol, user) else: data = response["data"] quote_time = data["quote_time"] quote_amount = Currency(data["dollars"]) + Currency( data["cents"]) cryptokey = data["cryptokey"] val = [quote_amount, symbol, user, quote_time, cryptokey] except KeyError as e: val = self.new_quote(symbol, user) return val
def __init__(self): self.money = 100000 self.account = Account( self.money ) self.account.set_stop(10000,2000) self.currency_string = 'EURUSD' self.currency = Currency( self.currency_string , '2015-1' , '2016-3' ) self.multiple = 3 self.minute = 600 self.main() print_earn( self.account )
def __init__(self): self.money = 100000 self.account = Account( self.money ) self.currency_string = 'EURUSD' self.currency = Currency( self.currency_string , '2001-1' , '2001-2' ) self.minute = 240 self.multiple = 3 self.main() self.print_hold_record() self.print_order() self.print_earn()
def parse_currency(self, row_element_by_css_selector): currency = Currency() currency.title = row_element_by_css_selector.find_element_by_css_selector( 'th').text currency.sell = row_element_by_css_selector.find_element_by_css_selector( 'td:nth-child(2) span > span').text currency.buy = row_element_by_css_selector.find_element_by_css_selector( 'td:nth-child(3) span > span').text return currency
def run(self): while not self.stopevent.isSet(): quote = Currency(self.cache.quote(self.symbol, self.user)[0]) if self.ver == "buy" and quote <= self.price: self.cli_data.commit_buy(username=self.user, stock_symbol=self.symbol, price=quote, buy_amount=self.amount) break elif self.ver == "sel" and quote >= self.price: count = int(self.price.dollars / quote.dollars) self.cli_data.commit_sell(username=self.user, stock_symbol=self.symbol, price=quote, count=count) break self.stopevent.wait(60.0)
def test_currency_initializer_zero_value(): try: zero_bound1 = Currency(0.0) Currency(0) Currency(zero_bound1) Currency("0") Currency("0.0") Currency() Currency(None) except ValueError as e: pytest.fail(repr(e)) with pytest.raises(ValueError): zero_bound_bad = Currency("zero")
def commit_sell(self, username, stock_symbol, price, count): total = price * count stock_price = Currency(price) cost = stock_price * count return self.post_to_model( UserUrls.COMMIT_SELL, { "username": username, "stock_symbol": stock_symbol, "stock_price_dollars": stock_price.dollars, "stock_price_cents": stock_price.cents, "dollars_delta": cost.dollars, "cents_delta": cost.cents })
def add_money(self, user, amount): try: assert type(user) == str amount = Currency(amount) self.post_to_model(UserUrls.ADD_FUNDS, { "username": user, "dollars": amount.dollars, "cents": amount.cents }) except KeyError: self.new_user(user) return True