connect to MySQL data base with QSqlDatabase pyqt4 - mysql

im new to python code, QT and MySQL, i wanna show a data base in a QtableView but i cant it.
i dont know whats happend, the error is ('QSqlDatabase' object has no attribute 'setHotsName')
the code is:
# -*- coding: utf-8 -*-
import sys
import mysql.connector
from PyQt4 import QtSql, QtCore, QtGui, uic
form_class = uic.loadUiType("dialog.ui")[0]
def crearConexion():
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHotsName('localhots')
db.setDatabaseName('Registro')
db.setUserName('root')
db.setPassword('xxxx')
db.open()
print(db.lastError().text())
return True
class MiClase(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.model=QtSql.QSqlTableModel(self)
self.model.setTable("RegistroIN")
self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
self.model.select()
self.tableView.setModel(self.model)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
if not crearConexion():
sys.exit(1)
MiApp = MiClase()
MiApp.show()
sys.exit(app.exec_())
somebody that help me? thank you.

Related

Import reflected Flask-SQLAlchemy Module before creating the app

This is a continuation of this question.
As my flask app should not write anything in my database, I set up Flask-SQLAlchemy to reflect my database. This way I do not have to change my models, when I change my schema:
# app/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
db.init_app(app)
with app.app_context():
db.Model.metadata.reflect(db.engine)
# app/models.py
from app import db
class Data(db.Model):
__table__ = db.Model.metadata.tables['data']
But now, if I have to import the Model before I created the app, I run into Errors because the metadata is not set yet. This is a problem when it comes to testing for example:
# test.py
import unittest
from app import create_app, db
from app.models import Data
class TestGUI(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.app = create_app()
# etc ...
This throws KeyError: 'data' in __table__ = db.Model.metadata.tables['data'] when importing from app.models as the metadata is not correctly set before the create_app() function is run.
I did find a solution (thanks to #snakecharmerb). The solution is simply to avoid the problem, to not import app.models before running create_app(). A bit hacky, so feel free to post an answer as well, when you have a better solution.
My test file now looks like this:
# test.py
import unittest
from app import create_app, db
app = create_app()
from app.models import Data
class TestGUI(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.app = app
# etc ...

The PyQt5 Application Stop completely

I have a problem here with my Pyqt5 app when I try to add the user input to mysql database in the Add_car_info function. When I press the button to add the info the app stop working and gives me this error message. tested on windows.
here is the code:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import loadUiType
from PyQt5 import QtWidgets, QtGui
import threading
import sys
import os
from os import path
import mysql.connector
import MySQLdb
#get the ui file
FORM_CLASS,_=loadUiType(path.join(path.dirname(__file__),"main.ui"))
class MainApp(QMainWindow, FORM_CLASS):
def __init__(self, parent=None):
super(MainApp,self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
self.Handel_Ui()
self.Handel_DB_Connect()
self.Handel_Buttons()
self.Handel_DB_Connect()
def Handel_Ui(self):
self.setWindowTitle('Car_System')
self.tabWidget.tabBar().setVisible(False)
def Handel_DB_Connect(self):
db = mysql.connector.connect(database='mydb',
host='localhost',
user='root',
port='3309',
password='toor')
self.cur = db.cursor()
QApplication.processEvents()
def Handel_Buttons(self):
self.pushButton.clicked.connect(self.Add_car_info)
self.pushButton_2.clicked.connect(self.Update_car_info)
self.pushButton_3.clicked.connect(self.Delete_car_info)
self.pushButton_4.clicked.connect(self.Add_fuel_info)
self.pushButton_9.clicked.connect(self.Update_fuel_info)
self.pushButton_5.clicked.connect(self.Add_maintenance_info)
self.pushButton_6.clicked.connect(self.Update_maintenance_info)
self.pushButton_7.clicked.connect(self.Add_Licence_info)
self.pushButton_8.clicked.connect(self.Update_Licence_info)
self.pushButton_17.clicked.connect(self.Add_Revenus_info)
self.pushButton_18.clicked.connect(self.Update_Revenus_info)
self.pushButton_19.clicked.connect(self.Add_Rents_info)
self.pushButton_20.clicked.connect(self.Update_Rents_info)
self.pushButton_34.clicked.connect(self.Add_elewater_info)
self.pushButton_33.clicked.connect(self.Update_elewater_info)
def Add_car_info(self):
car_number = self.lineEdit_12.text()
owner_company = self.lineEdit_10.text()
branch = self.lineEdit_8.text()
service_mode = self.comboBox.currentIndex()
shaceh_number = self.lineEdit_4.text()
motor_number = self.lineEdit_2.text()
fuel_type = self.comboBox_2.currentIndex()
car_type = self.lineEdit_11.text()
car_model = self.lineEdit_9.text()
car_load = self.lineEdit_7.text()
car_wight = self.lineEdit_5.text
car_shape = self.lineEdit_3.text()
car_color = self.lineEdit.text()
self.cur.execute('''INSERT INTO car_info(car_number, owner_company, branch, service_mode, shaceh_number, motor_number, fuel_type, car_type, car_model, car_load, car_weight, car_shape, car_color)'
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''' , (car_number,owner_company,branch,service_mode,shaceh_number,motor_number,fuel_type,car_type,car_model,car_load,car_wight,car_shape,car_color))
QApplication.processEvents()
print('Done')
def Update_car_info(self):
pass
def Delete_car_info(self):
pass
def Add_fuel_info(self):
pass
def Update_fuel_info(self):
pass
def Add_maintenance_info(self):
pass
def Update_maintenance_info(self):
pass
def Add_Licence_info(self):
pass
def Update_Licence_info(self):
pass
def Add_Revenus_info(self):
pass
def Update_Revenus_info(self):
pass
def Add_Rents_info(self):
pass
def Update_Rents_info(self):
pass
def Add_elewater_info(self):
pass
def Update_elewater_info(self):
pass
def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
app.exec_()
if __name__ == '__main__':
main()
thank you for your attantion and have a good day.

putting HTML output from SHAP into the Dash output layout callback

I am trying to make a dashboard where the output from shap forceplot is illustrated. Shap.forceplot is HTML decorated with json. The example is here
I made a very simple dashboard using the tutorial which should plot the desirable figure after clicking the submit
here is the code
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import pandas as pd
from sqlalchemy import create_engine
import shap
from sources import *
import xgboost
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Input(id='input-cvr-state', type='text', value='12'),
html.Button(id='submit-button', n_clicks=0, children='Submit'),
html.Div(id='output-state'),
html.Div(id='output-shap')
])
#app.callback(Output('output-shap', 'children'),
[Input('submit-button', 'n_clicks')],
[State('input-cvr-state', 'value')])
def update_shap_figure(n_clicks, input_cvr):
shap.initjs()
# train XGBoost model
X,y = shap.datasets.boston()
model = xgboost.train({"learning_rate": 0.01}, xgboost.DMatrix(X, label=y), 100)
# explain the model's predictions using SHAP values(same syntax works for LightGBM, CatBoost, and scikit-learn models)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)
# visualize the first prediction's explanation
return(shap.force_plot(explainer.expected_value, shap_values[0,:], X.iloc[0,:])) # matplotlib=True
if __name__ == '__main__':
app.run_server(debug=True)
I managed it by following steps:
import shap
from shap.plots._force_matplotlib import draw_additive_plot
# ... class dashApp
# ... callback as method
# matplotlib=False => retrun addaptativevisualizer,
# if set to True the visualizer will render the result is the stdout directly
# x is index of wanted input
# class_1 is ma class to draw
force_plot = shap.force_plot(
self.explainer.expected_value[class_1],
self.shap_values[class_1][x[0], :],
self.data.iloc[x, :].drop(columns=["TARGET"], errors="ignore"),
matplotlib=False
)
# set show=False to force the figure to be returned
force_plot_mpl = draw_additive_plot(force_plot.data, (30, 7), show=False)
return figure_to_html_img(force_plot_mpl)
def figure_to_html_img(figure):
""" figure to html base64 png image """
try:
tmpfile = io.BytesIO()
figure.savefig(tmpfile, format='png')
encoded = base64.b64encode(tmpfile.getvalue()).decode('utf-8')
shap_html = html.Img(src=f"data:image/png;base64, {encoded}")
return shap_html
except AttributeError:
return ""
The result will be like it
An alternative is to use html.IFrame which will produce a better looking and fully interactive plot.
Here's an example that can be used directly as an Output
def _force_plot_html(*args):
force_plot = shap.force_plot(*args, matplotlib=False)
shap_html = f"<head>{shap.getjs()}</head><body>{force_plot.html()}</body>"
return html.Iframe(srcDoc=shap_html,
style={"width": "100%", "height": "200px", "border": 0})

raise_FirstSetError in SpaCy topic modeling

I want to create a LDA topic model and am using SpaCy to do so, following a tutorial. The error I receive when I try to use spacy is one I cannot find on google, so I'm hoping someone here knows what it's about.
I'm running this code on Anaconda:
import numpy as np
import pandas as pd
import re, nltk, spacy, gensim
# Sklearn
from sklearn.decomposition import LatentDirichletAllocation, TruncatedSVD
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import GridSearchCV
from pprint import pprint
# Plotting tools
import pyLDAvis
import pyLDAvis.sklearn
import matplotlib.pyplot as plt
df = pd.DataFrame(data)
def sent_to_words(sentences):
for sentence in sentences:
yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))
# deacc=True removes punctuations
data_words = list(sent_to_words(data))
print(data_words[:1])
def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):
"""https://spacy.io/api/annotation"""
texts_out = []
for sent in texts:
doc = nlp(" ".join(sent))
texts_out.append(" ".join([token.lemma_ if token.lemma_ not in ['-PRON-'] else '' for token in doc if token.pos_ in allowed_postags]))
return texts_out
nlp = spacy.load('en', disable=['parser', 'ner'])
# Do lemmatization keeping only Noun, Adj, Verb, Adverb
data_lemmatized = lemmatization(data_words, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])
print(data_lemmatized[:1])
And I receive the following error:
File "C:\Users\maart\AppData\Local\Continuum\anaconda3\lib\site-packages\_regex_core.py", line 1880, in get_firstset
raise _FirstSetError()
_FirstSetError
The error must occur somewhere after the lemmatization, because the other parts work fine.
Thanks a bunch!
I had this same issue and I was able to resolve it by uninstalling regex (I had the wrong version installed) and then running python -m spacy download en again. This will reinstall the correct version of regex.

HTMLTestRunner is not working

I'm trying to generate an HTML report from my Unittests of Python3.6. I'm using the HTMLTestRunner library.
Here are my unit tests:
#!/usr/bin/env python
import unittest
import boto3
import warnings
import HTMLTestRunner
class SecurityGroupTest(unittest.TestCase):
def setUp(self):
session = boto3.Session(profile_name='default')
self.ec2_clt = session.client('ec2')
def test_delete_03(self):
response = self.ec2_clt.describe_security_groups()
self.assertEqual(len(response['SecurityGroups']), 0)
if __name__ == "__main__":
HTMLTestRunner.main()
When I run the tests, nothing is generated. What am I missing here?