Exemplo n.º 1
0
 def __init__(self, btcTrader, apiName, authId, authPass):
     Engine.__init__(self, apiName, btcTrader, 1) # refresh rate of 1 second. In the futur with the websockets we will probably put 0 and use some kind of select
     self.req = self.CreateRequester(authId, authPass)
     self.depth = {}
     self.clock = Clock()
     self.first = 1
     self.account = Account()
Exemplo n.º 2
0
    def test_create_address(self):
        con = Connection("http://127.0.0.1:9888")
        account = Account.find_by_alias(con, "zhangsan")

        response = Account.create_address(con, "zhangsan", account.id)
        print(response)
        print(response['address'])
Exemplo n.º 3
0
def run():
    logging.basicConfig(filename='log.txt',
                        filemode='a',
                        format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                        datefmt='%d-%b-%y %H:%M:%S',
                        level=logging.DEBUG)
    logging.info('Initiating Run')
    auth_client = Account()
    history = History('BTC-USD')
    sma50 = history.sma(50)
    sma100 = history.sma(100)
    if sma50 > sma100:
        bull_flag = True
    else:
        bull_flag = False
    while True:
        if datetime.now().minute == 0:
            history = History('BTC-USD')
            if bull_flag is False and history.sma(50) > history.sma(100):
                buy = auth_client.buy('BTC-USD')
                logging.info(f'Golden Cross: {buy}')
                bull_flag = True
            if bull_flag is True and history.sma(50) < history.sma(100):
                sell = auth_client.sell('BTC-USD')
                logging.info(f'Death Cross: {sell}')
                bull_flag = False
            else:
                logging.info('No Crossover event')
            time.sleep((60 * 60) - datetime.now().minute * 60 - (datetime.now().microsecond / 1000000))
        else:
            time.sleep((60 * 60) - datetime.now().minute * 60 - (datetime.now().microsecond / 1000000))
Exemplo n.º 4
0
    def selectAccount(self):

        flag = 0

        with open('accounts.txt') as f:
            lines = f.readlines()

        for line in lines:
            data = line.split(" // ")
            a = Account(str(data[0]), str(data[1]))

            if len(self.accounts) == 0:
                self.accounts.append(a)
                print("Account selected: " + data[0])
                flag = 1
                break
            else:
                flagC = 0
                for account in self.accounts:
                    if a.username == account.username:
                        flagC = 1

                if flagC == 0:
                    self.accounts.append(a)
                    print("Account selected: " + data[0])
                    flag = 1
                    break

        if flag == 1:
            return a
        else:
            return Account("", "")
Exemplo n.º 5
0
def verifySign(line):
    """: ([a-f0-9]+) : ([a-f0-9]+) : ([a-f0-9]+) : ([0-9]{2}) : ([a-f0-9]+)$"""
    f = inspect.currentframe()
    rematch = f.f_back.f_globals[f.f_code.co_name].__doc__
    res = re.match(rematch, line)
    if not res:
        return False

    privateKeyHex = res.group(1)
    expectedPublic = unhexlify(res.group(2))
    expectedSignature = unhexlify(res.group(3))
    dataLength = int(res.group(4))
    data = unhexlify(res.group(5))
    assert (len(data) == dataLength)

    account = Account(privateKeyHex)
    if account.pk == expectedPublic:
        computedSignature = account.sign(data)
        if computedSignature == expectedSignature:
            return True
        else:
            print('Failed when calculating signature:')
            print('  computed signature:' + hexlify(computedSignature))
            print('  expected signature:' + hexlify(expectedSignature))
            return False

    else:
        print('Failed public from private:')
        print('  computed public:' + hexlify(account.pk))
        print('  expected public:' + hexlify(expectedPublic))
        return False
Exemplo n.º 6
0
    def mosaicClick(self):
        c = NemConnect(self.host.get(), int(self.port.get()))

        privkey = self.privKeyEntry.get()
        fqn = self.create_namespaceNameEntry.get(
        ) + '.' + self.create_mosaicNameEntry.get()
        desc = self.mosaicDescText.get("1.0", END)
        defaultProps = {
            'divisibility': int(self.m_d.get()),
            'initialSupply': int(self.m_is.get()),
            'supplyMutable': True if self.m_ms.get() else False,
            'transferable': True if self.m_t.get() else False
        }
        multisig = self.multisigPubKeyEntry.get() if self.multisigEnabled.get(
        ) else None

        if self.m_hasLevy.get():
            defaultProps['levy'] = {
                "type":
                int(self.m_levy_type.get()),
                "recipient":
                self.m_levy_recipient.get(),
                "mosaicFqn":
                self.m_levy_namespace.get() + '.' + self.m_levy_mosaic.get(),
                "fee":
                int(self.m_levy_fee.get())
            }
        try:
            a = Account(privkey)
            ok, j = c.prepareMosaicCreation(a.getHexPublicKey(), multisig, fqn,
                                            desc, defaultProps)
            self.commonHandle(c, a, ok, j)

        except Exception as e:
            self.report(str(e), traceback.format_exc())
Exemplo n.º 7
0
    def Start(self, InitialCapital, Logic, Lookback=1, Start=False, End=False):
        # Initialize account
        self.Account = Account(InitialCapital)

        # Adjust custom timeframe
        if not (Start): Start = self.Data['date'].iloc[0]
        if not (End): End = self.Data['date'].iloc[-1]
        self.Start, self.End = Start, End
        self.Timeframe = self.Data.loc[(self.Data['date'] >= Start)
                                       & (self.Data['date'] <= End)]

        # Enter backtest ---------------------------------------------

        for Index, Today in self.Timeframe.iterrows():
            Days = [self.Data.loc[Index]]
            for Day in range(Lookback):
                try:
                    Days.insert(1, self.Data.loc[Index - Day - 1])
                except KeyError:
                    pass

            try:
                Days.insert(1, self.Data.loc[Index + 1])
            except KeyError:
                pass

            # Update account variables
            self.Account.Date = Today['date']
            self.Account.Equity.append(self.Account.TotalValue(Today['open']))

            # Execute trading logic
            Logic(self.Account, Period(Days))

            # Cleanup empty positions
            self.Account.PurgePositions()
Exemplo n.º 8
0
    def transferClick(self):
        try:
            c = NemConnect(self.host.get(), int(self.port.get()))

            privkey = self.privKeyEntry.get()
            multisig = self.multisigPubKeyEntry.get(
            ) if self.multisigEnabled.get() else None
            recipient = self.transferRecipient.get()
            amount = int(self.transferAmount.get())
            message = self.transferMessage.get("1.0", END)
            mosaics = map(
                lambda x:
                (x['t'].get() + '.' + x['m'].get(), int(x['q'].get())),
                self.attachments)

            if len(self.attachments) > 0:
                amount *= 1000000

            a = Account(privkey)
            ok, j = c.prepareTransfer(a.getHexPublicKey(), multisig, recipient,
                                      amount, message, mosaics)
            self.commonHandle(c, a, ok, j)

        except Exception as e:
            self.report(str(e), traceback.format_exc())
Exemplo n.º 9
0
 def __init__(self):
     self.user = User()
     self.account = Account()
     self.employee = Employee()
     self.service = Service()
     self.utilities = Utilities()
     self.initAmt = 0
Exemplo n.º 10
0
    def pressedSettings(self, event):
        sender = self.sender()
        id = 0
        for bid, btn in self.buttonsMap.items():
            if btn == sender:
                id = bid

        try:
            current_account_id, current_account_login, current_account_password, current_account_status = \
                self.getRowInformation(id)
        except:
            sender.setStyleSheet("background-color: #FF0000")
            return

        sender.setStyleSheet("background-color: #E1E1E1")

        user = None
        if not id in users:
            user = Account(current_account_id, current_account_login,
                           current_account_password, current_account_status,
                           True, 0, 0, 0, 0)
            users[id] = user
        else:
            user = users[id]
            user.login = current_account_login
            user.password = current_account_password
        self.createSettingsForAccountWindow(user)
Exemplo n.º 11
0
    def mosaicClick(self):
        c = NemConnect(self.host.get(), int(self.port.get()))

        privkey = self.privKeyEntry.get()
        fqn = self.create_namespaceNameEntry.get(
        ) + '.' + self.create_mosaicNameEntry.get()
        desc = self.mosaicDescText.get("1.0", END)
        defaultProps = {
            'divisibility': int(self.m_d.get()),
            'initialSupply': int(self.m_is.get()),
            'supplyMutable': True if self.m_ms.get() else False,
            'transferable': True if self.m_t.get() else False
        }
        multisig = self.multisigPubKeyEntry.get() if self.multisigEnabled.get(
        ) else None

        if self.m_hasLevy.get():
            defaultProps['levy'] = {
                "type":
                int(self.m_levy_type.get()),
                "recipient":
                self.m_levy_recipient.get(),
                "mosaicFqn":
                self.m_levy_namespace.get() + '.' + self.m_levy_mosaic.get(),
                "fee":
                int(self.m_levy_fee.get())
            }
        try:
            a = Account(privkey)
            ok, j = c.prepareMosaicCreation(a.getHexPublicKey(), multisig, fqn,
                                            desc, defaultProps)
            self.commonHandle(c, a, ok, j)

        except Exception as e:
            self.report(str(e), traceback.format_exc())
Exemplo n.º 12
0
class Authorization(QtWidgets.QMainWindow):
    def enter(self):
        login = self.ui.loginEdit.text()
        password = self.ui.passworEdit.text()

        if get_password(login) is None:
            QMessageBox.question(self, 'Error', 'Error', QMessageBox.Ok,
                                 QMessageBox.Ok)
        elif get_password(login).lower() == password.lower():
            self.user_window = User(login)
            self.user_window.show()
        elif get_password(login).lower() == (password.lower() + '~1'):
            self.w3 = Administrator(login)
            self.w3.show()
        else:
            QMessageBox.question(self, 'Error', 'Error', QMessageBox.Ok,
                                 QMessageBox.Ok)

    def exit(self):
        self.close()

    def registration(self):
        self.w2 = Account()
        self.w2.show()

    def __init__(self):
        super(Authorization, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.enter.clicked.connect(self.enter)
        self.ui.exit.clicked.connect(self.exit)
        self.ui.reg.clicked.connect(self.registration)
Exemplo n.º 13
0
    def __init__(self, master):
        super().__init__(master)
        self.master = master

        self.user = User()
        self.account = Account()

        self.master.geometry("500x500")
        self.master.title("Most Secure banking")
        self.master.geometry("500x500")
        self.master.config(bg='orange')
        # pages
        self.entry_page = Frame(self.master)
        self.user_create_page = Frame(self.master)
        self.user_logged_page = Frame(self.master)
        self.user_login_page = Frame(self.master)

        self.user_deposit_page = Frame(self.master)
        self.user_withdraw_page = Frame(self.master)
        self.user_edit_page = Frame(self.master)
        self.user_delete_page = Frame(self.master)
        self.user_send_page = Frame(self.master)
        self.user_overview_page = Frame(self.master)

        self.UI_elements()
        self.create_entry_page()
        self.open_windows = []
Exemplo n.º 14
0
def exchange():
    if not session:
        return redirect(url_for('login'))
    acc = Account(private_key=session['data']['private_key'],
                  password=session['data']['password'])
    balance = acc.get_balance()
    return render_template('exchange.html', balance=balance)
Exemplo n.º 15
0
def verifySign(line):
    """: ([a-f0-9]+) : ([a-f0-9]+) : ([a-f0-9]+) : ([0-9]{2}) : ([a-f0-9]+)$"""
    f = inspect.currentframe()
    rematch = f.f_back.f_globals[f.f_code.co_name].__doc__
    res = re.match(rematch, line)
    if not res:
        return False

    privateKeyHex = res.group(1)
    expectedPublic = unhexlify(res.group(2))
    expectedSignature = unhexlify(res.group(3))
    dataLength = int(res.group(4))
    data = unhexlify(res.group(5))
    assert (len(data) == dataLength)

    account = Account(privateKeyHex)
    if account.pk == expectedPublic:
        computedSignature = account.sign(data)
        if computedSignature == expectedSignature:
            return True
        else:
            print('Failed when calculating signature:')
            print('  computed signature:' + hexlify(computedSignature))
            print('  expected signature:' + hexlify(expectedSignature))
            return False

    else:
        print('Failed public from private:')
        print('  computed public:' + hexlify(account.pk))
        print('  expected public:' + hexlify(expectedPublic))
        return False
Exemplo n.º 16
0
 def createAccount(self,accountNo,custName,balance):
     self.account=Account()
     self.account.setAccountNo(accountNo)
     self.account.setCustName(custName)
     self.account.setBalance(balance)
     self.accounts.update({accountNo:self.account})
     print "Account has been successfully created for account number",accountNo
Exemplo n.º 17
0
 def __init__(self, logger, perm_dict, start_all=True):
     self.accounts = []
     if start_all:
         for acc_index in perm_dict["accs"]:
             new_account = Account(perm_dict["accs"][acc_index], logger,
                                   perm_dict)
             new_account.start()
             self.accounts.append(new_account)
Exemplo n.º 18
0
def initial_accounts(scenario, outline):
    acc1 = Account('1', 0)
    acc2 = Account('2', 150)
    accounts_dict = {}
    accounts_dict[acc1.id] = acc1
    accounts_dict[acc2.id] = acc2
    world.accounts = accounts_dict
    world.deposit_to = accounts_dict
def main():
    account = Account(1122, 20000, 4.5)
    account.withdraw(2500)
    account.deposit(3000)
    print("account's id is", account.getId(), "balance is", 
    account.getBalance(), "monthly interest rate is", 
    format(account.getMonthlyInterestRate(), ".5f"), "monthly interest is", 
    format(account.getMonthlyInterest(), ".2f"))
Exemplo n.º 20
0
    def __init__(self, *args, **kwargs):

        # Hoster list
        self.hoster = []
        # Timestamp
        self.ts = 0

        Account.__init__(self, *args, **kwargs)
Exemplo n.º 21
0
 def __init__(self, name):
     """
     Constructor method that initialize customer attributes
     :param name: Takes Name of Customer to initialize Customer object
     """
     self.c_name = name
     self.c_id = -1
     self.account = Account()
Exemplo n.º 22
0
def initial_accounts(scenario,outline):
    acc1 = Account('1', 0)
    acc2 = Account('2', 150)
    accounts_dict = {}
    accounts_dict[acc1.id] = acc1
    accounts_dict[acc2.id] = acc2
    world.accounts=accounts_dict
    world.withdrawal_from = accounts_dict
 def __init__(self,init_balance=0,interest_rate=0.16):
     if(init_balance >=0) and (interest_rate >=0):
         Account.__init__(self,init_balance)
         self.interest_rate=interest_rate
         self.tipe= "Saving account"
     else:
         print("Error al crear la cuenta, verifica los valores indicados")
         return
Exemplo n.º 24
0
def main():
    a1 = Account(1122, 20000.0, 0.045)
    a1.withdraw(2500)
    a1.deposit(3000)
    print("ID:", format(a1.getId(), ".2f"))
    print("Balance:", a1.getBalance())
    print("Monthly interest rate:", format(a1.getMonthlyInterestRate(), ".3%"))
    print("Monthly interest:", format(a1.getMonthlyInterest(), ".2f"))
Exemplo n.º 25
0
    def __init__(self, *args, **kwargs):

        # Hoster list
        self.hoster = []
        # Timestamp
        self.ts = 0

        Account.__init__(self, *args, **kwargs)
Exemplo n.º 26
0
def main():
    cpte = Account("BNC", 500)
    print("Compte :", cpte.name)

    ope = Operation("29-12-2019", "DEP", "EPICERIE", -25)
    #ope.print_operation()
    cpte.add_operation(ope)
    bal = cpte.get_balance()
    print(bal)
Exemplo n.º 27
0
 def __init__(self, username, balanceid, f, l, amt):
     self.__account_init = Account(amt)
     self.__username = username
     self.__balanceid = balanceid
     self.__firstName = str(f)
     self.__lastName = str(l)
     self.__account = {username: {"BALANCE ID: ": self.__balanceid,
                                  "NAME: ": self.__firstName + " " + self.__lastName,
                                  "BALANCE:": self.__account_init.getBalance(balanceid)}}
Exemplo n.º 28
0
 def post(self):
     username = self.request.get('username')
     useremail = self.request.get('email')
     newUser = Account()
     newUser.username = username
     newUser.email = useremail
     #newUser.key = ndb.Key(Account, '')
     newUser.put()
     self.redirect('/admin')
Exemplo n.º 29
0
 def __init__(self, username, password):
     Account.__init__(self, username, password)
     self.__userID = self.generateUserID()
     self.__name = ""
     self.__email = ""
     self._rights = False
     self.__cart = []
     self.__points = 0
     self.__myRewards = []
Exemplo n.º 30
0
    def test_sell(self):
        ticker = "NEOUSDT"
        price = 100
        quantity = .5
        test_account = Account(balance=100)
        test_account.sell(price, quantity, ticker)

        result = test_account.position_exists("NEOUSDT")
        self.assertEqual(True, result)
Exemplo n.º 31
0
    def test_init(self):
        with self.assertRaises(TypeError):
            Account('100.0')

        with self.assertRaises(ValueError):
            Account(-100.0)

        account = Account()
        self.assertEqual(account.balance, 0.0)
Exemplo n.º 32
0
class AccountTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        super(cls)
        cls.account2 = Account("Piotr Nowak", 1500)

    def setUp(self):
        print("SetUp account")
        self.account = Account("Jan Kowalski", 1500)
        self.account.owner = MagicMock(return_value="Piotr Nowak")

    def test_constructor(self):
        self.assertEqual(self.account.balance, 1500)
        self.assertEqual(self.account.owner, "Jan Kowalski")

    def test_getOwner(self):
        self.assertEqual(self.account.owner.return_value, "Jan Kowalski")

    def test_getOwner2(self):
        with patch.object(Account, "getOwner") as acow:
            acow.return_value = "Kazimierz"

            self.assertEqual(self.account.owner, acow.return_value)

    def test_getBalance(self):
        balance = self.account.getBalance()

        self.assertEqual(balance, 1500)

    def test_transfer(self):
        new_balance = self.account.transfer(-500)
        # self.account2.transfer(-500)

        self.assertEqual(new_balance, 1000)

    def test_transfer_failure(self):
        new_balance = self.account.transfer(500)

        self.assertEqual(new_balance, 1500)

    def test_transfer_success(self):
        new_balance = self.account2.transfer(500)

        self.assertEqual(new_balance, 1500)

    def test_transferWithMock(self):
        self.account.balance = MagicMock(return_value=3000)

        self.assertEqual(self.account.balance.return_value, 1500)

    def test_transferWithPatch(self):
        with patch.object(Account, "getBalance") as newBalance:
            newBalance.return_value = 0
            addedBalance = self.account.transfer(500)

            self.assertEqual(addedBalance, 0)
Exemplo n.º 33
0
def getAccountObj(id):
    if Account.accountExist(id):
        account = Account(id)
        if account.type == 'CA':
            account = CAccount(id)
        elif account.type == 'SA':
            account = SAccount(id)
        return account
    else:
        return 0
Exemplo n.º 34
0
def accountDetails():
    outputWindow.show()
    account1 = Account(str(checkAccountBox.text()))
    opDict=account1.getAccountDetails()
    op=open('Account_Details.html').read()
    op=op.replace('idVal',opDict['AccountID'])
    op=op.replace('typeVal',opDict['Account Type'])
    op=op.replace('nameVal',opDict['Customer Name'])
    op=op.replace('balanceVal',opDict['Balance'])
    outputWindow.setHtml(op)
Exemplo n.º 35
0
 def GetAccount(self):
     # get account infos
     res = self.Perform("/generic/private/info", {}, 1)
     result = res["return"]
     a = Account()
     a.tradeFee = result["Trade_Fee"]
     a.wallets["BTC"] = result["Wallets"]["BTC"]["Balance"]["value"]
     a.wallets["EUR"] = result["Wallets"]["EUR"]["Balance"]["value"]
     # get btc address
     res = self.Perform("/generic/bitcoin/address", {}, 1)
     a.btcAddress = res["return"]["addr"];
     return a
Exemplo n.º 36
0
    def namespaceClick(self):
        c = NemConnect(self.host.get(), int(self.port.get()))

        privkey = self.privKeyEntry.get()
        fqn = self.namespaceNameEntry.get()
        multisig = self.multisigPubKeyEntry.get() if self.multisigEnabled.get() else None
        try:
            a = Account(privkey)
            ok, j = c.prepareProvisionNamespace(a.getHexPublicKey(), multisig, fqn)
            self.commonHandle(c, a, ok, j)

        except Exception as e:
            self.report(str(e), traceback.format_exc())
Exemplo n.º 37
0
 def _init_account_from_gconf(self, path):
     """Setup an Account class with values from GConf."""
     email = self.gconf.get_value("{0}/email".format(path))
     account = Account(email)
     for pspec in account.props:
         if pspec.name == "password":
             auth_token = self.gconf.get_value("{0}/auth_token".format(path))
             account.props.password = self.keyring.get_password(auth_token)
         elif pspec.name != "email":
             setattr(account.props, pspec.name, self.gconf.get_value("{0}/{1}".format(path, pspec.name)))
     self._account_hid[account.props.email] = account.connect("notify", self._account_prop_changed)
     self._accounts.append(account)
     return account
 def GetAccount(self):
     #actually, there is no way yet to get informations from
     #the bitcoin-central API but it would be a call to "/me"
     #check the https://bitcoin-central.net/s/api-v1-documentation
     #it should change soon
     #now I only get the current balance
     res = self.Perform("account_operations", {}, 1)
     account = Account()
     account.tradeFee = 0.498
     for i in res:
         if not i['currency'] in account.wallets:
             account.wallets[i['currency']] = i['balance']
     return account
Exemplo n.º 39
0
    def mosaicSupplyClick(self):
        c = NemConnect(self.host.get(), int(self.port.get()))

        privkey = self.privKeyEntry.get()
        fqn = self.mosaicSupply_namespace.get() + '.' + self.mosaicSupply_mosaic.get()
        supplyDelta = int(self.ms_supplyChange.get())
        supplyMode = self.ms_mode.get()

        multisig = self.multisigPubKeyEntry.get() if self.multisigEnabled.get() else None
        try:
            a = Account(privkey)
            ok, j = c.prepareMosaicSupply(a.getHexPublicKey(), multisig, fqn, supplyMode, supplyDelta)
            self.commonHandle(c, a, ok, j)
        except Exception as e:
            self.report(str(e), traceback.format_exc())
Exemplo n.º 40
0
def insert_new_user(login,pw,shipName=""):
  """
    This used during the create new user process
    saves a new user to the database
    
    args:
      login: 
        unique email address supplied by the user
      pw: 
        password supplied by the user. 
      shipName: 
        The space ship name is supplied by the user. 
        Not required but lame if not there.
    returns:
      a tuple containing the primary key of the newly inserted user from the
      User table, the primary key of the account created for the new user,
      and the primary key of the hero created for the new user.
  """
  from Account import Account
  from Hero import Hero

  if is_login_taken(login):
    raise FileExistsError("That email is already taken")
  loginPk = safe_insert_new_user(login,pw)
  accountId = Account.create_new_account_in_db(loginPk)
  heroId = Hero.construct_new_hero_in_db(accountId,shipName)
  return (loginPk,accountId,heroId)
 def test_get_heroPk_by_accountPk(self):
   from Account import Account
   from Hero import Hero
   pk = dbHelp.create_login_using_test_values()
   accntPk = Account.create_new_account_in_db(pk)
   hPk = Hero.construct_new_hero_in_db(accntPk)
   rPk = auth.get_heroPk_by_accountPk(accntPk)
   self.assertEqual(hPk,rPk)
Exemplo n.º 42
0
    def transferClick(self):
        try:
            c = NemConnect(self.host.get(), int(self.port.get()))

            privkey = self.privKeyEntry.get()
            multisig = self.multisigPubKeyEntry.get() if self.multisigEnabled.get() else None
            recipient = self.transferRecipient.get()
            amount = int(self.transferAmount.get())
            message = self.transferMessage.get("1.0", END)
            mosaics = map(lambda x: (x['t'].get() + '.' + x['m'].get(), int(x['q'].get())), self.attachments)

            if len(self.attachments) > 0:
                amount *= 1000000

            a = Account(privkey)
            ok, j = c.prepareTransfer(a.getHexPublicKey(), multisig, recipient, amount, message, mosaics)
            self.commonHandle(c, a, ok, j)

        except Exception as e:
            self.report(str(e), traceback.format_exc())
Exemplo n.º 43
0
 def get(self):
     user = users.get_current_user()
     
     if user:
         if user.email() == '*****@*****.**':
             query = Account.query()
             result = query.fetch() 
             template_values = {
                 'accounts': result,
             }
             template = jinja_env.get_template('Admin.html')
             self.response.out.write(template.render(template_values))
         else:
             self.response.out.write('WARNING!!!')
     else:
         self.redirect(users.create_login_url(self.request.uri))
Exemplo n.º 44
0
def check_in_and_get_notices(heroPk,accountPk,checkinTimeUtc,utcOffset):
  """
    this should be called on page load and should be used to get any notices
    for the use

    args:
      heroPk:
        we want a  pymongo objectId for the hero table
      accountPk:
        we want a  pymongo objectId for the hero table
      checkinTimeUtc:
        this needs to be that the user check in and it needs to be utc
      utcOffset:
         the time-zone offset from UTC, in minutes, for the current locale.

    returns:
      we return a dict with two elements: 'story' which will be a list of 
      huge things of text and 'zoneChoice' which is a list of dicts each
      of which contain 'zonePk','description'
      but zoneChoice may be none.

  """
  from Hero import Hero
  from Account import Account
  hero = Hero.construct_model_from_pk(heroPk)
  account = Account.construct_model_from_pk(accountPk)

  lastCheckinTime = account.lastCheckInTime
  account.lastCheckInTime = checkinTimeUtc
  account.save_changes()

  if not lastCheckinTime:
    messages = build_first_time_checkin_messages(hero)
    
    hero.save_changes()
    return messages

  if hero.isInZoneLimbo:
    autoPickedZoneDict = random.choice(hero.zone.nextZoneReferenceList)
    hero.zone = Zone.construct_model_from_dict(autoPickedZoneDict)
    hero.monster = Monster.construct_new_monster(hero.zone.definitionKey,hero.zone.lvl)
    

  timeDiffInDays = (checkinTimeUtc - lastCheckinTime)/(60*60*24)
  if timeDiffInDays >= 1:
    pass
def create_test_account_using_default_values(loginPk=None):
  from Account import Account
  accountPk = Account.create_new_account_in_db(loginPk)
  return accountPk
 def test_get_accountPk_by_loginPk(self):
   from Account import Account
   pk = dbHelp.create_login_using_test_values()
   accntPk = Account.create_new_account_in_db(pk)
   rPk = auth.get_accountPk_by_loginPk(pk)
   self.assertEqual(accntPk,rPk)
Exemplo n.º 47
0
import csv
from Account import Account
from elasticsearch import Elasticsearch

es = Elasticsearch('192.168.2.90:9200/')

acs = []
count = 0
with open('data.csv', 'r') as datafile:
    datareader = csv.reader(datafile, delimiter=',')
    if datareader:
        for row in datareader:
            print(row)
            count += 1
            new = Account()
            new.fields['FirstName'] = row[0]
            new.fields['LastName'] = row[1]
            new.fields['NickName'] = row[2]
            new.FirstName = row[0]
            new.LastName = row[1]
            new.NickName = row[2]
            new.Street1 = row[3]
            new.Street2 = row[4]
            new.City = row[5]
            new.State = row[6]
            new.Postal = row[7]
            new.Country = row[8]
            new.CreateDate = row[9]
            new.ModifiedDate = row[10]
            acs.append(new)
    else:
Exemplo n.º 48
0
        print " [!] announce failed"
    prettyPrint(j)


c = NemConnect('127.0.0.1', 7890)

if args.sub == 'info':
    j = c.nodeInfo()
    print " [+] NODE INFO:"
    prettyPrint(j)
    sys.exit(0)

elif args.sub == 'harvest':
    msg = "UNLOCK" if args.unlock else "LOCK"
    privkey = args.unlock or args.lock
    a = Account(privkey)
    print " [+] TRYING TO %s USING ACCOUNT" % msg
    print "private: %s" % a.getHexPrivateKey()
    print " public: %s" % a.getHexPublicKey()
    if args.unlock:
        ok, j = c.accountUnlock(privkey)
    else:
        ok, j = c.accountLock(privkey)

    if ok:
        print " [+] SUCCESSFULLY %sED" % msg
    else:
        prettyPrint(j)
    sys.exit(0)

elif args.sub == 'transfer':
Exemplo n.º 49
0

def choice_repository():
    print 'Select repositories'
    arr = []
    bb  = bitbucket.BitBucket(g_usr,g_pwd)
    for repo in bb.user(g_usr).repositories():
        name = repo['name']
        arr.append(name)
        print '%d) %s' % (len(arr), name)

    idx = int_input('>>> ')
    if 0 < idx and idx <= len(arr):
        return arr[idx -1]
    return ''





account = Account('~/.bitbacketpw')
g_usr,g_pwd = account.get();


repo = choice_repository()
if '' != repo:
    type = choice_clone_type()
    if CLONE_TYPE_SSH == type or CLONE_TYPE_HTTPS == type:
        git_clone(make_repo_url(repo, type))

Exemplo n.º 50
0
print args

def prettyPrint(j):
	print json.dumps(j, indent=2)

c = NemConnect('127.0.0.1', 7890)

if args.sub == 'info':
	j = c.nodeInfo()
	print " [+] NODE INFO:"
	prettyPrint(j)

elif  args.sub == 'harvest':
	msg = "UNLOCK" if args.unlock else "LOCK"
	privkey = args.unlock or args.lock
	a = Account(privkey)
	print " [+] TRYING TO %s USING ACCOUNT" % msg
	print "private: %s" % a.getHexPrivateKey()
	print " public: %s" % a.getHexPublicKey()
	if args.unlock:
		ok,j = c.accountUnlock(privkey)
	else:
		ok,j = c.accountLock(privkey)

	if ok:
		print " [+] SUCCESSFULLY %sED" % msg
	else:
		prettyPrint(j)

elif args.sub == 'send':
	privkey = args.key
	else:
		print " [!] announce failed"
	prettyPrint(j)

c = NemConnect('62.75.171.41', 7890)

if args.sub == 'info':
	j = c.nodeInfo()
	print " [+] NODE INFO:"
	prettyPrint(j)
	sys.exit(0)

elif  args.sub == 'harvest':
	msg = "UNLOCK" if args.unlock else "LOCK"
	privkey = args.unlock or args.lock
	a = Account(privkey)
	print " [+] TRYING TO %s USING ACCOUNT" % msg
	print "private: %s" % a.getHexPrivateKey()
	print " public: %s" % a.getHexPublicKey()
	if args.unlock:
		ok,j = c.accountUnlock(privkey)
	else:
		ok,j = c.accountLock(privkey)

	if ok:
		print " [+] SUCCESSFULLY %sED" % msg
	else:
		prettyPrint(j)
	sys.exit(0)

elif args.sub == 'send':
Exemplo n.º 52
0
 def disable_popups(self):
   accountPk = cherrypy.session.get(BaseFields.ACCOUNT_PK_KEY)
   account = Account.construct_model_from_pk(accountPk)
   account.preventPopups = True
   account.save_changes()