Example #1
0
def add_handler(sub_args):
    alias = sub_args.alias
    service = sub_args.service
    account = sub_args.account
    if alias is None:
        alias = str(click.prompt("Please type an alias to store the credential (this alias must be unique)"))
    if not _alias_valid(alias):
        select = Account.select().where(Account.alias == alias)
        service = str(select[0].service)
        account = str(select[0].account)
        sys.exit("Aborting , this alias already exist for the service " + service + " and the account " + account)
    if service is None:
        service = str(click.prompt("Please type the name of the service you want to use"))
    if not sub_args.noformat:
        if service.split("://")[0].lower() == "http":
            service = urlparse(service).netloc
        service = service.lower()
    if account is None:
        account = str(click.prompt("Please enter the account for the credential (aka login)"))
    select = Account.select().where((Account.service == service) & (Account.account == account))
    if len(select) != 0:
        print "The account " + account + " associated to the service " + service + " already exist"
        if not click.confirm("Do you wish to continue adding this credential ?"):
            sys.exit("Aborting")
    passphrase = getpass.getpass("Enter passphrase:")
    Account.create(service=service,
                   account=account,
                   passphrase=passphrase,
                   alias=alias)
Example #2
0
    def _new(cls, author, link, parent, body, ip):
        c = Comment(body = body,
                    link_id = link._id,
                    sr_id = link.sr_id,
                    author_id = author._id,
                    ip = ip)

        c._spam = author._spam

        #these props aren't relations
        if parent:
            c.parent_id = parent._id

        c._commit()

        link._incr('num_comments', 1)

        to = None
        if parent:
            to = Account._byID(parent.author_id)
        elif link.is_self:
            to = Account._byID(link.author_id)

        inbox_rel = None
        # only global admins can be message spammed.
        if to and (not c._spam or to.name in g.admins):
            inbox_rel = Inbox._add(to, c, 'inbox')

        return (c, inbox_rel)
Example #3
0
 def cprint(a: Account):
     """Clean prints an Account
     """
     print("Account({},{},".format(a.get_name(), a.get_kind()))
     pprint(a.get_ts())
     print(",")
     pprint(a.get_budgets())
Example #4
0
def _view_range_budget(a: Account, timeframe: [(int, int)], width: int) -> str:
    """Returns string of Account's budget tuple over a certain time period
    """
    bud_lim = ((width-10)//11)                                                  # How many budgets can be on one line
    it = len(timeframe)                                                         # How many budgets that will be displayed 
    set_lim = it//bud_lim + 1                                                   # How many sets to iterate through  
    set_apprch = 0; bud_apprch = 0; lines = list() 
        
    while set_apprch != set_lim: 
        set_apprch += 1
        title_sub_str = "Account {} for set {}".format(a.get_name(), set_apprch)
        hd          = "="*width + "\n"
        space_amt   = width//2-len(title_sub_str)
        title_str   = "{}{}{}".format(" "*space_amt, title_sub_str, " "*space_amt)
        attrib_str  = "Attribute|"
        goal_str    = "Goal.....|"
        reach_str   = 'Reached..|'
        remain_str  = "Remaining|"
                
        for y,m in timeframe[(set_apprch-1)*min(bud_lim, it):set_apprch*min(bud_lim, it)]:
            bud_apprch += 1

            attrib_str += "  {} {}|".format(bc.months_abv(m), y+1)
            
            g_str = "{:.2f}".format(a.get_goal(y,m)/100) 
            goal_str += "."*(10-len(g_str)) + g_str+"|"
            
            r_str = "{:.2f}".format(a.get_reached(y,m)/100)
            reach_str += "."*(10-len(r_str)) + r_str+"|"
            
            e_str = "{:.2f}".format(a.get_remain(y,m)/100)
            remain_str += "."*(10-len(e_str)) + e_str + "|"
        lines.append(title_str + "\n" + hd + attrib_str + "\n" + goal_str + "\n" + reach_str + "\n" + remain_str + "\n")
    return "\n".join(lines)
Example #5
0
def draw(uid, currency):
    s = current_session()
    u = Account.find(uid)
    if not u:
        raise exceptions.UserNotFound

    helpers.require_free_backpack_slot(s, uid)

    if currency == 'ppoint':
        amount = constants.LOTTERY_PRICE
        Account.add_user_credit(u, [('ppoint', -amount)],
                                exceptions.InsufficientFunds)

    elif currency == 'jiecao':
        amount = constants.LOTTERY_JIECAO_PRICE
        Account.add_user_credit(u, [('jiecao', -amount)],
                                exceptions.InsufficientFunds)

    else:
        raise exceptions.InvalidCurrency

    reward = random.choice(constants.LOTTERY_REWARD_LIST)

    item = Item(owner_id=uid, sku=reward, status='backpack')
    s.add(item)
    s.flush()
    s.add(ItemActivity(
        uid=uid, action='lottery', item_id=item.id,
        extra=json.dumps({'currency': currency, 'amount': amount}),
        created=datetime.datetime.now(),
    ))
    return reward
Example #6
0
def main():

    try:

        rate_history = RateHistory(u"配置.ini")
        print rate_history
        # return

        if len(sys.argv) < 2:
            data_file = raw_input(u"请输入文件名称:".encode('gbk')).decode('gbk')
        else:
            data_file = sys.argv[1]

        if not os.path.isfile(data_file):
            print u"文件'%s'不存在" % data_file
            exit(0)

        balance_list = load_balance_flow(data_file)
        acc = Account(rate_history)
        earn = acc.interest(balance_list)

        open(u"明细.csv", "w").write(str(acc))
        print u"余额明细如下\n%s" % acc
        print u"明细可参考文档'明细.csv'"
        print u"总利息 %s亿,余额 %s亿" % (earn, acc.total_amount())
        print u"计算完成!"
    except Exception, e:
        print u"异常:%s" % str(e)
        traceback.print_tb()
def test_checking_account():
    bank = Bank()
    checkingAccount = Account(CHECKING)
    bill = Customer("Bill").openAccount(checkingAccount)
    bank.addCustomer(bill)
    checkingAccount.deposit(100.0)
    assert_equals(bank.totalInterestPaid(), 0.1)
Example #8
0
    def modify(self, account, newname = None):
        if not Account.hasSupport(account.network):
            return False

        if not self.exists(account):
            return False

        pm = PersistenceManager()

        if not pm.existsConfig():
            return False

        config = pm.readConfig()

        accountType = Account.networkToAccount(account.network)

        for entry in config['accounts'][account.network]:
            if entry['name'] == account.name:
                if newname:
                    entry['name'] = newname
                if accountType == 'OAuth':
                    entry['key'], entry['secret'] = account.credentials()
                elif accountType == 'UserPass':
                    entry['user'], entry['password'] = account.credentials()

                break

        pm.writeConfig(config)

        return True
Example #9
0
    def _new(cls, author, link, parent, body, ip):
        from r2.lib.db.queries import changed

        c = Comment(_ups=1, body=body, link_id=link._id, sr_id=link.sr_id, author_id=author._id, ip=ip)

        c._spam = author._spam

        # these props aren't relations
        if parent:
            c.parent_id = parent._id

        link._incr("num_comments", 1)

        to = None
        name = "inbox"
        if parent:
            to = Account._byID(parent.author_id, True)
        elif link.is_self and not link.noselfreply:
            to = Account._byID(link.author_id, True)
            name = "selfreply"

        c._commit()

        changed(link, True)  # only the number of comments has changed

        inbox_rel = None
        # only global admins can be message spammed.
        if to and (not c._spam or to.name in g.admins):
            inbox_rel = Inbox._add(to, c, name)

        return (c, inbox_rel)
Example #10
0
class AccountTest(unittest.TestCase):

    def setUp(self):
        self.account = Account(number='123456', holder='Linus')

    def test_it_has_a_number(self):
        self.account.number |should| equal_to('123456')

    def test_it_as_a_holder(self):
        self.account.holder |should| equal_to('Linus')

    def test_it_has_a_balance_beginning_at_zero(self):
        self.account.balance |should| be(0)

    def test_it_allows_deposit(self):
        self.account.deposit(100)
        self.account.balance |should| be(100)
        self.account.deposit(100)
        self.account.balance |should| be(200)

    def test_it_allows_withdrawals(self):
        self.account.deposit(100)
        self.account.withdrawal(75)
        self.account.balance |should| be(25)

    def test_it_raises_an_error_for_insufficient_balance(self):
        self.account.deposit(100)
        (self.account.withdrawal, 100.01) |should| throw(InsufficientBalance)
Example #11
0
    def getAllByNetwork(self, network):
        if not Account.hasSupport(network):
            return None

        pm = PersistenceManager()

        if not pm.existsConfig():
            return None

        config = pm.readConfig()

        accounts = []
        accountType = Account.networkToAccount(network)

        for entry in config['accounts'][network]:
            account = Account.getAccount(network, entry['name'])

            if accountType == 'OAuth':
                account.setCredentials((entry['key'], entry['secret']))
            elif accountType == 'UserPass':
                account.setCredentials((entry['user'], entry['password']))

            accounts.append(account)

        return accounts
Example #12
0
def new_account():
    """
    Endpoint for creating new accounts when the app is installed.
    Returns the account id and the account's secret key.
    """
    if not request.form.get('uuid'):
        return api_error('must provide a device uuid')

    uuid = request.form['uuid'].strip()

    name = request.form['name'].strip() if 'name' in request.form else None
    email = request.form['email'].strip() if 'email' in request.form else None
    phone = request.form['phone'].strip() if 'phone' in request.form else None

    if phone == '':
      phone = None

    if Account.uuid_used(uuid):
        return user_error('an account already exists for this device.')
    if phone and Account.phone_used(phone):
        return user_error('phone number already in use')
    if email and Account.email_used(email):
        return user_error('email already in use')

    new_account = Account.new(uuid, name, phone, email)

    if not new_account:
        return api_error('unable to create new account')

    ret = {'aid': new_account.aid, 'key': new_account.key}
    return jsonify(**ret)
Example #13
0
    def _new(cls, author, link, parent, body, ip,criticism=False):
        from r2.lib.db.queries import changed

        #We're turing it off for now...
        criticism = False
        c = Comment(_ups = 1,
                    body = body,
                    link_id = link._id,
                    sr_id = link.sr_id,
                    author_id = author._id,
                    ip = ip)

        c._spam = author._spam
	c.criticism=criticism

        #these props aren't relations
        if parent:
            c.parent_id = parent._id

	#should increment based on crit flag
	#Each should contain the root author and its id, problem is the id isn't created yet if we're the root so have to be clever
	if criticism:
		link._incr("num_criticisms",1)
		if parent:
			c.rootauthor=parent.rootauthor
			if parent.rootid:
				c.rootid=parent.rootid
			else:
				c.rootid=parent._id
		else:
			c.rootauthor=author._id
			c.rootid=False
	else:
        	link._incr('num_comments', 1)

        to = None
        name = 'inbox'
        if parent:
            to = Account._byID(parent.author_id, True)
        elif link.is_self and not link.noselfreply:
            to = Account._byID(link.author_id, True)
            name = 'selfreply'

        c._commit()

        changed(link, True)  # link's number of comments changed

        inbox_rel = None
        # only global admins can be message spammed.
        # Don't send the message if the recipient has blocked
        # the author
        if to and ((not c._spam and author._id not in to.enemies)
            or to.name in g.admins):
            # When replying to your own comment, record the inbox
            # relation, but don't give yourself an orangered
            orangered = (to.name != author.name)
            inbox_rel = Inbox._add(to, c, name, orangered=orangered)

        return (c, inbox_rel)
Example #14
0
def _view_all_budgets(a: Account, width: int) -> str:
    """Returns string of Account's budget tuple over all time periods.
    Prints out strings with the specified maximum width  
    """
    r = sorted(
        [(y,m) for y in a.get_budgets() for m in a.get_budgets(y)], 
        key=lambda x: (x[0], x[1]), reverse = True)
    return "\n"+_view_range_budget(a, r, width)
def _breakdown_str(i: int, a: Account, tf: [(int, int)], net: float, line: str) -> str:
    """Returns string indicating the breakdown of an Account 
    """
    tf_amount   = round(
        sum(t.get_amount() for t in a.get_ts() \
            if (t.get_year(), t.get_month()) in tf)/100, 2)
    tf_perc     = round((tf_amount/net)*100, 2)
    return line.format(i, a.get_name(), tf_amount, tf_perc)
Example #16
0
 def create_account(self, attr, password, password_confirm):
     account = Account("", attr)
     if account.create_key(password, password_confirm):
         self.accounts[account._id] = account.store()
         self.set_account(account._id)
         return self._store()
     else:
         return False
Example #17
0
def _um(a: Account, y: int) -> [int]:
    """Returns integers representing unique months of an Account and breakout integer
    """
    if y in a.get_budgets(): 
        return sorted(
        set(bc.months_abv(m) for m in a.get_budgets(y)), 
        key=lambda x: bc.months_to_int[x]) + [-1]
    return [-1]
 def get_default_account(cls):
     # we are not going to set the id, because we never save this
     url = 'blogtest.letseatalready.com'
     username = '******'
     password = '******'
     default_account = Account(url, username, password)
     default_account.set_section_id(AccountManager.DEFAULT_ACCOUNT_ID)
     return default_account
def _budget_total(a: Account, s: str, tf: [(int, int)]) -> int:
    """Returns sum of Account's attribute over specified timeframe
    """
    _sum = 0
    for y,m in tf: 
        if y in a.get_budgets():
            if m in a.get_budgets(y):
                method_str = "a.get_" + s + "(" + str(y)+ "," + str(m) + ")"
                _sum += eval(method_str)
    return _sum
Example #20
0
    def analyse_trade_stock(self, in_market_stra, out_market_stra, stock_id = '999999'):
        account = Account(50000*1000)  # initial money
        market_trigger = StraTrigger(in_market_stra, out_market_stra)
        market_status_in_market = False
        hold_stock_days = 0

        # tick: (time, [(stock_id, (open, close, high, low, volume)), (stock_id, ()), ...])
        for tick in self.stocks.iter_ticks():
            time_, stocks_price = tick
            for sid, price in stocks_price:
                if sid == stock_id:
                    in_market_trigger, out_market_trigger = market_trigger.update(price)
                    if not market_status_in_market:  # 不在市场内, 寻找入市机会
                        if in_market_trigger:
                            account.buy_stock(stock_id, price[1], today = time_)  # close价格作为买入, 卖出价
                            market_status_in_market = True
                            market_trigger.enter_market()
                            hold_stock_days = 0
                    else:
                        if price: hold_stock_days += 1
                        if out_market_trigger:
                            account.sell_stock(stock_id, price[1], today = time_, hold_stock_days = hold_stock_days)
                            market_status_in_market = False
                            market_trigger.quit_market()
                break
            account.update(tick)
        account.summarize()
        total_profit = account.report['account_total_profit']
        no_fee_profit = account.report['no_fee_total_profit']
        max_backoff = account.report['max_backoff']
        self._show_account_info(account)
        #self._show_stock_trade(account)
        return (total_profit, no_fee_profit, max_backoff)
Example #21
0
 def start(self, delay=0):
     if 'enabled' in self.rspec and self.rspec['enabled'] <= 0:
         logger.log('sliver_lxc: not starting %s, is not enabled'%self.name)
         return
     # the generic /etc/init.d/vinit script is permanently refreshed, and enabled
     self.install_and_enable_vinit()
     # expose .ssh for omf_friendly slivers
     if 'tags' in self.rspec and 'omf_control' in self.rspec['tags']:
         Account.mount_ssh_dir(self.name)
     Sliver_Libvirt.start (self, delay)
     # if a change has occured in the slice initscript, reflect this in /etc/init.d/vinit.slice
     self.refresh_slice_vinit()
Example #22
0
def test_transfer():
    checkingAccount = Account(CHECKING)
    savingsAccount = account(SAVINGS)
    henry = Customer("Henry").openAccount(checkingAccount).openAccount(savingsAccount)
    checkingAccount.deposit(100.0)
    savingsAccount.deposit(4000.0)
    savingsAccount.transferFunds(checkingAccount, 200.0)
    assert_equals(henry.getStatement(),
                  "Statement for Henry" +
                  "\n\nChecking Account\n  deposit $100.00\n  deposit $200.00\nTotal $300.00" +
                  "\n\nSavings Account\n  deposit $4000.00\n  withdrawal $200.00\nTotal $3800.00" +
                  "\n\nTotal In All Accounts $4100.00")
Example #23
0
    def get(self):
        """Handles OpenID Connect flow once user redirected back."""

        session = get_current_session()
        session.regenerate_id()
        session['response_with_code'] = self.request.path_url\
                                        + '?' + self.request.query_string

        # Perform steps 2, 3, and 4
        # 1) Exchange authorization code for access token
        # 2) Verify obtained access token
        # 3) Use access token to obtained user info
        openidconnect_credentials =\
        IDP_FLOW.step234_exchange_and_tokeninfo_and_userinfo(
            self.request.params)

        # Log in the user
        session['a_t'] = openidconnect_credentials.access_token
        session['user_id'] = openidconnect_credentials.userinfo.id
        session['token_info'] = openidconnect_credentials.tokeninfo
        session['user_info'] = openidconnect_credentials.userinfo

        userinfo = openidconnect_credentials.userinfo
        user_id =  openidconnect_credentials.userinfo.id

        # not happy with this, but not sure what else is available
        acct = Account(key_name=user_id,
            name=userinfo.name if 'name' in userinfo else None,
            user_info=userinfo.to_json(),
            family_name=userinfo.family_name if
            'family_name' in userinfo else None,
            locale=userinfo.locale if
            'locale' in userinfo else None,
            gender=userinfo.gender if
            'gender' in userinfo else None,
            email=userinfo.email if 'email' in userinfo else None,
            given_name=userinfo.given_name if
            'given_name' in userinfo else None,
            google_account_id=user_id if
            'id' in userinfo else None,
            verified_email=userinfo.verified_email if
            'verified_email' in userinfo else None,
            link=userinfo.link if
            'link' in userinfo else None,
            picture=userinfo.picture if
            'picture' in userinfo else None)

        # store the account within the DB
        acct.access_token = openidconnect_credentials.access_token
        acct.put()

        # redirect the user to the main page
        self.redirect('/')
Example #24
0
    def get_important_friends(cls, user_id, max_lookup=500, limit=100):
        a = Account._byID(user_id, data=True)
        # friends are returned chronologically by date, so pick the end of the list
        # for the most recent additions
        friends = Account._byID(a.friends[-max_lookup:], return_dict=False, data=True)

        # if we don't have a last visit for your friends, we don't care about them
        friends = [x for x in friends if hasattr(x, "last_visit")]

        # sort friends by most recent interactions
        friends.sort(key=lambda x: getattr(x, "last_visit"), reverse=True)
        return [x._id for x in friends[:limit]]
Example #25
0
def stream_select(game_pk):
    url = 'https://statsapi.mlb.com/api/v1/game/' + game_pk + '/content'
    headers = {
        'User-Agent': UA_ANDROID
    }
    r = requests.get(url, headers=headers, verify=VERIFY)
    json_source = r.json()

    stream_title = ['Highlights']
    #media_id = []
    free_game = []
    media_state = []
    content_id = []
    playback_scenario = []
    epg = json_source['media']['epg'][0]['items']
    for item in epg:
        xbmc.log(str(item))
        if item['mediaState'] != 'MEDIA_OFF':
            title = str(item['mediaFeedType']).title()
            title = title.replace('_', ' ')
            stream_title.append(title + " (" + item['callLetters'].encode('utf-8') + ")")
            media_state.append(item['mediaState'])
            #media_id.append(item['mediaId'])
            content_id.append(item['contentId'])
            # playback_scenario.append(str(item['playback_scenario']))

    # All past games should have highlights
    if len(stream_title) == 0:
        # and stream_date > localToEastern():
        msg = "No playable streams found."
        dialog = xbmcgui.Dialog()
        dialog.notification('Streams Not Found', msg, ICON, 5000, False)
        xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem())
        sys.exit()

    stream_url = ''

    dialog = xbmcgui.Dialog()
    n = dialog.select('Choose Stream', stream_title)
    if n > -1 and stream_title[n] != 'Highlights':
        account = Account()
        stream_url, headers = account.get_stream(content_id[n-1])

    if '.m3u8' in stream_url:
        play_stream(stream_url, headers)

    elif stream_title[n] == 'Highlights':
        highlight_select_stream(json_source['highlights']['live']['items'])

    else:
        xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem())
        xbmc.executebuiltin('Dialog.Close(all,true)')
    def start(self, delay=0):
        logger.log('==================== sliver_lxc.start {}'.format(self.name))
        if 'enabled' in self.rspec and self.rspec['enabled'] <= 0:
            logger.log('sliver_lxc: not starting {}, is not enabled'.format(self.name))
            return
        # the generic /etc/init.d/vinit script is permanently refreshed, and enabled
        self.install_and_enable_vinit()
        # expose .ssh for omf_friendly slivers
        if 'tags' in self.rspec and 'omf_control' in self.rspec['tags']:
            Account.mount_ssh_dir(self.name)
#        logger.log("NM is exiting for debug - just about to start {}".format(self.name))
#        exit(0)
        Sliver_Libvirt.start(self, delay)
Example #27
0
File: stra1.py Project: ul1234/st
class Test(object):
    def __init__(self):
        self.account = Account(10000)
        self.stocks = Stocks()
        self.stocks.load_from_file('stock_data.dat')

    def test_stra(self, stra):
        self.account.reset()
        for tick in self.stocks.iter_ticks():
            time_, oper = stra.first_oper(tick)
            oper = stra.second_oper(tick, self.account, time_, oper)
            oper = stra.third_oper(tick, self.account, time_, oper)
        return result
 def __load_accounts_from_config(self):
     for section in self.__config.sections():
         section_id = self.__next_id()
         url = self.__config.get(section, 'url')
         username = self.__config.get(section, 'username')
         try:
             password = self.__config.get(section, 'password')
             if password == '': password = None
         except NoOptionError:
             password = None
         new_account = Account(url, username, password)
         new_account.set_section_id(section_id)
         self.__set_section_id_and_load_account(new_account)
Example #29
0
 def setAccount(self, accountNumber=None, meterNumber=None):
     index = None
     for i, val in enumerate(self.account):
         if val.getAccount() == str(accountNumber):
             index = i
     
     if index == None:
         newAccount = Account(str(accountNumber))
         newAccount.setMeter(meterNumber)
         self.account.append(newAccount)
     else:
         print "Existing Account: ", self.account[index]
         self.account[index].setMeter(meterNumber)
    def configure(self, rec):

        #sliver.[LXC/QEMU] tolower case
        #sliver_type = rec['type'].split('.')[1].lower() 

        #BASE_DIR = '/cgroup/libvirt/{}/{}/'.format(sliver_type, self.name)

        # Disk allocation
        # No way through cgroups... figure out how to do that with user/dir quotas.
        # There is no way to do quota per directory. Chown-ing would create
        # problems as username namespaces are not yet implemented (and thus, host
        # and containers share the same name ids

        # Btrfs support quota per volumes

        if "rspec" in rec and "tags" in rec["rspec"]:
            if cgroups.get_cgroup_path(self.name) == None:
                # If configure is called before start, then the cgroups won't exist
                # yet. NM will eventually re-run configure on the next iteration.
                # TODO: Add a post-start configure, and move this stuff there
                logger.log("Configure: postponing tag check on {} as cgroups are not yet populated"
                           .format(self.name))
            else:
                tags = rec["rspec"]["tags"]
                # It will depend on the FS selection
                if 'disk_max' in tags:
                    disk_max = tags['disk_max']
                    if disk_max == 0:
                        # unlimited
                        pass
                    else:
                        # limit to certain number
                        pass

                # Memory allocation
                if 'memlock_hard' in tags:
                    mem = str(int(tags['memlock_hard']) * 1024) # hard limit in bytes
                    cgroups.write(self.name, 'memory.limit_in_bytes', mem, subsystem="memory")
                if 'memlock_soft' in tags:
                    mem = str(int(tags['memlock_soft']) * 1024) # soft limit in bytes
                    cgroups.write(self.name, 'memory.soft_limit_in_bytes', mem, subsystem="memory")

                # CPU allocation
                # Only cpu_shares until figure out how to provide limits and guarantees
                # (RT_SCHED?)
                if 'cpu_share' in tags:
                    cpu_share = tags['cpu_share']
                    cgroups.write(self.name, 'cpu.shares', cpu_share)

        # Call the upper configure method (ssh keys...)
        Account.configure(self, rec)
Example #31
0
 def __enter__(self) -> Account:
     return Account(service.next_acc_id(), self.name, self.balance)
Example #32
0
from car import Car
from account import Account

if __name__ == "__main__":
    car = Car("AMS545", Account("Andres Herrera", "ASN545"))
    print(vars(car))

    car2 = Car("AM8945", Account("Andrea Herrera", "ASA545"))
    print(vars(car2))    
Example #33
0
 def sub_acc_bal(self, account: Account, amount: float):
     account.sub_balance(amount)
     return self
Example #34
0
def add_to_watchlist(api_key, firstname, lastname):
    account = Account.api_authenticate(api_key)
    name = firstname + " " + lastname
    account.add_to_watchlist(name)
    return jsonify({"added": name})
Example #35
0
def get_api_key():
    data = request.get_json()
    account = Account.login(username=data['username'],
                            password=data['password'])
    return jsonify({"api_key": account.api_key})
Example #36
0
import pytest

from account import Account

checking = Account('Checking')
saving = Account('Saving', 10)


def test_account_balance():
    assert checking.start_balance == 0
    checking + 10
    assert checking.balance == 10

    assert saving.start_balance == 10
    with pytest.raises(ValueError):
        saving - 'a'
    saving - 5
    assert saving.balance == 5


def test_account_comparison():
    assert checking > saving
    assert checking >= saving
    assert saving < checking
    assert saving <= checking
    saving + 5


def test_account_len():
    checking + 10
    checking + 3
Example #37
0
from car import Car
from account import Account

if __name__ == "__main__":
    print("hola mundo")
    
    car = Car("AMW123", Account("Christian Fernandez", "C-653"))
    print(vars(car))
    print(vars(car.driver))

    car2 = Car("DRT345", Account("Marcos Lopez", "C-534"))
    print(vars(car2))
    print(vars(car2.driver))
from account import Account
from userdefined_exceptions import AmountTooSmallException
from userdefined_exceptions import InsufficientBalanceException
a1 = Account("mike", 12345, 200)

balance = a1.checkBalance()
print("Balance in {}'s account is {}".format(a1.holder, balance))

success, balance = a1.deposit(1000)

print("Deposit status: {}".format(success))
print("Balance after deposit is {}".format(balance))

#success, balance = a1.deposit(10)

try:
    success, balance = a1.deposit(10)
except AmountTooSmallException as e:
    # print("give an amount greater than 50")
    print(e.message)

a1.withDraw(300)

try:
    a1.withDraw(2000000)
except InsufficientBalanceException as i:
    print(i.message)
    print("you tried to withdrew an amount of {}".format(i.amount))
Example #39
0
from car import Car
from account import Account

if __name__ == "__main__":
    print("Hello world!!")
    car = Car("TEH23", Account("Pepito Perez", "UY3T4"))

    print(vars(car))
    print(vars(car.driver))
Example #40
0
from car import Car
from account import Account

if __name__ == "__main__":
    print("Hello world")

    car = Car("GFK253", Account("Dilan Ariza", "10001333805"))
    print(vars(car))
    print(vars(car.driver))
Example #41
0
from car import Car
from account import Account

if __name__ == "__main__":
    print("Hola Mundo")
    car = Car("AMS234", Account("Andrés Herrera", "AND876"))
    print(vars(car))
    print(vars(car.driver))
Example #42
0
        # if-else condition set for trendline color
        if lst_regr_data[0] > lst_regr_data[1]:
            a.plot(lst_regr_days,
                   lst_regr_data,
                   ls="--",
                   lw=0.75,
                   color=DEC_COLOR)
        else:
            a.plot(lst_regr_days,
                   lst_regr_data,
                   ls="--",
                   lw=0.75,
                   color=INC_COLOR)

        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().place(x=0, y=0)


''' Main Loop '''
if __name__ == '__main__':
    # instantiate core class objects
    data = Data()
    acct = Account()
    analysis = Analysis()
    app = Gui()

    app.geometry(str(WIN_LENGTH) + "x" + str(WIN_WIDTH))
    app.mainloop()
Example #43
0
                Write a test program that creates an Account object with an 
                account id of 1122, a balance of $20,000, and an annual interest 
                rate of 4.5%. Use the withdraw method to withdraw $2,500, use 
                the deposit method to deposit $3,000, and print the id, balance, 
                monthly interest rate, and monthly interest.

"""
from account import Account

if __name__ == "__main__":
    # create dictionay to hold the test account parameters
    account_dict = {
        "account_id": 1122,
        "balance": 20000,
        "int_rate": 0.045,
        "withdrawal_amount": 2500,
        "deposit_amount": 3000
    }

    account = Account(account_dict["account_id"], account_dict["balance"],
                      account_dict["int_rate"])
    account.withdraw(account_dict["withdrawal_amount"])
    account.deposit(account_dict["deposit_amount"])

    print("The id is: {}".format(account.getId()))
    print("The balance is: ${:0,.2f}".format(account.getBalance()))
    print("The monthly interest rate is: {} %".format(
        account.getMonthlyInterestRate() * 100))
    print("The monthly interest is: ${:0,.2f}".format(
        account.getMonthlyInterest()))
Example #44
0
 def testWithSufficientFunds(self):
     account = Account(10)
     amount = account.debit(4)
     self.assertEqual(amount, 4)
Example #45
0
 def author(self):
     return Account._byID(self.author_id, True)
Example #46
0
    def vote(cls, sub, obj, dir, ip, spam=False, organic=False):
        from admintools import valid_user, valid_thing, update_score
        from r2.lib.count import incr_counts

        # An account can only perform 1 voting operation at a time.
        with g.make_lock('account_%s_voting' % sub._id) as lock:
            kind = obj.__class__.__name__.lower()

            lock.log('voting checkpoint A')

            # If downvoting ensure that the user has enough karma, it
            # will raise an exception if not.
            if dir == False:
                sub.check_downvote(kind)

            lock.log('voting checkpoint B')

            # Do the voting.
            sr = obj.subreddit_slow
            karma = sub.karma(kind, sr)

            lock.log('voting checkpoint C')

            #check for old vote
            rel = cls.rel(sub, obj)
            oldvote = list(
                rel._query(rel.c._thing1_id == sub._id,
                           rel.c._thing2_id == obj._id,
                           data=True))

            amount = 1 if dir is True else 0 if dir is None else -1
            # Users have a vote_multiplier which effects how much their votes are worth
            if isinstance(sub, Account):
                amount *= sub.vote_multiplier

            lock.log('voting checkpoint D')

            is_new = False
            #old vote
            if len(oldvote):
                v = oldvote[0]
                oldamount = int(v._name)
                v._name = str(amount)

                #these still need to be recalculated
                old_valid_thing = getattr(v, 'valid_thing', True)
                v.valid_thing = (valid_thing(v, karma) and v.valid_thing
                                 and not spam)
                v.valid_user = (v.valid_user and v.valid_thing
                                and valid_user(v, sr, karma))
            #new vote
            else:
                is_new = True
                oldamount = 0
                v = rel(sub, obj, str(amount))
                v.author_id = obj.author_id
                v.ip = ip
                old_valid_thing = v.valid_thing = (valid_thing(v, karma)
                                                   and not spam)
                v.valid_user = v.valid_thing and valid_user(v, sr, karma)
                if organic:
                    v.organic = organic

            lock.log('voting checkpoint E')
            v._commit()
            lock.log('voting checkpoint F')

            # Record that this account has made a downvote.
            up_change, down_change = score_changes(amount, oldamount)
            if down_change:
                sub.incr_downvote(down_change, kind)

            lock.log('voting checkpoint G')

        # Release the lock since both the downvote count and the vote count
        # have been updated, and then continue by updating karmas.
        update_score(obj, up_change, down_change, v.valid_thing,
                     old_valid_thing)

        if v.valid_user:
            author = Account._byID(obj.author_id, data=True)
            author.incr_karma(kind, sr, up_change, down_change)

        #update the sr's valid vote count
        if is_new and v.valid_thing and kind == 'link':
            if sub._id != obj.author_id:
                incr_counts([sr])

        return v
Example #47
0
def draft_player(api_key, firstname, lastname):
    account = Account.api_authenticate(api_key)
    name = firstname + " " + lastname
    account.draft_player(name)
    return jsonify({"added": name})
Example #48
0
from car import Car
from account import Account
from uberX import UberX
from user import User

if __name__ == "__main__":
    print("Inicializando las info de los carros")
    print("Car")
    car = Car(
        "AMS256",
        Account("Andres Herrera", "ASD12365", "*****@*****.**", "2563"))
    print(vars(car))
    print(vars(car.driver))

    print("UberX")
    uberX = UberX(
        "KLO365", Account("Marco Lois", "SGHJ1236", "*****@*****.**",
                          "7856"), "Toyota", "Corolla")
    print(vars(uberX))
    print(vars(uberX.driver))

    print("User")
    user = User("mariana Valle", "SDFG125F", "*****@*****.**", "7856")
    print(vars(user))
Example #49
0
def remove_from_watchlist(api_key, firstname, lastname):
    account = Account.api_authenticate(api_key)
    name = firstname + " " + lastname
    account.remove_from_watchlist(name)
    return jsonify({"removed": name})
    def fetch_accounts(self, username):
        query = f'SELECT * FROM accounts WHERE Username = "******";'
        res = self.database_connector.execute_query(query)
        accounts = [Account(acc) for acc in res]

        return accounts
Example #51
0
    def vote(cls, sub, obj, dir, ip, organic=False, cheater=False, timer=None):
        from admintools import valid_user, valid_thing, update_score
        from r2.lib.count import incr_sr_count
        from r2.lib.db import queries

        if timer is None:
            timer = SimpleSillyStub()

        sr = obj.subreddit_slow
        kind = obj.__class__.__name__.lower()
        karma = sub.karma(kind, sr)

        is_self_link = (kind == 'link' and getattr(obj, 'is_self', False))

        #check for old vote
        rel = cls.rel(sub, obj)
        oldvote = rel._fast_query(sub, obj, ['-1', '0', '1']).values()
        oldvote = filter(None, oldvote)

        timer.intermediate("pg_read_vote")

        amount = 1 if dir is True else 0 if dir is None else -1

        is_new = False
        #old vote
        if len(oldvote):
            v = oldvote[0]
            oldamount = int(v._name)
            v._name = str(amount)

            #these still need to be recalculated
            old_valid_thing = getattr(v, 'valid_thing', False)
            v.valid_thing = (valid_thing(v, karma, cheater=cheater)
                             and getattr(v, 'valid_thing', False))
            v.valid_user = (getattr(v, 'valid_user', False) and v.valid_thing
                            and valid_user(v, sr, karma))
        #new vote
        else:
            is_new = True
            oldamount = 0
            v = rel(sub, obj, str(amount))
            v.ip = ip
            old_valid_thing = v.valid_thing = valid_thing(v,
                                                          karma,
                                                          cheater=cheater)
            v.valid_user = (v.valid_thing and valid_user(v, sr, karma)
                            and not is_self_link)
            if organic:
                v.organic = organic

        v._commit()

        timer.intermediate("pg_write_vote")

        up_change, down_change = score_changes(amount, oldamount)

        if not (is_new and obj.author_id == sub._id and amount == 1):
            # we don't do this if it's the author's initial automatic
            # vote, because we checked it in with _ups == 1
            update_score(obj, up_change, down_change, v, old_valid_thing)
            timer.intermediate("pg_update_score")

        if v.valid_user:
            author = Account._byID(obj.author_id, data=True)
            author.incr_karma(kind, sr, up_change - down_change)
            timer.intermediate("pg_incr_karma")

        #update the sr's valid vote count
        if is_new and v.valid_thing and kind == 'link':
            if sub._id != obj.author_id:
                incr_sr_count(sr)
            timer.intermediate("incr_sr_counts")

        # now write it out to Cassandra. We'll write it out to both
        # this way for a while
        CassandraVote._copy_from(v)
        VotesByAccount.copy_from(v)
        timer.intermediate("cassavotes")

        queries.changed(v._thing2, True)
        timer.intermediate("changed")

        return v
Example #52
0
def main():
    acc = Account('Vipin', 200)
    acc += 400
    acc -= 100
    print(acc)
Example #53
0
    amount = 0
    time = ""
    violations = list()

    for line in fileinput.input():
        logger.debug(line)
        json_data = json.loads(line)

        oper = list(json_data.keys())[0]

        if oper == "account":
            if account is None:
                # Create a new account
                active_card = json_data[oper]["active-card"]
                available_limit = json_data[oper]["available-limit"]
                account = Account(available_limit, active_card)
            else:
                violations.append("account-already-initialized")

        elif oper == "transaction":
            if account is None:
                violations.append("account-not-initialized")
            elif active_card is False:
                violations.append("card-not-active")
            else:
                merchant = json_data[oper]["merchant"]
                amount = json_data[oper]["amount"]
                time = json_data[oper]["time"]

        # Perform transcation
        if oper == "transaction" and len(violations) == 0:
Example #54
0
 def setUp(self) -> None:
     self.account = Account(name="Adrian",
                            account_number="1234567890",
                            surname="Woda",
                            account_balance=20000.00)
Example #55
0
 def add_acc_bal(self, account: Account, amount: float):
     account.add_balance(amount)
     return self
Example #56
0
class MyTestCase(unittest.TestCase):
    def setUp(self) -> None:
        self.account = Account(name="Adrian",
                               account_number="1234567890",
                               surname="Woda",
                               account_balance=20000.00)
        # self.account = Mock()
        # self.account.owner = Mock(return_value="Adrian Woda")

    def test_env_variable(self):
        self.assertEqual(os.environ['zmienna'], "123")

    def test_something(self):
        self.assertEqual(self.account(), "1234567890")

    def test_should_return_proper_owner_name(self):
        self.assertEqual(self.account.owner(), "Adrian Woda")

    def test_should_return_account_balance(self):
        self.assertEqual(self.account.balance(), 20000.00)

    def test_should_return_account_number(self):
        self.assertEqual(self.account.number(), "1234567890")

    def test_should_properly_transfer_money(self):
        self.account.transfer(-150)
        self.assertEqual(self.account.balance(), 19850)

    def test_should_properly_transfer_money2(self):
        self.account.transfer(1000)
        self.assertEqual(self.account.balance(), 21000)

    def test_should_card_return_owner_name(self):
        card = Card(self.account, "0000")

        self.assertEqual(card(), "Adrian Woda")

    def test_should_check_pin(self):
        card = Card(self.account, "0000")

        self.assertTrue(card.check_pin("0000"))
        self.assertFalse(card.check_pin("2345"))

    def test_should_card_return_proper_account(self):
        card = Card(self.account, "0000")

        self.assertEqual(card.get_account(), self.account)

    def test_should_withdraw_money_from_account(self):
        # 1. chce sprawdzic, czy po wyplacie, moj balance zmniejszyl się
        self.account.withdraw(500)
        self.assertEqual(self.account.balance(), 19500)

    def test_should_withdraw_money_from_account2(self):
        # 2. chce sprawdzic, czy moge wyciagnac wiecej niz mam
        self.account.withdraw(25000)
        self.assertEqual(self.account.balance(), 20000)

    def test_should_withdraw_money_from_account3(self):
        # 3. chce sprawdzic, czy moge wyciagnac wszystko
        self.account.withdraw(20000)
        self.assertEqual(self.account.balance(), 0)

    def test_should_send_money_to_another_account(self):
        account2 = Account(name="John",
                           surname="Doe",
                           account_number="0987654321",
                           account_balance=20000.00)
        self.account.sendMoney(account2, 10)
        self.assertEqual(self.account.balance(), 20000 - 10)
        self.assertEqual(account2.balance(), 20000 + 10)

    def test_should_send_money_to_another_account2(self):
        account2 = Account(name="John",
                           surname="Doe",
                           account_number="0987654321",
                           account_balance=20000.00)
        self.account.sendMoney(account2, 21000)
        self.assertEqual(self.account.balance(), 20000)
        self.assertEqual(account2.balance(), 20000)

    def test_should_not_be_able_to_send_negative_amount_of_money(self):
        account2 = Account(name="John",
                           surname="Doe",
                           account_number="0987654321",
                           account_balance=20000.00)
        self.account.sendMoney(account2, -1000)
        self.assertEqual(self.account.balance(), 20000,
                         "account1 balance mismatch")
        self.assertEqual(account2.balance(), 20000,
                         "account2 balance mismatch")

    def test_should_cart_be_blocked_after_3_incorret_attempts(self):
        cart = Card(account=self.account, pin="1234")
        cart.check_pin("0000")
        cart.check_pin("0000")
        cart.check_pin("0000")

        with self.assertRaises(CardLockedException):
            cart.check_pin("1234")

    def test_should_cart_not_be_blocked_after_2_incorrect_attempts(self):
        cart = Card(account=self.account, pin="1234")
        cart.check_pin("0000")
        cart.check_pin("0000")

        self.assertTrue(cart.check_pin("1234"))

    def test_x(self):
        cart = Card(account=self.account, pin="1234")
        cart.check_pin("0000")
        cart.check_pin("0000")
        cart.check_pin("1234")
        cart.check_pin("0000")

        self.assertTrue(cart.check_pin("1234"))

    def test_warinings(self):
        warnings.warn("You really want to assert warnings?!", RuntimeWarning)
        with self.assertWarnsRegex(RuntimeWarning, "warning") as warning:
            warnings.warn("another warning", RuntimeWarning)
Example #57
0
 def __init__(self):
     """Store the accounts the user has added(Twitter by default)."""
     self.accounts = {"twitter": Account(), "facebook": Account()}
Example #58
0
"""Use the indexer to search for transactions on chain."""

__author__ = "Adriano Di Luzio <*****@*****.**>"


import json
import base64
import msgpack

from config import account_mnemonic
from connect import indexer_client
from account import Account


def search(sender):
    response = indexer_client.search_transactions_by_address(address=sender.address)

    print(json.dumps(response, indent=2, sort_keys=True))

    txns = response["transactions"]
    last_txn = txns[0]  # Txs are sorted from most to least recent.
    note = last_txn["note"]

    print()
    print(f"✍️  Most recent note:\n{msgpack.unpackb(base64.b64decode(note))}")


if __name__ == "__main__":
    sender = Account.from_mnemonic(account_mnemonic)
    search(sender)
Example #59
0
    def vote(cls, sub, obj, dir, ip, organic=False, cheater=False):
        from admintools import valid_user, valid_thing, update_score
        from r2.lib.count import incr_sr_count
        from r2.lib.db import queries

        sr = obj.subreddit_slow
        kind = obj.__class__.__name__.lower()
        karma = sub.karma(kind, sr)

        is_self_link = (kind == 'link' and getattr(obj, 'is_self', False))

        #check for old vote
        rel = cls.rel(sub, obj)
        oldvote = rel._fast_query(sub, obj, ['-1', '0', '1']).values()
        oldvote = filter(None, oldvote)

        amount = 1 if dir is True else 0 if dir is None else -1

        is_new = False
        #old vote
        if len(oldvote):
            v = oldvote[0]
            oldamount = int(v._name)
            v._name = str(amount)

            #these still need to be recalculated
            old_valid_thing = getattr(v, 'valid_thing', False)
            v.valid_thing = (valid_thing(v, karma, cheater=cheater)
                             and getattr(v, 'valid_thing', False))
            v.valid_user = (v.valid_user and v.valid_thing
                            and valid_user(v, sr, karma))
        #new vote
        else:
            is_new = True
            oldamount = 0
            v = rel(sub, obj, str(amount))
            v.ip = ip
            old_valid_thing = v.valid_thing = valid_thing(v,
                                                          karma,
                                                          cheater=cheater)
            v.valid_user = (v.valid_thing and valid_user(v, sr, karma)
                            and not is_self_link)
            if organic:
                v.organic = organic

        v._commit()

        v._fast_query_timestamp_touch(sub)

        up_change, down_change = score_changes(amount, oldamount)

        if not (is_new and obj.author_id == sub._id and amount == 1):
            # we don't do this if it's the author's initial automatic
            # vote, because we checked it in with _ups == 1
            update_score(obj, up_change, down_change, v.valid_thing,
                         old_valid_thing)

        if v.valid_user:
            author = Account._byID(obj.author_id, data=True)
            author.incr_karma(kind, sr, up_change - down_change)

        #update the sr's valid vote count
        if is_new and v.valid_thing and kind == 'link':
            if sub._id != obj.author_id:
                incr_sr_count(sr)

        # now write it out to Cassandra. We'll write it out to both
        # this way for a while
        voter = v._thing1
        votee = v._thing2
        cvc = CassandraVote._rel(Account, votee.__class__)
        try:
            cv = cvc._fast_query(voter._id36, votee._id36)
        except tdb_cassandra.NotFound:
            cv = cvc(thing1_id=voter._id36, thing2_id=votee._id36)
        cv.name = v._name
        cv.valid_user, cv.valid_thing = v.valid_user, v.valid_thing
        cv.ip = v.ip
        if getattr(v, 'organic', False) or hasattr(cv, 'organic'):
            cv.organic = getattr(v, 'organic', False)
        cv._commit()

        queries.changed(votee, True)

        return v
 def __init__(self, holder, accnumber, sbal, overdraft_limit):
     Account.__init__(self, holder, accnumber, sbal)
     self.overdraft_limit = overdraft_limit