Can someone explain to me why this code doesn't return any output - datetime

The code doesn't output what I expected. How do I get the code to output when i call the function?
import calendar
import datetime
from datetime import date
Eke, Orie, Afor, Nkwo = 0, 1, 2, 3
start_year = 1600
def IgboWeek(func):
def wrapper_func():
if date.year != start_year:
Eke = calendar.SUNDAY
Orie = calendar.MONDAY
Afor = calendar.TUESDAY
Nkwo = calendar.WEDNESDAY
calendar.THURSDAY = Eke
calendar.FRIDAY = Orie
calendar.SATURDAY = Afor
func()
return wrapper_func
#IgboWeek
def birthday():
birthday = input("Enter your birthday in the format: YYYY/MM/DD: ")
if Eke in birthday:
print("Eke")
elif Orie in birthday:
print("Orie")
elif Afor in birthday:
print("Afor")
elif Nkwo in birthday:
print("Nkwo")
else:
print("Not in a good mood for that")
Igobirthday = IgboWeek(birthday)
Igobirthday()

Related

Not able to map data from sql join to pydantic models in fastapi

I am trying to map data from sql join of two tables to pydantic model, but getting null value
models.py
class Countries(BaseModel):
country_name: str = Field(None, alias="country_name")
class Tools(BaseModel):
tool_name:str = Field(None, alias="tool_name")
tool_id: int = Field(None, alias="tool_id")
class ShowData(BaseModel):
countries:Countries = Field(None, alias="countries")
tools:Tools = Field(None, alias="tools")
class Config:
orm_mode = True
repository.py
def test(db: Session = Depends(get_db)):
statement = select(Tool.tool_name, UserCountryToolAccess.tool_id, Country.country_name).where(Tool.tool_id == UserCountryToolAccess.tool_id, Country.country_id == UserCountryToolAccess.country_id)
results = db.exec(statement).fetchall()
print(results)
return results
This is the data I am receiving in repository.py [('pdf compressor', 1, 'United States of America'), ('image resizer', 4, 'United Kingdom'), ('cost budgeting', 2, 'Russia'), ('scenario planner', 5, 'Germany'), ('cropping image', 1, 'United States of America'), ('leave dashboard', 3, 'Russia')]
test.py
#router.get("/test",tags=['test'],response_model=schemas.ShowData)
def get_user(db: Session = Depends(get_db)):
result = repository.test(db)
return result
I need data in the below json structure
{
"countries": {
"country_name": "India"
},
"tools": {
"tool_id": 1,
"tool_name": "pdf compressor"
}
}

FLASK-ADDING DATETIME CALCULATION INTO DATABASE

I m trying to perform a little calculation and Logic on date.time with Flask application.
1.) the application will calculate the difference between issue date and expiry date called "remaining days" , The application will check if remaining days is less than 365 days and trigger a function
I attempted the first logic to manipulate the data and submit to database
`#bp.route('/cerpacs/add', methods=['GET', 'POST'])
#login_required
def add_cerpac():
"""
Add a an Cerpac/ expartriates to the database
"""
check_admin()
add_cerpac = True
form =CerpacForm()
if form.validate_on_submit():
cerpac = Cerpac(cerpac_serial_no=form.cerpac_serial_no.data,
cerpac_issue_date= form.cerpac_issue_date.data,
cerpac_exp_date=form.cerpac_exp_date.data,
employee =form.employee.data, )
form.cerpac_issue_date.data = cerpac.cerpac_issue_date
form.cerpac_exp_date.data = cerpac.cerpac_exp_date
if request.method == 'POST':
todays_date = datetime.now()
t = cerpac.cerpac_issue_date
t1 = cerpac.cerpac_exp_date
remaining_days = t1 - t
print(remaining_days) - good prints my result!
remaining_days = cerpac.remaining_days ----not adding to database
try:
add cerpac to the database
db.session.add(cerpac)
db.session.commit()
flash('You have successfully added a Cerpac.' )`
`
my model:
class Cerpac(db.Model):
__tablename__ = 'cerpacs'
id = db.Column(db.Integer, primary_key=True)
cerpac_issue_date = db.Column(db.DateTime)
cerpac_exp_date=db.Column(db.DateTime)
remaining_days = db.Column(db.DateTime)
cerpac_serial_no = db.Column(db.String(60))
cerpac_upload = db.Column(db.String(20), default='cerpac.jpg')
renew_status = db.Column(db.Boolean, default=False)
process_status = db.Column(db.Boolean, default=False)
renewcerpac_id = db.Column(db.Integer, db.ForeignKey('renewcerpacs.id'))
employee_id = db.Column(db.Integer, db.ForeignKey('employees.id'))
def __repr__(self):
return '<Cerpac {}>'.format(self.name) model:
I want to add this to database and eventually write a function like this:
I had a mistake also in the code because I had error issue_date not defined. How do I define issue_date as a date.time variable?
def remaining_days(issue_date, expired_date):
issue_date = datetime(issue_date)
days_to_go = expired - issue
if days_to_go == 365:
renew_status== True
print("time to renew")
print("We are Ok")
I would simplify this to something like:
from datetime import datetime
class Cerpac(db.Model):
...
cerpac_exp_date=db.Column(db.DateTime)
...
#property
def remaining_days(self):
return (self.cerpac_exp_date - self.cerpac_issue_date).days
#property
def days_to_expiry(self):
return (self.cerpac_exp_date - datetime.now()).days
Then, days_to_expiry and remaining_days become properties calculated when you query, and update automatically when they renew their cards.

Wxpython grid AppendRows

The following code is used to generate a table that an row can be added by a button, but only the data of the last row is eliminated after running.
import wx, wx.grid
class GridData(wx.grid.PyGridTableBase):
_cols = "a b c".split()
_data = [
"1 2 3".split(),
"4 5 6".split(),
"7 8 9".split()
]
_highlighted = set()
def GetColLabelValue(self, col):
return self._cols[col]
def GetNumberRows(self):
return len(self._data)
def GetNumberCols(self):
return len(self._cols)
def GetValue(self, row, col):
return self._data[row][col]
def SetValue(self, row, col, val):
self._data[row][col] = val
def AppendRows(self, *args):
msg = wx.grid.GridTableMessage(self,
wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED,
)
self.GetView().ProcessTableMessage(msg)
return True
# self.GetView().EndBatch()
# msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
# self.GetView().ProcessTableMessage(msg)
def GetAttr(self, row, col, kind):
attr = wx.grid.GridCellAttr()
attr.SetBackgroundColour(wx.GREEN if row in self._highlighted else wx.WHITE)
return attr
def set_value(self, row, col, val):
self._highlighted.add(row)
self.SetValue(row, col, val)
class Test(wx.Frame):#main frame
def __init__(self):
wx.Frame.__init__(self, None)
self.data = GridData()
self.grid = wx.grid.Grid(self)
self.grid.SetTable(self.data)
btn = wx.Button(self, label="set a2 to x")
btn.Bind(wx.EVT_BUTTON, self.OnTest)
self.Sizer = wx.BoxSizer(wx.VERTICAL)
self.Sizer.Add(self.grid, 1, wx.EXPAND)
self.Sizer.Add(btn, 0, wx.EXPAND)
def OnTest(self, event):
self.grid.AppendRows(numRows=3)
#self.data.set_value(1, 0, "x")
self.grid.Refresh()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()
There is no error report,and the expectation can't be reached.
The following code is used to generate a table that can be added by a button, but only the data of the last row can be eliminated after running.

Shopping cart quantity not updating

I have a basic shopping cart. I thought it was working but I have since discovered that even though it runs error free it is not doing one thing I thought it should and I am having trouble resolving the issue.
If I instantiate an item a second time, like this:
item1 = Item(1, "Cucumbers", 1., 1, 'kg')
item2 = Item(2, "Tissues", 2., 2, 'dozen')
item3 = Item(3, "Tomatoes", 3., 5, 'pound')
# item4 = Item(4, "Toothpaste", 1., 5, 'box')
item4 = Item(4, "Cucumbers", 1., 2, 'kg')
What I want is for the quantity of cucumbers in item 1 to increase to '3'
and for item 4 to be auto-deleted.
I thought this was doing what I intended, but it's not:
elif k == 'name':
total_qty = v.qty + item.qty
if total_qty:
v.qty = total_qty
continue
self.remove_item(k)
else:
v[k] = item[k]
The code runs error free but I end up with two separate instances of cucumber.
Full code:
class Item(object):
def __init__(self, unq_id, name, price, qty, measure):
self.unq_id = unq_id
self.product_name = name
self.price = price
self.qty = qty
self.measure = measure
class Cart(object):
def __init__(self):
self.content = dict()
def __format__(self, format_type):
if format_type == 'short':
return ', '.join(item.product_name for item in self.content.values())
elif format_type == 'long':
return '\n'.join(f'\t\t{item.qty:2} {item.measure:7} {item.product_name:12} # '
f'${item.price:1.2f} ... ${item.qty * item.price:1.2f}'
for item in self.content.values())
def add(self, item):
if item.unq_id not in self.content:
self.content.update({item.unq_id: item})
return
for k, v in self.content.get(item.unq_id).items():
if k == 'unq_id':
continue
elif k == 'name':
total_qty = v.qty + item.qty
if total_qty:
v.qty = total_qty
continue
self.remove_item(k)
else:
v[k] = item[k]
def get_total(self):
return sum([v.price * v.qty for _, v in self.content.items()])
def get_num_items(self):
return sum([v.qty for _, v in self.content.items()])
def remove_item(self, key):
self.content.pop(key)
if __name__ == '__main__':
item1 = Item(1, "Cucumbers", 1., 1, 'kg')
item2 = Item(2, "Tissues", 2., 2, 'dozen')
item3 = Item(3, "Tomatoes", 3., 5, 'pound')
# item4 = Item(4, "Toothpaste", 1., 5, 'box')
item4 = Item(4, "Cucumbers", 1., 2, 'kg')
cart = Cart()
cart.add(item1)
cart.add(item2)
cart.add(item3)
cart.add(item4)
print("Your cart contains: {0:short}".format(cart))
# cart.remove_item(1)
print()
print("Your cart contains: \n {0:long}".format(cart))
print()
print("The total number of items in your cart is: ", cart.get_num_items())
print()
print("The total cost of the items in your cart is: ", cart.get_total())
print()
cart.remove_item(3)
print("Your cart contains: {0:short}".format(cart))
print()
print("Your cart contains: \n {0:long}".format(cart))
print()
print("The total number of items in your cart is: ", cart.get_num_items())
print()
print("The total cost of the items in your cart is: ", cart.get_total())
The fix is:
def add(self, item):
if item.unq_id not in self.content:
self.content.update({item.unq_id: item})
return
else:
self.content[item.unq_id].qty = self.content[item.unq_id].qty + item.qty

Pyqt GUI, Lineedit, Game MasterMind

Good day, I can not run the following code in pyqt, I'm new and do not really understand the class, I appreciate the collaboration
Apparently the problem is how to connect the function (self.ui.lineEdit_2.returnPressed.connect (self.checkText)
# -*- coding: utf-8 -*-
import sys
from mastermind import *
from PyQt5 import QtWidgets
import random
import time
class Menu_mm(QtWidgets.QDialog):
def __init__(self,parent=None):
QtWidgets.QWidget.__init__(self,parent)
self.ui = Ui_MasterMind()
self.ui.setupUi(self)
self.ui.comboBox.addItem("Facil")
self.ui.comboBox.addItem("Dificil")
self.ui.comboBox.addItem("Legendario")
self.ui.comboBox.activated.connect(self.num)
self.ui.pushButton.clicked.connect(self.Empezar)
self.ui.label_14.setVisible(False)
self.ui.label_19.setVisible(False)
self.ui.label_20.setVisible(False)
self.ui.label_15.setVisible(False)
self.ui.label_16.setVisible(False)
def num(self):
x= self.ui.comboBox.currentText()
if x == "Facil":
self.ui.label_6.setText("3")
y=1
elif x == "Dificil":
self.ui.label_6.setText("4")
y=2
else:
self.ui.label_6.setText("5")
y=3
def Empezar(self):
x = self.ui.comboBox.currentText()
if x == "Facil":
y = 1
elif x == "Dificil":
y = 2
else:
y = 3
continuar = 1
while continuar == 1:
if y == 1:
cant_digitos = 3
elif y == 2:
cant_digitos = 4
elif y == 3:
cant_digitos = 5
print(cant_digitos)
#print("cant_digitos")
digitos = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
codigo = ''
for i in range(cant_digitos):
elegido = random.choice(digitos)
while elegido in codigo:
elegido = random.choice(digitos)
codigo = codigo + elegido
print(codigo)
global propuesta
propuesta = self.ui.lineEdit_2.text()
intentos = 1
while propuesta != codigo:
intentos = intentos + 1
aciertos = 0
coincidencias = 0
for i in range(cant_digitos):
if propuesta[i] == codigo[i]:
aciertos = aciertos + 1
elif propuesta[i] in codigo:
coincidencias = coincidencias + 1
propuesta=self.ui.lineEdit_2.text()
self.ui.lineEdit_2.returnPressed.connect(self.checkText)
print(propuesta)
self.ui.label_13.setText(str(propuesta))
self.ui.label_9.setText(str(aciertos))
self.ui.label_11.setText(str(coincidencias))
self.ui.label_14.setVisible(True)
self.ui.label_15.setVisible(True)
self.ui.label_16.setVisible(True)
def checkText(self):
propuesta =self.ui.lineEdit_2.Text()
print("si")
self.ui.lineEdit_2.clear()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = Menu_mm()
myapp.show()
sys.exit(app.exec_())
You shouldn't put the connect statement inside a loop. It's going to create a new connection for each iteration through the loop
while continuar == 1:
while propuesta != codigo:
self.ui.lineEdit_2.returnPressed.connect(self.checkText)
You probably want to make that connection in the __init__

Resources