Here's my situation:
I got a table on a database, as following:
nome_imagem estado type
57260-tracker-_tracker_face awake 0
57261-tracker-_tracker_face drowsiness 1
57268-tracker-_tracker_face noface 2
57289-tracker-_tracker_face distracted 3
57290-tracker-_tracker_face awake 1
57291-tracker-_tracker_face drowsiness 2
57293-tracker-_tracker_face noface 3
And I want to update de type column according to serveral if conditions, but I'm getting a error on line 29:
mysql.connector.errors.InternalError: Unread result found
I'm pretty sure its the way im making the query, and I already searched another questions about this before opening this one, but I couldnt solve it anyway.
EDIT 1: Changed the query and applied the solution gave by gzc to get rid of the error, but now it updates all the type column instead of just the cases where the if is true
import mysql.connector
from mysql.connector import errorcode
import os
cnx = mysql.connector.connect(user='root', database='empresa')
cursor = cnx.cursor()
fileDir = os.path.dirname(os.path.realpath(__file__))
textDir = os.path.join(fileDir, "test_img")
query = ("SELECT nome_imagem, estado, type FROM alertas ")
cursor.execute(query)
results = list(cursor)
for (nome_imagem, estado, type) in results:
print nome_imagem, estado
my_file_name = nome_imagem+'.txt'
my_file = open("test_img/"+my_file_name, 'r')
content = my_file.readline()
status = content.strip().split()[-1].split("=")[1]
face = content.strip().split()[0].split("=")[1]
print status, face #1 tem face, 0 nao tem
if (face == '1' and estado == status): #se tem cara e o estado que tem na bd for igual ao estado que o programa classificou = correto
print "correto"
cursor.execute("UPDATE alertas SET type='1' WHERE nome_imagem=nome_imagem")
if (face == '1' and estado == 'drowsiness' and status == 'awake') or (face == 1 and estado == 'awake' and status == 'drowsiness'): #verificar isto
print "trocado"
if (estado != '' and face == '0'): # se tiver estado mas nao tiver cara classifico logo como errado 3
print "errado"
if (estado == 'distracted' and face == '1'): # se tem cara mas for distracted deixo normal pois nao consigo classificar
print "normal"
cursor.close()
cnx.close()
What am I doing wrong?
Thanks
EDIT 2: gzc solver it again :)
You must read all results before doing another operation on the same cursor.
...
query = ("SELECT nome_imagem, estado, type FROM alertas ")
cursor.execute(query)
results = list(cursor)
for (nome_imagem, estado, type) in results:
...
Related
I'm trying to add to the Table Widget the information that I have on my SQLite table.
That's it my SQL table:
.
That my Table Widget:
The code of the method:
if self.ui.btn_jugadores.clicked.connect(lambda: self.ui.pila_de_paginas.setCurrentWidget(self.ui.pg_jugadores)): self.mostrar_jugadores()
def mostrar_jugadores(self):
try:
cursor = conectarse_bbdd_jugadores()
consulta = ''' SELECT * FROM jugadores'''
ejecucion = cursor.execute(consulta).fetchall()
if len(ejecucion) > 0:
fila = 0
for e in ejecucion:
columna = 0
for apartado in e:
celda = QTableWidgetItem(apartado)
self.ui.tabla_jgds.setItem(fila, columna, celda)
columna += 1
print(apartado)
fila += 1
else:
QMessageBox.setText('No hay registros en la tabla de jugadores')
QMessageBox.setIcon(QMessageBox.warning)
QMessageBox.exec_()
except Error as error:
QMessageBox.setText('No se ha podido ejecutar la sentencia')
QMessageBox.setIcon(QMessageBox.warning)
QMessageBox.exec_()
And this is the result:
when I executed it
I don't know why the numbers are not appearing in the table widget.
I'm working on a Python project which use SQlite3 database.
I created database with only one table called "Message" with this kind of data:
connexion = sqlite3.connect(BDD)
c = connexion.cursor()
c.execute(f""" CREATE TABLE IF NOT EXISTS {arg}(
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Jour_Heure_Reception text,
Jour_Heure_Reponse text,
Theme text,
Motif text,
Risque_incident_client text,
Transfert_sans_action text,
Matricule text,
Origine text)""")
connexion.commit()
connexion.close();
My goal is to search between 2 dates in the Jour_Heure_Reponse column, and return the number of entries by matricule.
To do that, I use this SQlite query:
def nbr(arg):
"requette dans la bdd de statistiques mails retournant le nombre de messages par utilisateur sur la période arg"
#Création de la liste des utilisateurs ayant saisies des entrées dans la BDD sur la période
connexion = sqlite3.connect(BDD)
c = connexion.cursor()
date_selection = str((datetime.now() - timedelta(arg)).strftime('%d/%m/%Y'))
yesterday = str(datetime.now().strftime('%d/%m/%Y'))
c.execute(f"""
select Matricule from Message Where
Jour_Heure_Reception >= "{date_selection}"
and Jour_Heure_Reponse < "{yesterday}" """ )
agents = c.fetchall()
liste_agents = []
for i in agents:
if not i[0] in liste_agents:
liste_agents.append(i[0])
c.close()
# calcul du nombre d'entrées pour chaque matricules présent dans la liste crée précédemment
connexion = sqlite3.connect(BDD)
c = connexion.cursor()
liste_affichage = []
for i in liste_agents:
c.execute(f"""SELECT * FROM Message where
Matricule = "{i}" and
Jour_Heure_Reception >= "{date_selection}" and
Jour_Heure_Reponse < "{yesterday}" """)
test = c.fetchall()
print(i)
for i in test:
print(i[1])
data_list = [str(i),str(len(test))]
liste_affichage.append(data_list)
c.close()
The problème is that one:
When i call mi nbr func, it return nothing if mi arg is not 1, and even with 1 arg, the result is not logical.
for exemple, calling nrb(1), return this ( i only print dates ):
02/06/2020
02/06/2020
02/06/2020
02/06/2020
02/06/2020
02/06/2020
02/06/2020
03/06/2020
03/06/2020
03/06/2020
03/06/2020
02/07/2020
02/07/2020
02/07/2020
03/07/2020
03/08/2020
02/09/2020
03/09/2020
03/09/2020
09/08/2020
09/08/2020
09/08/2020
09/08/2020
09/08/2020
01/10/2020
02/10/2020
02/10/2020
As you can see, the timedelta is not respected.
As the datatype is stored as Text, I send dates as str after a time.strftime() conversion.
Where am I going wrong?
Sqlite does not have a dedicated date type. It supports storing date using a text field in ISO-8601 format. You will have to do date format conversion, so that you can perform your comparison. For the format details and documentation see this:
https://www.sqlite.org/lang_datefunc.html
You should use %Y-%m-%d as format string.
I use the twilio API to write a simple program to remember my father to take his meds. Here is my code which can be replicated by anyone who has an account in twilio, one phone number and the sheet medications.csv(see bellow):
from twilio.rest import Client
import pandas as pd
from datetime import datetime
import re
account_sid = 'XXXXXXXXXXXXX' #INSERT YOUR SID HERE
auth_token = 'XXXXXXXXXXXXX' #INSERT YOUR TOKEN HERE
client = Client(account_sid, auth_token)
def to_list_integer(dt_time):
return [dt_time.year,dt_time.month,dt_time.day, dt_time.hour,dt_time.minute]
df=pd.read_csv('medications.csv')
while True:
data_lista = to_list_integer(datetime.now())
x=datetime(*data_lista)
hora = x.strftime("%Hh%M")
for i in range(len(df)):
if (datetime.now().hour==df['hour'][i]) & (datetime.now().minute==df['minute'][i]) & (datetime.now().second==1):
text = '''*Lembrete: {0}*\n
Olá sr. X, agora são {1},
\nestá na hora de tomar {2} comprimido(s) de {0}
\n\n*recomendação médica: {3}*'''.format(df['name'][i],hora,re.search(r'\d+',df['recomendation'][i]).group(),
df['recomendation'][i])
persons=['whatsapp:+XXXXXXXXXXXXX','whatsapp:+XXXXXXXXXXXXX','whatsapp:+XXXXXXXXXXXXX',
'whatsapp:+XXXXXXXXXXXXX', 'whatsapp:+XXXXXXXXXXXXX']
for person in persons:
message = client.messages.create(
body=text,
from_='whatsapp:+XXXXXXXXXXX',#INSERT YOUR TWILIO NUMBER HERE
to=person
)
print(message.sid)
medications.csv:
name,dosage,recomendation,hour,minute
Selozek,100mg,Tomar 1 comprimido pela manhã,6,9
Vasopril Plus,20/12.5 mg,Tomar 1 comprimido pela manhã,6,10
Glifage XR,500mg,Tomar 2 comprimidos após o café e após a última refeição da noite,7,10
Clopidogrel,75mg,Tomar 1 comprimido após o almoço,13,10
AAS,100mg,Tomar 1 comprimido após o almoço,13,11
Enalapril,10mg,Tomar 2 comprimidos à noite,20,10
Glifage XR,500mg,Tomar 2 comprimidos após o café e após a última refeição da noite,20,11
Rosuvastatina,20mg,Tomar 1 comprimido após a última refeição da noite,20,12
The code was working properly yesterday but today it is no longer working. The program runs without errors and print the sids for each message. However, none of the phones in the list persons are receiving the message. What is wrong here?
I'm making a video game in upbge (which for this aspect is basically python) but to send the info between sockets it needs to be in bytes but i only found a way to do it turning it into a string, (because the list get's created with the game (i have a script that once a new entity appears it get's added to the list in the form of (Player-entity|data) but i want the data to variate between entities and i ran out of symbols to use to split it into lists so i'm trying to send the data as a list to be able to simply check it's components, but as it's a list inside of a list (and sometimes more) the bytearray won't work (at least i can't figure out how to make it work)
I'm unsure of how to summarize the code, but this is the code that I have now to generate that info
import socket
mi_socket = socket.socket()
mi_socket.bind(('127.0.0.1',55555))
mi_socket.listen()
TP = 0 #Total players
AP = 0 #Actual player
PL = ["host"] #Player List
AE = 0 #Actual entity
TE = 0 #Total entities
EL = ["|PlayerEntity$[Data]|"] #Entity list
PI = [] #Player Intel (Player name, Total Players, Player Code) (apartado uno en las comunicaciones)
order = None #Variable reservada para guardar comandos u identificaciones (ej: nombre de la entidad) en las comunicaciones
content = None #Variable reservada para almacenar la información recibida
incoming = 0 #Variable reservada para analizar el mensaje recibido de entrada
def login():
global AP
global TP
global PL
PJ = str(incoming).split("$")[1] #incoming Player
if AP <= TP:
if PJ!=str(PL[int(AP)]): #Nombre jugador que se conecta
AP+=1
login()
pass
else:
identity()
pass
if AP > TP:
PL.append(str("Player" + str(AP))) #Agregar jugador a la lista
TP = int(AP)
def identity(): #identifica de qué se trata la orden para responder en consecuencia, si se trata de entidad anota tmb la entidad en la lista
global TE
global AE
global EL
global AP
global PL
PJ = str(incoming).split("$")[1] # incoming Player
PE = str(incoming).split("$")[2] # incoming entity
if AE <= TE:
# Si nombre de jugador|nombre de objeto no és EL[AE]([1]|[2])
if str(str(PL[AP])+"-"+str(PE)) != str(str(EL[AE]).split("|")[1]).split("$")[0]:
AE+=1
identity()
pass
else:
EL[AE] = "|"+PL[AP]+"-"+PE+"$"+str(incoming).split("$")[3]+"|"
if AE > TE:
EL.append("|"+PL[AP]+"-"+PE+"$"+str(incoming).split("$")[3]+"|")
TE = int(AE)
def main():
global AP
global AE
global TE
global incoming
conexion, ip = mi_socket.accept()
incoming = conexion.recv(1024)
login()
conexion.send(str("#"+str(PL[AP])+"#"+str(EL[1:TE+1])+"#").encode())
AP=0
AE=0
conexion.close()
while True:
main()
I am importing an excel worksheet that has the following columns name:
N° Pedido
1234
6424
4563
The column name ha a special character (°). Because of that, I can´t merge this with another Data Frame or rename the column. I don´t get any error message just the name stays the same. What should I do?
This is the code I am using and the result of the Dataframes:
import pandas as pd
import numpy as np
# Importando Planilhas
CRM = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
Vendas\relatorio_vendas_CRM.xlsx', encoding= 'utf-8')
protheus = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
Vendas\relatorio_vendas_protheus.xlsx', encoding= 'utf-8')
#transformando em Data Frame
df_crm = CRM.parse('190_pedido_export (33)')
df_protheus = protheus.parse('Relatorio de Pedido de Venda')]
# Transformando Campos em float o protheus
def turn_to_float(x):
return np.float(x)
df_protheus["TES"] = df_protheus["TES"].apply(turn_to_float)
df_protheus["Qtde"] = df_protheus["Qtde"].apply(turn_to_float)
df_protheus["Valor"] = df_protheus["Valor"].apply(turn_to_float)
#Tirando Tes de não venda do protheus
# tirando valores com código errado 6
df_protheus_1 = df_protheus[df_protheus.TES != 513.0]
df_protheus_2 = df_protheus_1[df_protheus_1.TES != 576.0]
**df_crm.columns = df_crm.columns.str.replace('N° Pedido', 'teste')
df_crm.columns**
Orçamento Origem N° Pedido Nº Pedido ERP Estabelecimento Tipo de
Pedido Classificação(Tipo) Aplicação Conta CNPJ/CPF Contato ...
Aprovação Parcial Antecipa Entrega Desconto da Tabela de Preço
Desconto do Cliente Desconto Informado Observações Observações NF Vl
Total Bruto Vl Total Completo
0 20619.0 23125 NaN Optitex 1 - Venda NaN Industrialização/Revenda
XAVIER E ARAUJO LTDA ME 7970626000170 NaN ... N N 0 0 0
Note that I used other codes for the bold part with the same result:
#renomeando tabela para dar Merge
#df_crm['proc'] = df_crm['N\xc2\xb0 Pedido']
#df_crm['N Pedido'] = df_crm['N° Pedido']
#df_crm.drop('N° Pedido',inplace=True,axis=1)
#df_crm
#df_crm['N Pedido'] = df_crm['N° Pedido']
#df.drop('N° Pedido',inplace=True,axis=1)
#df_crm
#df_crm_1 = df_crm.rename(columns={"N°Pedido": "teste"})
#df_crm_1
Thanks for posting the link to the Google Sheet. I downloaded it and loaded it via pandas:
df = pd.read_excel(r'~\relatorio_vendas_CRM.xlsx', encoding = 'utf-8')
df.columns = df.columns.str.replace('°', '')
df.columns = df.columns.str.replace('º', '')
Note that the two replace statements are replacing different characters, although they look very similar.
Help from: Why do I get a SyntaxError for a Unicode escape in my file path?
I was able to copy the values into another column. You could try that
df['N Pedido'] = df['N° Pedido']
df.drop('N° Pedido',inplace=True,axis=1)