Exemple #1
0
 def __init__(self):
     super().__init__()
     self.proxylist = []
     self.proxylist_obj = None
     self.proxylist_thread = None
     self.proxyModel = TableModel('Id', 'Country', 'Url', 'Response_time', 'Used', 'Error')
     self.sortProxyModel = SortFilterProxyModel(self.proxyModel)
     self.rootContext().setContextProperty('sortProxyModel', self.sortProxyModel)
Exemple #2
0
 def __init__(self, parent=None):
     super(FrozenTableView, self).__init__(parent)
     self.model = TableModel()
     self.setSelectionBehavior(QAbstractItemView.SelectRows)
     self.setSelectionMode(QAbstractItemView.SingleSelection)
     self.verticalHeader().setVisible(False)
     self.setSortingEnabled(True)
     self.setModel(self.model)
     self.is_updating = False
Exemple #3
0
class Log(Db):
    def __init__(self):
        self.logModel = TableModel('Time', 'Type', 'Message')
        self.rootContext().setContextProperty('logModel', self.logModel)

    def log(self, message, messageType='System', messageTime=None):
        if not messageTime:
            messageTime = datetime.now().strftime('%H:%M:%S')
        self.logModel.addRow([messageTime, messageType, message])
Exemple #4
0
 def __init__(self):
     super().__init__()
     self.items = []
     self.parse_obj = None
     self.parse_thread = None
     self.itemsModel = TableModel('Id', 'Dt', 'Name', 'Price', 'Author',
                                  'Address', 'Phone')
     self.sortItemsModel = SortFilterProxyModel(self.itemsModel)
     self.rootContext().setContextProperty('sortItemsModel',
                                           self.sortItemsModel)
Exemple #5
0
class FrozenTableView(QTableView):
    def __init__(self, parent=None):
        super(FrozenTableView, self).__init__(parent)
        self.model = TableModel()
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.verticalHeader().setVisible(False)
        self.setSortingEnabled(True)
        self.setModel(self.model)
        self.is_updating = False

    def clear(self):
        self.model.set_data([], [])

    def get_selected_row(self):
        if self.model.columnCount() == 0:
            return ()
        if self.model.rowCount() == 0:
            return tuple(None for _ in range(self.model.columnCount()))
        index = self.selectedIndexes()
        if not index:
            return tuple(None for _ in range(self.model.columnCount()))
        else:
            index = self.selectedIndexes()[0]
            return self.model.row(index)

    def set_data(self, headers, values):
        self.selectionModel().blockSignals(
            True)  #prevent selectionChanged signal when updating
        self.model.set_data(values, headers)
        self.selectRow(0)
        self.selectionModel().blockSignals(False)
 def setup_table(self):
     """
     Initializes the table for budget records.
     """
     self.records = TableModel(("Amount", "Category", "Type", "On day"))
     self.recordsView.setModel(self.records)
     self.selection = QItemSelectionModel(self.records)
     self.recordsView.setSelectionModel(self.selection)
Exemple #7
0
 def __init__(self):
     super().__init__()
     self.setWindowTitle("Single word translations")
     self.table = QTableView()
     self.table.verticalHeader().setDefaultSectionSize(50)
     self.table.horizontalHeader().setDefaultSectionSize(150)
     self.model = TableModel()
     self.table.setModel(self.model)
     self.setLayout(QVBoxLayout())
     self.layout().addWidget(self.table)
Exemple #8
0
class Parse(Proxylist):
    def __init__(self):
        super().__init__()
        self.items = []
        self.parse_obj = None
        self.parse_thread = None
        self.itemsModel = TableModel('Id', 'Dt', 'Name', 'Price', 'Author',
                                     'Address', 'Phone')
        self.sortItemsModel = SortFilterProxyModel(self.itemsModel)
        self.rootContext().setContextProperty('sortItemsModel',
                                              self.sortItemsModel)

    def parse(self):
        if self.parse_thread and self.parse_thread.isRunning():
            return
        self.log('Start parsing', 'Parse')
        self.itemsModel.clear()
        self.items = []
        self.parse_obj = ParseWorker(self.proxylist)
        self.parse_thread = QThread()
        self.parse_obj.moveToThread(self.parse_thread)
        self.parse_obj.message.connect(self.parse_on_message)
        self.parse_obj.finished.connect(self.parse_on_finished)
        self.parse_thread.started.connect(self.parse_obj.start)
        self.parse_thread.start()

    def parse_on_message(self, message):
        if message[0]:
            self.log(message[0], 'Parse')
        if message[1]:
            item = message[1]
            self.itemsModel.addRow([
                item['id'] + 1, item['dt'], item['name'], item['price'],
                item['author'], item['address'], item['phone']
            ])

    def parse_on_finished(self, message):
        self.parse_thread.quit()
        self.parse_thread.wait()
        self.items = message[0]
        self.proxylist = message[1]
        self.log('Parsing END')
Exemple #9
0
def test_table_array_shape_ndim(filename, tmp_path):
    file_path = tmp_path / filename
    with TableModel() as x:
        x.table = [(
            42,
            37.5,
            'STRING',
            [[37.5, 38.0], [39.0, 40.0], [41.0, 42.0]],
            [[37.5, 38.0], [39.0, 40.0], [41.0, 42.0]],
        )]
        assert x.table.dtype == [
            ('int16_column', '=i2'),
            ('float32_column', '=f4'),
            ('ascii_column', 'S64'),
            ('float32_column_with_shape', '=f4', (3, 2)),
            ('float32_column_with_ndim', '=f4', (3, 2)),
        ]

        x.save(file_path)

    with TableModel(file_path) as x:
        assert x.table.dtype == [
            ('int16_column', '=i2'),
            ('float32_column', '=f4'),
            ('ascii_column', 'S64'),
            ('float32_column_with_shape', '=f4', (3, 2)),
            ('float32_column_with_ndim', '=f4', (3, 2)),
        ]

    with TableModel() as x:
        with pytest.raises(ValueError):
            x.table = [(
                42,
                37.5,
                'STRING',
                # This element should fail because it's shape is (2, 2) and not (3, 2):
                [[37.5, 38.0], [39.0, 40.0]],
                [[37.5, 38.0], [39.0, 40.0], [41.0, 42.0]],
            )]
Exemple #10
0
    def display_table(self, tables):
        for tab, table in tables.items():
            view = getattr(self, "{}_table".format(tab))
            model = TableModel(table[1], table[0])
            model.data_changed.connect(self.update_data)

            view.setModel(model)
            view.setColumnHidden(0, True)

        self.ca_addr_list.clear()
        self.ca_addr_list.addItems(
            self.db.configs.find_one({
                "config": "EPICS_CA_ADDR_LIST"
            }).get("ips"))
    def __init__(self, orm):
        super().__init__()
        self.setupUi(self)

        self.orm = orm

        self.set_month_and_year()

        # Connect signals and slots
        self.yearBox.currentTextChanged.connect(
            lambda year: self.load_balance())
        self.monthBox.currentTextChanged.connect(
            lambda month: self.load_balance())

        self.roll = TableModel(("Date", "Change", "Total", "Origin", "Category"))
        self.balanceView.setModel(self.roll)

        # Show report for current month as initial
        self.load_balance()
    def __init__(self, orm):
        super().__init__()
        self.setupUi(self)

        self.orm = orm

        self.set_month_and_year()

        # Connect signals and slots
        self.yearBox.currentTextChanged.connect(
            lambda year: self.load_budget_bars())
        self.monthBox.currentTextChanged.connect(
            lambda month: self.load_budget_bars())

        # Show report for current month as initial
        self.load_budget_bars()

        # Prepare place for transactions list
        self.transactions = TableModel(("Date", "Amount", "Info", "Category"))
        self.transactionsView.setModel(self.transactions)
Exemple #13
0
def post():
    if request.args:
        return {"Message ":"Unsupported Action ; query parameters are not allowed"},403
    data = request.get_json()
    if data == None:
        return {'Message ': "Request body cannot be empty"}, 403
    elif not request.json :
        return {"Message ": "Unsupported format"}, 400
    else:
        #taking the current dat and time
        tstamp = datetime.datetime.now()
        #if authorized by is not given by the user, an message will be displayed
        if 'authorized_by' not in data[1]:
            return {"Message ": "Please provide the key 'authorized_by' and your mail id as its value"},500
        #storing authorized_by
        auth_by = data[1]['authorized_by'] 
        #checking if the person is authorized to make an entry from the Master table
        record_user_id = Master_entries.query.filter_by(user_name = auth_by).first()
        if record_user_id == None:
            return {"Message " : "You are not authorized to make an entry!! Please contact Sree Harsha Chintamani"},401
        master_user_dict = record_user_id.json2()
        int_userID = master_user_dict['int_user_id']
        active_status = master_user_dict['active']
        dict_userIDs = data[0]   
        for j in range(0,len(dict_userIDs['user_id'])): 
            if active_status == False:
                return {"Message " : "You are only authorized to read an entry!! Please contact Sree Harsha Chintamani"},401
            new_record = TableModel('phoenix_windxplore', dict_userIDs['user_id'][j],'1', tstamp,'accepted')
            new_record1 = Accepted_entries(int_userID,'insert', "phoenix_windxplore", dict_userIDs['user_id'][j],'1', tstamp,'accepted')
            db.session.add(new_record)
            try :
                db.session.commit()
            except :
                return {"Message ": "Could not update in the Database!"}, 500
            db.session.add(new_record1)
            try :
                db.session.commit()
            except :
                return {"Message ": "Could not update in the local Database!"},500
        return {"Message " : "New record(s) added successfully"}, 200
    def __init__(self, orm, account):
        super().__init__()
        self.setupUi(self)

        self.orm = orm
        self.account = account

        self.roll = TableModel(("Date", "Amount", "Info", "Category"))
        self.rollView.setModel(self.roll)
        self.selection = QItemSelectionModel(self.roll)
        self.rollView.setSelectionModel(self.selection)

        self.rollView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)

        self.addTransaction.clicked.connect(self.add_transaction)
        self.editTransaction.clicked.connect(self.edit_transaction)
        self.deleteTransaction.clicked.connect(self.delete_transaction)

        self.categories = self.orm.fetch_subcategories()

        self.show_transactions()
class BudgetReport(Ui_Dialog, QDialog):
    def __init__(self, orm):
        super().__init__()
        self.setupUi(self)

        self.orm = orm

        self.set_month_and_year()

        # Connect signals and slots
        self.yearBox.currentTextChanged.connect(
            lambda year: self.load_budget_bars())
        self.monthBox.currentTextChanged.connect(
            lambda month: self.load_budget_bars())

        # Show report for current month as initial
        self.load_budget_bars()

        # Prepare place for transactions list
        self.transactions = TableModel(("Date", "Amount", "Info", "Category"))
        self.transactionsView.setModel(self.transactions)

    def set_month_and_year(self):
        """
        Sets initial values for year and month boxes.
        """
        self.yearBox.addItems(YEARS)
        self.monthBox.addItems(MONTHS)
        current_date = QDate.currentDate()
        self.yearBox.setCurrentText(str(current_date.year()))
        self.monthBox.setCurrentText(MONTHS[current_date.month()])

    def load_budget_bars(self):
        """
        Loads the budget report from DB for chosen month and year and puts
        it into GUI.
        """
        self.clear_bars()

        year = int(self.yearBox.currentText())
        month = int(self.monthBox.currentIndex())  # by position

        for budget_bar in self.orm.fetch_budget_report_bars(month, year):
            self.add_bar(budget_bar)

        self.barsLayout.setColumnStretch(1, 1)

    def clear_bars(self):
        """
        Clears the widget for budget report.
        """
        for i in reversed(range(self.barsLayout.count())):
            widget = self.barsLayout.itemAt(i).widget()
            # Detach from layout
            self.barsLayout.removeWidget(widget)
            # Remove from GUI
            widget.setParent(None)

    def add_bar(self, budget_bar):
        """
        Adds single bar to the budget report at selected position
        """
        category = budget_bar.category
        category_text = category.parent + '::' + category.name
        position = self.barsLayout.rowCount() + 1
        self.barsLayout.addWidget(QLabel(category_text), position, 0)
        bar = QBar(budget_bar)
        bar.mousePressed.connect(self.show_transactions)
        self.barsLayout.addWidget(bar, position, 1)

    def show_transactions(self, q_bar):
        """
        Show list of transactions for selected budget category.
        """
        self.transactions.prepare()

        year = int(self.yearBox.currentText())
        month = int(self.monthBox.currentIndex())  # by position
        category = q_bar.model.category

        for transaction in self.orm.fetch_transactions_for_month(month, year,
                                                                 category):
            self.transactions.addRow(transaction)
Exemple #16
0
class Proxylist(Log):
    def __init__(self):
        super().__init__()
        self.proxylist = []
        self.proxylist_obj = None
        self.proxylist_thread = None
        self.proxyModel = TableModel('Id', 'Country', 'Url', 'Response_time', 'Used', 'Error')
        self.sortProxyModel = SortFilterProxyModel(self.proxyModel)
        self.rootContext().setContextProperty('sortProxyModel', self.sortProxyModel)

    async def proxylist_init(self):
        cursor = await self.db.execute('SELECT * FROM proxy')
        proxylist = await cursor.fetchall()
        if proxylist:
            for p in proxylist:
                self.proxylist.append({'id': p[0], 'added': p[1], 'country': p[2], 'host': p[3], 'port': p[4], 'url': p[5], 'response_time': p[6], 'used': p[7], 'error': p[8]})
                self.proxyModel.addRow([p[0], p[2], p[5], f'{p[6]:.2f}', p[7], p[8]])
            self.log(f'Load {len(self.proxylist)} proxy', 'Proxylist')

    async def proxylist_close(self):
        if self.proxylist:
            await self.db.executemany('UPDATE proxy SET used=?, error=? WHERE id=?',
                [(proxy['used'], proxy['error'], proxy['id']) for proxy in self.proxylist])
            await self.db.commit()

    def proxylist_update(self):
        if self.proxylist_thread and self.proxylist_thread.isRunning():
            return
        self.log('Start update proxylist', 'Proxylist')
        self.proxyModel.clear()
        self.proxylist = []
        self.proxylist_obj = ProxylistUpdate()
        self.proxylist_thread = QThread()
        self.proxylist_obj.moveToThread(self.proxylist_thread)
        self.proxylist_obj.message.connect(self.proxylist_on_message)
        self.proxylist_obj.finished.connect(self.proxylist_on_finished)
        self.proxylist_thread.started.connect(self.proxylist_obj.start)
        self.proxylist_thread.start()

    async def proxylist_save(self):
        await self.db.executemany('INSERT OR REPLACE INTO proxy (country,host,port,url,response_time) VALUES (?,?,?,?,?)',
            [(proxy['country'], proxy['host'], proxy['port'], proxy['url'], proxy['response_time']) for proxy in self.proxylist])
        await self.db.commit()
        self.log(f'Save {len(self.proxylist)} proxy', 'Proxylist')

    async def proxylist_clear(self):
        self.proxyModel.clear()
        self.proxylist = []
        await self.db.execute(f'DELETE FROM proxy')
        await self.db.execute(f'DELETE FROM sqlite_sequence WHERE name="proxy"')
        await self.db.commit()
        self.log('Clear proxylist', 'Proxylist')

    def proxylist_on_message(self, message):
        if message[0]:
            self.log(message[0], 'Proxylist')
        if message[1]:
            proxy = message[1]
            self.proxyModel.addRow([proxy['id']+1, proxy['country'], proxy['url'], f'{proxy["response_time"]:.2f}', proxy['used'], proxy['error']])

    def proxylist_on_finished(self, message):
        self.proxylist_thread.quit()
        self.proxylist_thread.wait()
        self.proxylist = message
        self.loop.run_until_complete(self.proxylist_save())
class BalanceReport(Ui_Dialog, QDialog):
    def __init__(self, orm):
        super().__init__()
        self.setupUi(self)

        self.orm = orm

        self.set_month_and_year()

        # Connect signals and slots
        self.yearBox.currentTextChanged.connect(
            lambda year: self.load_balance())
        self.monthBox.currentTextChanged.connect(
            lambda month: self.load_balance())

        self.roll = TableModel(("Date", "Change", "Total", "Origin", "Category"))
        self.balanceView.setModel(self.roll)

        # Show report for current month as initial
        self.load_balance()

    def set_month_and_year(self):
        """
        Sets initial values for year and month boxes.
        """
        self.yearBox.addItems(YEARS)
        self.monthBox.addItems(MONTHS)
        current_date = QDate.currentDate()
        self.yearBox.setCurrentText(str(current_date.year()))
        self.monthBox.setCurrentText(MONTHS[current_date.month()])

    def load_balance(self):
        """
        Fetches info from ORM and puts it into balance report.
        """
        self.roll.prepare()

        year = int(self.yearBox.currentText())
        month = int(self.monthBox.currentIndex())  # by position

        # Get starting balance
        last_date, balance = self.orm.fetch_balance_to_date(month, year)
        self.roll.addRow((last_date, 0, balance, 'Transaction', "- - -"))

        # Get transaction for the active period
        for transaction in self.orm.fetch_transactions_for_period(month, year):
            balance += transaction.amount
            last_date = max(last_date, transaction.date)
            self.roll.addRow((transaction.date, transaction.amount, balance,
                              'Transaction', transaction.category))

        # Correct the last activity date
        today = datetime.date.today()
        last_date = max(last_date, today)

        # Get budget spendings/incoms after active period
        predictions = list(
            self.orm.fetch_budget_prediction(month, year, last_date))
        predictions = sorted(predictions, key=lambda p: p.date)
        for prediction in predictions:
            category = prediction.category
            balance += prediction.amount
            self.roll.addRow((prediction.date, prediction.amount, balance,
                              'Budget', category.parent+"::"+category.name))
Exemple #18
0
 def __init__(self):
     self.logModel = TableModel('Time', 'Type', 'Message')
     self.rootContext().setContextProperty('logModel', self.logModel)
class TransactionsRoll(Ui_Dialog, QDialog):
    """
    GUI that handles the list of all transactions for given account.
    """
    def __init__(self, orm, account):
        super().__init__()
        self.setupUi(self)

        self.orm = orm
        self.account = account

        self.roll = TableModel(("Date", "Amount", "Info", "Category"))
        self.rollView.setModel(self.roll)
        self.selection = QItemSelectionModel(self.roll)
        self.rollView.setSelectionModel(self.selection)

        self.rollView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)

        self.addTransaction.clicked.connect(self.add_transaction)
        self.editTransaction.clicked.connect(self.edit_transaction)
        self.deleteTransaction.clicked.connect(self.delete_transaction)

        self.categories = self.orm.fetch_subcategories()

        self.show_transactions()

    def show_transactions(self):
        """
        Fetches transactions from DB and shows them.
        """
        self.roll.prepare()
        transactions = self.orm.fetch_transactions(self.account)
        for tr in transactions:
            self.roll.addRow(tr)

    def add_transaction(self):
        """
        Fires up GUI for adding transaction.
        """
        manager = Manager(self.categories.values())
        manager.createdTransaction.connect(self.transaction_created)
        manager.exec()

    def edit_transaction(self):
        """
        Fires up GUI for editing transaction.
        """
        index = self.selection.currentIndex()
        if index.isValid():
            transaction = index.data(role=Qt.UserRole)
            manager = Manager(self.categories.values(), transaction)
            manager.editedTransaction.connect(self.transaction_edited)
            manager.exec()

    def delete_transaction(self):
        """
        Deletes transaction from DB and GUI.
        """
        index = self.selection.currentIndex()
        if index.isValid():
            transaction = index.data(role=Qt.UserRole)
            self.orm.delete_transaction(transaction, self.account)
            self.roll.removeRows(index.row(), 1)

    def transaction_created(self, date, amount, info, category):
        """
        Catches transaction created signal and adds transaction to DB and GUI.
        """
        transaction = self.orm.add_transaction(date, amount, info, self.account,
                                               category)
        self.roll.addRow(transaction)

    def transaction_edited(self, transaction, category):
        """
        Catches transaction edited signal and updates transaction in the DB,
        redraws all transactions in the GUI.
        """
        self.orm.update_transaction(transaction, self.account, category)
        self.show_transactions()
class BudgetManager(ui.manageBudget.Ui_Dialog, QDialog):
    """
    GUI that handles creation, editing and deletion of budgets.
    """
    def __init__(self, orm):
        super().__init__()
        self.setupUi(self)

        self.orm = orm

        # Fetch subcategories list
        self.categories = self.orm.fetch_subcategories(full=False)

        self.recordsView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)

        self.set_month_and_year()
        self.setup_table()
        self.load_budget_records()

        # Connect signals and slots
        self.yearBox.currentTextChanged.connect(
            lambda year: self.load_budget_records())
        self.monthBox.currentTextChanged.connect(
            lambda month: self.load_budget_records())
        self.addBtn.clicked.connect(self.add_record)
        self.editBtn.clicked.connect(self.edit_record)
        self.deleteBtn.clicked.connect(self.delete_record)
        self.copyBtn.clicked.connect(self.copy_records)

    def set_month_and_year(self):
        """
        Sets initial values for year and month boxes.
        """
        self.yearBox.addItems(YEARS)
        self.monthBox.addItems(MONTHS[1:])
        current_date = QDate.currentDate()
        self.yearBox.setCurrentText(str(current_date.year()))
        self.monthBox.setCurrentText(MONTHS[current_date.month()])

    def setup_table(self):
        """
        Initializes the table for budget records.
        """
        self.records = TableModel(("Amount", "Category", "Type", "On day"))
        self.recordsView.setModel(self.records)
        self.selection = QItemSelectionModel(self.records)
        self.recordsView.setSelectionModel(self.selection)

    def load_budget_records(self):
        """
        Loads the data from DB to GUI.
        """
        self.records.prepare()
        month = self.monthBox.currentIndex() + 1  # by position+1
        year = self.yearBox.currentText()
        records = self.orm.fetch_records(month, year)
        for r in records:
            self.records.addRow(r)

    def add_record(self):
        """
        Fires up GUI for budget record creation.
        """
        if len(self.categories) == 0:
            show_warning('You have to create categories first.')
            return

        manager = Manager(self.categories.values())
        manager.createdRecord.connect(self.record_created)
        manager.exec()

    def edit_record(self):
        """
        Fires up GUI for budget record editing.
        """
        index = self.selection.currentIndex()
        if index.isValid():
            record = index.data(role=Qt.UserRole)
            manager = Manager(self.categories.values(), record)
            manager.editedRecord.connect(self.record_edited)
            manager.exec()

    def delete_record(self):
        """
        Deletes the budget record from DB and GUI.
        """
        index = self.selection.currentIndex()
        if index.isValid():
            record = index.data(role=Qt.UserRole)
            self.orm.delete_record(record)
            self.records.removeRows(index.row(), 1)

    def copy_records(self):
        dialog = Selector()
        dialog.monthSelected.connect(self.copy_from_month)
        dialog.exec()

    def copy_from_month(self, month, year):
        records = self.orm.fetch_records(month, year)
        new_month = self.monthBox.currentIndex() + 1
        new_year = int(self.yearBox.currentText())
        _, last_day = monthrange(new_year, new_month)
        for rec in records:
            category = self.orm.fetch_subcategory(rec.category_id)
            amount = to_cents(rec.amount)
            new_day = min(last_day, rec.day)
            self.record_created(amount, category, rec.type, new_day,
                                new_year, new_month)

    def record_created(self, amount, category, budget_type, day, year,
                       month):
        """
        Adds created budget record into DB and GUI.
        """
        record = self.orm.add_record(amount, category, budget_type, day,
                                     year, month)
        if (self.monthBox.currentIndex() + 1 == month and
                int(self.yearBox.currentText()) == year):
            self.records.addRow(record)

    def record_edited(self, amount, category, budget_type, day, year,
                      month, record_id):
        """
        Adds edited budget record into DB and reloads all records in the GUI.
        """
        self.orm.update_record(amount, category, budget_type, day, year,
                               month, record_id)
        self.load_budget_records()