None-type in script - nonetype

I'm making a calculator that imports 2 unit files and calculates which one would win, and with what numbers left (have removed the tkinter stuffs as there wasn't enough space in stack overflow to let me). I run the code, and get this:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\The Ginger Knight\Documents\Uni\Software\Python\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/The Ginger Knight/Documents/Game/Game Folder/Combat Calculator.py", line 718, in allstates
cavef1a = efsmounta(mountefsa)[0] + efsprima(primefsa)[0]
TypeError: 'NoneType' object is not subscriptable
I've tried multiple things, and none of them have worked. Could someone please take a look (long code, sorry), and tell me what I've done wrong? I've looked at some of the other none returns, but I couldn't match them up to what I've done.
Cheers (Code below):
from glob import glob
import os
import ast
from tkinter import *
files_black = glob(os.path.join('Black', '*.txt'))
files_red = glob(os.path.join('Red', '*.txt'))
files_blue = glob(os.path.join('Blue', '*.txt'))
files_yellow = glob(os.path.join('Yellow', '*.txt'))
files_green = glob(os.path.join('Green', '*.txt'))
files_purple = glob(os.path.join('Purple', '*.txt'))
side_list = ['Black', 'Blue', 'Red', 'Purple', 'Yellow', 'Green']
combats = ['Melee', 'Ranged', 'Ram']
primsecat = ['Primary', 'Secondary', 'Ram']
primsecde = ['Primary', 'Secondary', 'Hull']
files_black_neat = []
files_red_neat = []
files_blue_neat = []
files_yellow_neat = []
files_green_neat = []
files_purple_neat = []
for file_black in files_black:
a = file_black.split('\\')[1]
b = a.split('.txt')[0]
files_black_neat.append(b)
for file_red in files_red:
a = file_red.split('\\')[1]
b = a.split('.txt')[0]
files_red_neat.append(b)
for file_blue in files_blue:
a = file_blue.split('\\')[1]
b = a.split('.txt')[0]
files_blue_neat.append(b)
for file_yellow in files_yellow:
a = file_yellow.split('\\')[1]
b = a.split('.txt')[0]
files_yellow_neat.append(b)
for file_green in files_green:
a = file_green.split('\\')[1]
b = a.split('.txt')[0]
files_green_neat.append(b)
for file_purple in files_purple:
a = file_purple.split('\\')[1]
b = a.split('.txt')[0]
files_purple_neat.append(b)
def allstates():
attackbool = list(attacker.state())
at = []
for i in range(len(attackbool)):
if attackbool[i] == 1:
at.append(side_list[i])
combool = list(combatstyles.state())
c = []
for i in range(len(combool)):
if combool[i] == 1:
c.append(combats[i])
blackbool = list(black.state())
b = []
for i in range(len(blackbool)):
if blackbool[i] == 1:
b.append(files_black[i])
bluebool = list(blue.state())
bl = []
for i in range(len(bluebool)):
if bluebool[i] == 1:
bl.append(files_blue[i])
redbool = list(red.state())
r = []
for i in range(len(redbool)):
if redbool[i] == 1:
r.append(files_red[i])
yellowbool = list(yellow.state())
y = []
for i in range(len(yellowbool)):
if yellowbool[i] == 1:
y.append(files_yellow[i])
purplebool = list(purple.state())
p = []
for i in range(len(purplebool)):
if purplebool[i] == 1:
p.append(files_purple[i])
greenbool = list(green.state())
g = []
for i in range(len(greenbool)):
if greenbool[i] == 1:
g.append(files_green[i])
atprimbool = list(at_primsec.state())
at_ps = []
for i in range(len(atprimbool)):
if atprimbool[i] == 1:
at_ps.append(primsecat[i])
defprimbool = list(def_primsec.state())
def_ps = []
for i in range(len(defprimbool)):
if defprimbool[i] == 1:
def_ps.append(primsecde[i])
charge_size = charge_dist.get()
num_attack = num_attack_entry.get()
num_defend = num_def_entry.get()
if b != []:
if at[0] == 'Black':
filename = b[0]
fin = open(filename, 'r')
txt1b = fin.read()
txt1b = txt1b.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1b = txt1b.split('\n')[0]
txt2b = ast.literal_eval(txt1b)
healtha = txt2b[3]
attackprima = txt2b[4]
attackseca = txt2b[7]
rangedat = txt2b[5]
chargeprima = txt2b[9]
chargeseca = txt2b[10]
defprima = txt2b[11]
defseca = txt2b[12]
shipram = txt2b[2]
mountefsa = txt2b[0]
primefsa = txt2b[6]
secefsa = txt2b[8]
else:
filename = b[0]
fin = open(filename, 'r')
txt1b = fin.read()
txt1b = txt1b.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1b = txt1b.split('\n')[0]
txt2b = ast.literal_eval(txt1b)
healthd = txt2b[3]
attackprimd = txt2b[4]
attacksecd = txt2b[7]
chargeprimd = txt2b[9]
chargesecd = txt2b[10]
defprimd = txt2b[11]
defsecd = txt2b[12]
cover = txt2b[13]
armour = txt2b[14]
shiphealth = txt2b[1]
mountefsd = txt2b[0]
primefsd = txt2b[6]
secefsd = txt2b[8]
else:
nout = 0
if bl != []:
if at[0] == 'Blue':
filename = bl[0]
fin = open(filename, 'r')
txt1bl1 = fin.read()
txt1bl = txt1bl1.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1bl = txt1bl.split('\n')[0]
txt2bl = ast.literal_eval(txt1bl)
healtha = txt2bl[3]
attackprima = txt2bl[4]
attackseca = txt2bl[7]
rangedat = txt2bl[5]
chargeprima = txt2bl[9]
chargeseca = txt2bl[10]
defprima = txt2bl[11]
defseca = txt2bl[12]
shipram = txt2bl[2]
mountefsa = txt2bl[0]
primefsa = txt2bl[6]
secefsa = txt2bl[8]
else:
filename = bl[0]
fin = open(filename, 'r')
txt1bl = fin.read()
txt1bl = txt1bl.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1bl = txt1bl.split('\n')[0]
txt2bl = ast.literal_eval(txt1bl)
healthd = txt2bl[3]
attackprimd = txt2bl[4]
attacksecd = txt2bl[7]
chargeprimd = txt2bl[9]
chargesecd = txt2bl[10]
defprimd = txt2bl[11]
defsecd = txt2bl[12]
cover = txt2bl[13]
armour = txt2bl[14]
shiphealth = txt2bl[1]
mountefsd = txt2bl[0]
primefsd = txt2bl[6]
secefsd = txt2bl[8]
else:
nout = 0
if y != []:
if at[0] == 'Yellow':
filename = y[0]
fin = open(filename, 'r')
txt1y = fin.read()
txt1y = txt1y.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1y = txt1y.split('\n')[0]
txt2y = ast.literal_eval(txt1y)
healtha = txt2y[3]
attackprima = txt2y[4]
attackseca = txt2y[7]
rangedat = txt2y[5]
chargeprima = txt2y[9]
chargeseca = txt2y[10]
defprima = txt2y[11]
defseca = txt2y[12]
shipram = txt2y[2]
mountefsa = txt2y[0]
primefsa = txt2y[6]
secefsa = txt2y[8]
else:
filename = y[0]
fin = open(filename, 'r')
txt1y = fin.read()
txt1y = txt1y.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1y = txt1y.split('\n')[0]
txt2y = ast.literal_eval(txt1y)
healthd = txt2y[3]
attackprimd = txt2y[4]
attacksecd = txt2y[7]
chargeprimd = txt2y[9]
chargesecd = txt2y[10]
defprimd = txt2y[11]
defsecd = txt2y[12]
cover = txt2y[13]
armour = txt2y[14]
shiphealth = txt2y[1]
mountefsd = txt2y[0]
primefsd = txt2y[6]
secefsd = txt2y[8]
else:
nout = 0
if p != []:
if at[0] == 'Purple':
filename = p[0]
fin = open(filename, 'r')
txt1p = fin.read()
txt1p = txt1p.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1p = txt1p.split('\n')[0]
txt2p = ast.literal_eval(txt1p)
healtha = txt2p[3]
attackprima = txt2p[4]
attackseca = txt2p[7]
rangedat = txt2p[5]
chargeprima = txt2p[9]
chargeseca = txt2p[10]
defprima = txt2p[11]
defseca = txt2p[12]
shipram = txt2p[2]
mountefsa = txt2p[0]
primefsa = txt2p[6]
secefsa = txt2p[8]
else:
filename = p[0]
fin = open(filename, 'r')
txt1p = fin.read()
txt1p = txt1p.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1p = txt1p.split('\n')[0]
txt2p = ast.literal_eval(txt1p)
healthd = txt2p[3]
attackprimd = txt2p[4]
attacksecd = txt2p[7]
chargeprimd = txt2p[9]
chargesecd = txt2p[10]
defprimd = txt2p[11]
defsecd = txt2p[12]
cover = txt2p[13]
armour = txt2p[14]
shiphealth = txt2p[1]
mountefsd = txt2p[0]
primefsd = txt2p[6]
secefsd = txt2p[8]
else:
nout = 0
if g != []:
if at[0] == 'Green':
filename = g[0]
fin = open(filename, 'r')
txt1g = fin.read()
txt1g = txt1g.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1g = txt1g.split('\n')[0]
txt2g = ast.literal_eval(txt1g)
healtha = txt2g[3]
attackprima = txt2g[4]
attackseca = txt2g[7]
rangedat = txt2g[5]
chargeprima = txt2g[9]
chargeseca = txt2g[10]
defprima = txt2g[11]
defseca = txt2g[12]
shipram = txt2g[2]
mountefsa = txt2g[0]
primefsa = txt2g[6]
secefsa = txt2g[8]
else:
filename = g[0]
fin = open(filename, 'r')
txt1g = fin.read()
txt1g = txt1g.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1g = txt1g.split('\n')[0]
txt2g = ast.literal_eval(txt1g)
healthd = txt2g[3]
attackprimd = txt2g[4]
attacksecd = txt2g[7]
chargeprimd = txt2g[9]
chargesecd = txt2g[10]
defprimd = txt2g[11]
defsecd = txt2g[12]
cover = txt2g[13]
armour = txt2g[14]
shiphealth = txt2g[1]
mountefsd = txt2g[0]
primefsd = txt2g[6]
secefsd = txt2g[8]
else:
nout = 0
if r != []:
if at[0] == 'Red':
filename = r[0]
fin = open(filename, 'r')
txt1r = fin.read()
txt1r = txt1r.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1r = txt1r.split('\n')[0]
txt2r = ast.literal_eval(txt1r)
healtha = txt2r[3]
attackprima = txt2r[4]
attackseca = txt2r[7]
rangedat = txt2r[5]
chargeprima = txt2r[9]
chargeseca = txt2r[10]
defprima = txt2r[11]
defseca = txt2r[12]
shipram = txt2r[2]
mountefsa = txt2r[0]
primefsa = txt2r[6]
secefsa = txt2r[8]
else:
filename = r[0]
fin = open(filename, 'r')
txt1r = fin.read()
txt1r = txt1r.split('BELOW IS FOR COMBAT CODE ONLY:\n')[1]
txt1r = txt1r.split('\n')[0]
txt2r = ast.literal_eval(txt1r)
healthd = txt2r[3]
attackprimd = txt2r[4]
attacksecd = txt2r[7]
chargeprimd = txt2r[9]
chargesecd = txt2r[10]
defprimd = txt2r[11]
defsecd = txt2r[12]
cover = txt2r[13]
armour = txt2r[14]
shiphealth = txt2r[1]
mountefsd = txt2r[0]
primefsd = txt2r[6]
secefsd = txt2r[8]
else:
nout = 0
def efsmounta(mountefsa):
for mountef in mountefsa:
if mountef == '+10% vs Mounted Units':
cavefb1 = 1.1
infefb1 = 1.0
armefb1 = 1.0
charefb1 = 1.0
return cavefb1, infefb1, armefb1, charefb1
elif mountef == '+20 vs Mounted Units':
cavefb1 = 1.2
infefb1 = 1.0
armefb1 = 1.0
charefb1 = 1.0
return cavefb1, infefb1, armefb1, charefb1
elif mountefsa[0] == '+20 vs Infantry' and mountefsa[1] == '-20% vs Mounted Units':
cavefb1 = 0.8
infefb1 = 1.2
armefb1 = 1.0
charefb1 = 1.0
return cavefb1, infefb1, armefb1, charefb1
else:
cavefb1 = 1.0
infefb1 = 1.0
armefb1 = 1.0
charefb1 = 1.0
return cavefb1, infefb1, armefb1, charefb1
def efsprima(primefsa):
for primef in primefsa:
if primefsa[0] == 'Ignore 1/4 Armour' and primefsa[1] == '+30% vs Mounted Units':
cavefb2 = 0.3
infefb2 = 0.0
armefb2 = -0.25
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif primef == 'Ignore 1/4 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -0.25
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif primef == 'Ignore 1/8 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -(1/8)
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif primef == 'Ignore 1/3 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -(2/3)
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif primef == '+30% vs Cavalry':
cavefb2 = 0.3
infefb2 = 0.0
armefb2 = 0.0
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif primefsa[0] == '+60% vs Mounted Units' and primefsa[1] == '1/2 Enemy Charge Bonus':
cavefb2 = 0.6
infefb2 = 0.0
armefb2 = 0.0
charefb2 = -0.5
return cavefb2, infefb2, armefb2, charefb2
elif primefsa[0] == '+80% vs Mounted Units' and primefsa[1] == 'Ignore Enemy Charge Bonus':
cavefb2 = 0.8
infefb2 = 0.0
armefb2 = 0.0
charefb2 = -1.0
return cavefb2, infefb2, armefb2, charefb2
else:
infefb2 = 0.0
armefb2 = 0.0
cavefb2 = 0.0
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
def efsseca(secefsa):
for secef in secefsa:
if secefsa[0] == 'Ignore 1/4 Armour' and secefsa[1] == '+30% vs Mounted Units':
cavefb2 = 0.3
infefb2 = 0.0
armefb2 = -0.25
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/4 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -0.25
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/8 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -(1/8)
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/3 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -(2/3)
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secef == '+30% vs Cavalry':
cavefb2 = 0.3
infefb2 = 0.0
armefb2 = 0.0
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secefsa[0] == '+60% vs Mounted Units' and secefsa[1] == '1/2 Enemy Charge Bonus':
cavefb2 = 0.6
infefb2 = 0.0
armefb2 = 0.0
charefb2 = -0.5
return cavefb2, infefb2, armefb2, charefb2
elif secefsa[0] == '+80% vs Mounted Units' and secefsa[1] == 'Ignore Enemy Charge Bonus':
cavefb2 = 0.8
infefb2 = 0.0
armefb2 = 0.0
charefb2 = -1
return cavefb2, infefb2, armefb2, charefb2
else:
infefb2 = 0.0
armefb2 = 0.0
cavefb2 = 0.0
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
return cavefb2, infefb2, armefb2, charefb2
def efsmountd(mountefsd):
for mountef in mountefsd:
if mountef == '+10% vs Mounted Units':
cavefb1 = 1.1
infefb1 = 1
armefb1 = 1
charefb1 = 1
return cavefb1, infefb1, armefb1, charefb1
elif mountef == '+20 vs Mounted Units':
cavefb1 = 1.2
infefb1 = 1
armefb1 = 1
charefb1 = 1
return cavefb1, infefb1, armefb1, charefb1
elif mountefsd[0] == '+20 vs Infantry' and mountefsd[1] == '-20% vs Mounted Units':
cavefb1 = 0.8
infefb1 = 1.2
armefb1 = 1
charefb1 = 1
return cavefb1, infefb1, armefb1, charefb1
else:
cavefb1 = 1
infefb1 = 1
armefb1 = 1
charefb1 = 1
return cavefb1, infefb1, armefb1, charefb1
def efsprimd(primefsd):
for primef in primefsd:
if primefsd[0] == 'Ignore 1/4 Armour' and primefsd[1] == '+30% vs Mounted Units':
cavefb2 = 0.3
infefb2 = 0
armefb2 = -0.25
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif primef == 'Ignore 1/4 Armour':
cavefb2 = 0
infefb2 = 0
armefb2 = -0.25
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif primef == 'Ignore 1/8 Armour':
cavefb2 = 0
infefb2 = 0
armefb2 = -(1/8)
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif primef == 'Ignore 1/3 Armour':
cavefb2 = 0
infefb2 = 0
armefb2 = -(2/3)
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif primef == '+30% vs Cavalry':
cavefb2 = 0.3
infefb2 = 0
armefb2 = 0
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif primefsd[0] == '+60% vs Mounted Units' and primefsd[1] == '1/2 Enemy Charge Bonus':
cavefb2 = 0.6
infefb2 = 0
armefb2 = 0
charefb2 = -0.5
return cavefb2, infefb2, armefb2, charefb2
elif primefsa[0] == '+80% vs Mounted Units' and primefsa[1] == 'Ignore Enemy Charge Bonus':
cavefb2 = 0.8
infefb2 = 0
armefb2 = 0
charefb2 = -1
return cavefb2, infefb2, armefb2, charefb2
else:
infefb2 = 0
armefb2 = 0
cavefb2 = 0
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
def efssecd(secefsd):
for secef in secefsd:
if secefsd[0] == 'Ignore 1/4 Armour' and secefsd[1] == '+30% vs Mounted Units':
cavefb2 = 0.3
infefb2 = 0
armefb2 = -0.25
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/4 Armour':
cavefb2 = 0
infefb2 = 0
armefb2 = -0.25
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/8 Armour':
cavefb2 = 0
infefb2 = 0
armefb2 = -(1/8)
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/3 Armour':
cavefb2 = 0
infefb2 = 0
armefb2 = -(2/3)
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif secef == '+30% vs Cavalry':
cavefb2 = 0.3
infefb2 = 0
armefb2 = 0
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
elif secefsd[0] == '+60% vs Mounted Units' and secefsd[1] == '1/2 Enemy Charge Bonus':
cavefb2 = 0.6
infefb2 = 0
armefb2 = 0
charefb2 = -0.5
return cavefb2, infefb2, armefb2, charefb2
elif secefsd[0] == '+80% vs Mounted Units' and secefsd[1] == 'Ignore Enemy Charge Bonus':
cavefb2 = 0.8
infefb2 = 0
armefb2 = 0
charefb2 = -1
return cavefb2, infefb2, armefb2, charefb2
else:
infefb2 = 0
armefb2 = 0
cavefb2 = 0
charefb2 = 0
return cavefb2, infefb2, armefb2, charefb2
cavef1a = efsmounta(mountefsa)[0] + efsprima(primefsa)[0]
cavef2a = efsmounta(mountefsa)[0] + efsseca(secefsa)[0]
infef1a = efsmounta(mountefsa)[1] + efsprima(primefsa)[1]
infef2a = efsmounta(mountefsa)[1] + efsseca(secefsa)[1]
armef1a = efsmounta(mountefsa)[2] + efsprima(primefsa)[2]
armef2a = efsmounta(mountefsa)[2] + efsseca(secefsa)[2]
charef1a = efsmounta(mountefsa)[3] + efsprima(primefsa)[3]
charef2a = efsmounta(mountefsa)[3] + efsseca(secefsa)[3]
cavef1d = efsmountd(mountefsd)[0] + efsprimd(primefsd)[0]
cavef2d = efsmountd(mountefsd)[0] + efssecd(secefsd)[0]
infef1d = efsmountd(mountefsd)[1] + efsprimd(primefsd)[1]
infef2d = efsmountd(mountefsd)[1] + efssecd(secefsd)[1]
armef1d = efsmountd(mountefsd)[2] + efsprimd(primefsd)[2]
armef2d = efsmountd(mountefsd)[2] + efssecd(secefsd)[2]
charef1d = efsmountd(mountefsd)[3] + efsprimd(primefsd)[3]
charef2d = efsmountd(mountefsd)[3] + efssecd(secefsd)[3]
print(attackprima, attackprimd)
Button(root, text='Fight!', command=allstates).pack(side=RIGHT)
root.mainloop()

Right, so I found the problem myself. What I actually did above was that if either mountefsa/mountefsd/primefsa/primefsd/secefsa/secefsd were equal to [] (ie, there were none), the definitions afterwards searched this empty list and assigned values from that empty list, meaning that when I referenced those values, I returned a None Type. Here is an example definition done correctly:
def efssecd(secefsd):
if secefsd != []:
for i in range(len(secefsd)):
secef = secefsd[i]
print(secef)
if secefsd[0] == 'Ignore 1/4 Armour' and secefsd[1] == '+30% vs Mounted Units':
cavefb2 = 0.3
infefb2 = 0.0
armefb2 = -0.25
charefb2 = 0.0
print(cavefb2, infefb2, armefb2, charefb2)
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/4 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -0.25
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/8 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -(1/8)
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secef == 'Ignore 1/3 Armour':
cavefb2 = 0.0
infefb2 = 0.0
armefb2 = -(2/3)
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secef == '+30% vs Cavalry':
cavefb2 = 0.3
infefb2 = 0.0
armefb2 = 0.0
charefb2 = 0.0
return cavefb2, infefb2, armefb2, charefb2
elif secefsd[0] == '+60% vs Mounted Units' and secefsd[1] == '1/2 Enemy Charge Bonus':
cavefb2 = 0.6
infefb2 = 0.0
armefb2 = 0.0
charefb2 = -0.5
return cavefb2, infefb2, armefb2, charefb2
elif secefsd[0] == '+80% vs Mounted Units' and secefsd[1] == 'Ignore Enemy Charge Bonus':
cavefb2 = 0.8
infefb2 = 0.0
armefb2 = 0.0
charefb2 = -1
return cavefb2, infefb2, armefb2, charefb2
else:
infefb2 = 0.0
armefb2 = 0.0
cavefb2 = 0.0
charefb2 = 0.0
print(cavefb2, infefb2, armefb2, charefb2)
return cavefb2, infefb2, armefb2, charefb2
else:
infefb2 = 0.0
armefb2 = 0.0
cavefb2 = 0.0
charefb2 = 0.0
print(cavefb2, infefb2, armefb2, charefb2)
return cavefb2, infefb2, armefb2, charefb2

Related

Why is the dictionary not translated with Flask-Babel

I am writing a website in Flask. I use Flask-Babel for translation into different languages. I use lazy_gettext to translate dictionary values. When changing the language on the site, all phrases and sentences that I wrapped should be translated. Everything is translated besides the words that are wrapped in this mqtt.py file in the MgttTOAA class. Tell me what the problem might be or suggest some other translation option. Thanks
# mqtt.py
from app import socketio, app
from flask import request
from flask_mqtt import Mqtt
from flask_babel import lazy_gettext as _l
from app.tasks import SchedulerTask
import json
import copy
import logging
mqtt = Mqtt(app)
logger = logging.getLogger('flask.flask_mqtt')
logger.disabled = True
class MqttTOAA(object):
# топик контроля воротами забора, топик данных воротами забора, топик контроля гаражными, топик данных гаражными
type_topic = ["/Control", "/Data"]
m_request_state = {"comm": "3"} # запрос на получение статуса ворот
m_start = {"Gate": "Start"} # сообщение для открытия/закрытия ворот
m_stop = {"Gate": "Stop"} # сообщение для остановки ворот
qos_request = 1
qos_sub = 2
struct_state_devices = None # словарь информации о состоянии устройств
# состояние ворот: действие
# действие: статус, отображаемый на странице
# поля: текст кнопки, отображаемый статус, код устройства
# статус ворот # предыдущая позиция ворот и отметка о том, были ли отсановленны
dict_gate = {"dict_state_button": {'con_Clos': _l(u'Открыть'),
'con_Open': _l(u'Закрыть'),
"fl_OpenClos": (_l(u'Продолжить'),
_l(u'Остановить'),
_l(u'Прервать'))},
"dict_state_text": {_l(u'Открыть'): _l(u'закрыты'),
_l(u'Закрыть'): _l(u'открыты'),
_l(u'Продолжить'): _l(u'остановлены'),
_l(u'Прервать'): _l(u'закрываются'),
_l(u'Остановить'): (_l(u'открываются'),
_l(u'закрываются'),
_l(u'в движении'))},
"dict_type_element": {"button": u'', "text": u'', "device_code": u'', },
"state_gate": {},
"position": {"state": u'', "stop": False},
"reverse": False,
}
close_msg = _l(u'закрываются')
open_msg = _l(u'открываются')
POOL_TIME = 2 # Интервал отправки запроса брокеру
end_publish = None
devices = None
app_now = None
schedulers_list = list()
sch_task = None
code_list = list()
def __init__(self, devices, app):
mqtt._connect()
self.devices = devices
self.app_now = app
self.sch_task = SchedulerTask()
self.create_devices_dict()
self.handle_mqtt_connect()
self.mqtt_onmessage = mqtt.on_message()(self._handle_mqtt_message)
self.mqtt_onlog = mqtt.on_log()(self._handle_logging)
self.socketio_error = socketio.on_error()(self._handle_error)
self.handle_change_state = socketio.on('change_state')(self._handle_change_state)
self.handle_unsubscribe_all = socketio.on('unsubscribe_all')(self._handle_unsubscribe_all)
# ожидание подключения к брокеру,
# затем подписка на топик и запуск потока для постоянной отсылки сообщений в топик Control
def handle_mqtt_connect(self):
task = None
for dev in self.devices:
if dev.device_code not in self.code_list: # запущен ли уже поток с таким кодом
mqtt.subscribe("BK" + dev.device_code + self.type_topic[1], self.qos_sub)
self.code_list.append(dev.device_code)
task = self.sch_task.add_scheduler_publish(dev.device_code,
mqtt,
"BK" + dev.device_code +
self.type_topic[0],
self.m_request_state,
self.qos_request,
self.POOL_TIME)
if task is not None:
self.schedulers_list.append(task)
if len(self.schedulers_list) > 0:
self.sch_task.start_schedulers()
self.code_list.clear()
# обработчик ошибок
#staticmethod
def _handle_error():
print(request.event["message"]) # "my error event"
print(request.event["args"]) # (data,)
# отмена подписки на топик
#staticmethod
def _handle_unsubscribe_all():
mqtt.unsubscribe_all()
# функция изменения состояния ворот по нажатию
def _handle_change_state(self, code):
print(code)
# print(self.struct_state_devices[code])
message = None
if code is not None:
try:
type_g = self.struct_state_devices[code]["state_gate"]
if type_g["fl_OpenClos"] == 1: # ворота в движении -> остановка
message = self.m_stop
else:
if self.struct_state_devices[code]["reverse"] is True:
# остановились и двигаются в обратном направлении -> остановка
if self.struct_state_devices[code]["position"]["state"] == self.close_msg:
message = self.m_stop
self.struct_state_devices[code]["position"]["state"] = self.open_msg
else:
message = self.m_start
else: # ворота остановленны -> продолжение движения
message = self.m_start
print("Msg:" + str(message))
except Exception as ex:
print(ex)
if message is not None:
mqtt.publish("BK" + code + self.type_topic[0], json.dumps(message), self.qos_request)
else:
print("Error change state " + code)
# обработка принятых сообщений от топика, на который подписан
def _handle_mqtt_message(self, client, userdata, message):
# print("Get message")
data = dict(
topic=message.topic,
payload=message.payload.decode(),
qos=message.qos,
)
try:
data = json.loads(data['payload'])
self.gate_msg(data)
except Exception as ex:
print("Exception: " + str(ex))
# логирование
#staticmethod
def _handle_logging(self, client, userdata, level, buf):
print(level, buf)
pass
# создание словаря устройств
def create_devices_dict(self):
if self.struct_state_devices is None:
self.struct_state_devices = dict()
for dev in self.devices:
self.struct_state_devices[dev.device_code] = self.dict_gate.copy() # добавление словаря устройства
if dev.typedev.reverse:
self.struct_state_devices[dev.device_code]['reverse'] = True
# функция измения состояния гаражных ворот (с реверсом)
def gate_msg(self, data):
k = ""
code = data["esp_id"][2:]
dict_dev = copy.deepcopy(self.struct_state_devices[code])
dict_dev["state_gate"] = data.copy()
try:
if dict_dev["state_gate"]["con_Clos"] == 0: # ворота закрыты
# print("1")
k = "con_Clos"
dict_dev["position"]["state"] = k
dict_dev["position"]["stop"] = False
elif dict_dev["state_gate"]["con_Open"] == 0: # ворота открыты
# print("2")
k = "con_Open"
dict_dev["position"]["state"] = k
dict_dev["position"]["stop"] = False
elif dict_dev["state_gate"]["fl_OpenClos"] == 0: # ворота остановленны/движение прервано
# print("3")
k = "fl_OpenClos"
# обратный ход ворот при закрытии
if dict_dev["position"]["state"] == self.close_msg and dict_dev["reverse"] is True:
# print("4")
k1 = 1
k2 = 0
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
dict_dev["position"]["stop"] = False
else:
# print("5")
k1 = 0
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]]
dict_dev["position"]["stop"] = True
elif dict_dev["state_gate"]["fl_OpenClos"] == 1: # ворота в движении
# print("6")
k = "fl_OpenClos"
# Если невозможно определить открываются или закрываются ворота
if len(dict_dev["position"]["state"]) == 0:
# print("7")
k1 = 1
k2 = 2
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
# определение - закрываются или открываются ворота
elif dict_dev["position"]["state"] == "con_Clos" or \
dict_dev["position"]["state"] == self.open_msg:
if dict_dev["position"]["stop"]:
# print("8")
k1 = 1
k2 = 1
dict_dev["position"]["stop"] = False
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
else:
# print("9")
k1 = 1
k2 = 0
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
elif dict_dev["position"]["state"] == "con_Open" or \
dict_dev["position"]["state"] == self.close_msg:
if dict_dev["reverse"]:
# print("10")
k1 = 2
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]]
else:
if dict_dev["position"]["stop"]:
# print("11")
k1 = 1
k2 = 0
dict_dev["position"]["stop"] = False
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
else:
# print("12")
k1 = 1
k2 = 1
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k][k1]][k2]
if dict_dev["position"]["state"] != dict_dev["dict_type_element"]["text"]:
# print("13")
dict_dev["position"]["state"] = dict_dev["dict_type_element"]["text"]
if k == "fl_OpenClos":
dict_dev["dict_type_element"]["button"] = dict_dev["dict_state_button"][k][k1]
else:
dict_dev["dict_type_element"]["button"] = dict_dev["dict_state_button"][k]
dict_dev["dict_type_element"]["text"] = \
dict_dev["dict_state_text"][dict_dev["dict_state_button"][k]]
except Exception as ex:
print("Exception (gate_msg): " + str(ex))
dict_dev["dict_type_element"]["device_code"] = data["esp_id"][2:]
dict_dev["dict_type_element"]["temp"] = data["temp_1"]
dict_dev["dict_type_element"]["button"] = copy.deepcopy(str(dict_dev["dict_type_element"]["button"]))
dict_dev["dict_type_element"]["text"] = copy.deepcopy(str(dict_dev["dict_type_element"]["text"]))
self.struct_state_devices[code] = copy.deepcopy(dict_dev)
socketio.emit('mqtt_message', data=dict_dev["dict_type_element"])

Retrieving information form several textbox (Template) in Django

**I want to fetch information from course titile & course code textbox ,,,, if title & code both are given or only title /code data will be showed.
Bt, in my code not working when only title are given..
what are the logical mistake..?? My View Code
def search_view(request):
c = 0
d = 0
c_title = ''
c_code = ''
course_Details = ''
course_Details1 = ''
if request.GET.get('Code'):
c_code = request.GET.get("Code")
if request.GET.get('Course_Title'):
c_title = request.GET.get("Course_Title")
if c_code != '':
course_Details = Course.objects.filter(course_code=c_code)
if (course_Details):
c = 1
if c_title != '':
if c == 1:
course_Details1 = course_Details.filter(course_title=c_title)
if (course_Details1):
d = 1
if d == 1:
course_Details = course_Details1
if d == 0:
course_Details = Course.objects.filter(course_title=c_title)
if c == 1 | d == 1:
return render(request, 'index.html', {'course_Details': course_Details})
else:
return render(request, 'index.html')
You need to set d=1 when you query by title only:
def search_view(request):
c = 0
d = 0
c_title = ''
c_code = ''
course_Details = ''
course_Details1 = ''
if request.GET.get('Code'):
c_code = request.GET.get("Code")
if request.GET.get('Course_Title'):
c_title = request.GET.get("Course_Title")
if c_code != '':
course_Details = Course.objects.filter(course_code=c_code)
if (course_Details):
c = 1
if c_title != '':
if c == 1:
course_Details1 = course_Details.filter(course_title=c_title)
if (course_Details1):
d = 1
if d == 1:
course_Details = course_Details1
if d == 0:
course_Details = Course.objects.filter(course_title=c_title)
d = 1
if c == 1 | d == 1:
return render(request, 'index.html', {'course_Details': course_Details})
else:
return render(request, 'index.html')

If statement gives wrong output in query set

I'm getting the incorrect output of a query set when I use request.method == 'POST' and selectedaccesslevel == '#' showing as <QuerySet ['S00009']> when it's written to the database.
I believe I should be using a get since i'm expecting one value, but how do I filter my get on coid = owner.coid.coid and provide the value ?level?
I'm looking for my output for datareducecode to be 'S00009' and not <QuerySet ['S00009']>. How can I accomplish this? Below is my view...
def submitted(request):
owner = User.objects.get (formattedusername=request.user.formattedusername)
checkedlist = request.POST.getlist('report_id')
print (f"checkedlist on submitted:{checkedlist}")
access_request_date = timezone.now()
coid = User.objects.filter(coid = request.user.coid.coid).filter(formattedusername=request.user.formattedusername)
datareducecode = OrgLevel.objects.distinct().filter(coid=request.user.coid.coid)
# facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
# divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
# print(facilitycfo)
# print(divisioncfo)
selectedaccesslevel = request.POST.get('accesslevelid')
print (f"accesslevel:{selectedaccesslevel}")
selectedphi = request.POST.get('phi')
print (f"phi:{selectedphi}")
print (owner.coid.coid)
if request.method == 'POST' and selectedaccesslevel == '3':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('slevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '4':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('blevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '5':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('rlevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '6':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('dlevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '7':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('f"Z{Coid}"', flat = True)
print (datareducecode)
else:
datareducecode = 'No Match on Coid'
print (datareducecode)
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = access_request_date, datareducecode = datareducecode )
requestsave.save()
# print (datareducecode)
return JsonResponse({'is_success':True})
So this seems to do the trick:
list(datareducecode)[0]

How to add a widget in QmdiArea in pyqt?

I'm trying to add a window to Qmdi area when user clicks a button inside another widget in Qmdi area.
Codes i have written so far is:
from __future__ import print_function
from PyQt4.QtGui import *
import csv
import subprocess
import sys
from PyQt4 import QtGui
from PyQt4.QtCore import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.lee = QLineEdit()
self.lee.setObjectName("hosta")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("inject")
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.lee)
layout.addWidget(self.pb)
self.setLayout(layout)
self.connect(self.pb, SIGNAL("clicked()"), self.button_click)
self.setWindowTitle("Stuck-at-0")
def button_click(self):
# shost is a QString object
n = int(self.le.text())
line = str(self.lee.text())
print(n, line)
with open('main.txt', 'r') as files:
# read a list of lines into data
data = files.readlines()
# now inject fault in nth level, note that you have to add a newline
print
data[1]
if line in data[0]:
data.insert(n + 1, '0' + ',' + line + '\n')
# and write everything back
with open('main.txt', 'w') as files:
files.writelines(data)
res = subprocess.call(['python stuck.py'], shell=True)
res = subprocess.call(['python comp.py'], shell=True)
class UserWindow(QtGui.QMainWindow):
def __init__(self):
super(UserWindow, self).__init__()
self.ctr_frame = QtGui.QWidget()
self.specTable = QtGui.QTableView()
self.specModel = QtGui.QStandardItemModel(self)
self.specList = self.createSpecTable()
self.initUI()
def specData(self):
with open('tests.csv', 'rb') as csvInput:
for row in csv.reader(csvInput):
if row > 0:
items = [QtGui.QStandardItem(field) for field in row]
self.specModel.appendRow(items)
def createSpecTable(self):
# This is a test header - different from what is needed
specHdr = ['Test', 'Date', 'Time', 'Type']
self.specData()
specM = specTableModel(self.specModel, specHdr, self)
self.specTable.setModel(specM)
self.specTable.setShowGrid(False)
v_head = self.specTable.verticalHeader()
v_head.setVisible(False)
h_head = self.specTable.horizontalHeader()
h_head.setStretchLastSection(True)
self.specTable.sortByColumn(3, Qt.DescendingOrder)
return self.specTable
def initUI(self):
self.specList.setModel(self.specModel)
p_grid = QtGui.QGridLayout()
p_grid.setSpacing(5)
p_grid.addWidget(self.specList, 2, 5, 13, 50)
self.ctr_frame.setLayout(p_grid)
self.setCentralWidget(self.ctr_frame)
self.statusBar()
bar = self.menuBar()
menu_item1 = bar.addMenu("Circuit Details")
fault_inject = bar.addMenu("Fault Injection")
fault_inject_sa = fault_inject.addMenu("Stuck-at Fault")
fault_inject_sa.addAction("Stuck-at-0")
fault_inject_sa.addAction("Stuck-at-1")
fault_inject_bridge = fault_inject.addMenu("Bridging Fault")
fault_inject_bridge.addAction("Bridging-OR")
fault_inject_bridge.addAction("Bridging-AND")
fault_inject_cross = fault_inject.addMenu("Crosspoint Fault")
fault_inject_cross.addAction("Crosspoint-Appearance")
fault_inject_cross.addAction("Crosspoint-Dissappearence")
fault_inject_mgf = fault_inject.addMenu("Missing Gate Fault")
fault_inject_mgf.addAction("Single-MGF")
fault_inject_mgf.addAction("Multiple-MGF")
fault_inject_mgf.addAction("Repeated-MGF")
fault_inject_mgf.addAction("Partial-MGF")
self.setWindowTitle('Truth Table')
fault_inject.triggered[QAction].connect(self.fault_injection)
def fault_injection(self, q):
print("triggered")
if q.text() == "Stuck-at-0":
print(q.text())
exx = Form()
self.mdi.addSubWindow(exx)
exx.show()
if q.text() == "Stuck-at-1":
print(q.text())
if q.text() == "Bridging-OR":
print(q.text())
if q.text() == "Bridging-AND":
print(q.text())
if q.text() == "Crosspoint-Appearance":
print(q.text())
if q.text() == "Crosspoint-Dissappearence":
print(q.text())
if q.text() == "Single-MGF":
print(q.text())
if q.text() == "Multiple-MGF":
print(q.text())
if q.text() == "Repeated-MGF":
print(q.text())
if q.text() == "Partial-MGF":
print(q.text())
class specTableModel(QAbstractTableModel):
def __init__(self, datain, headerData, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.arrayData = datain
self.headerData = headerData
def rowCount(self, parent):
return 0
def columnCount(self, parent):
return 0
def data(self, index, role):
if not index.isValid():
return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.arraydata[index.row()][index.column()])
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.headerdata[col]
return None
class MainWindow(QMainWindow):
count = 0
filename = 0
def test_display(self,q):
self.mdi.tileSubWindows()
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
menu_item1 = bar.addMenu("About Tool")
menu_item_tool = menu_item1.addMenu("User Manual")
menu_item_example = menu_item1.addMenu("Example and Demos")
menu_item2 = bar.addMenu("Reversible Computing")
menu_item_rc = menu_item2.addMenu("RC vs Conventional")
menu_item_rcg = menu_item2.addMenu("RC Gates")
menu_item_rcp = menu_item2.addMenu("Properties of RC")
menu_item_rcl = menu_item2.addMenu("RC Gate Libraries")
menu_item = bar.addMenu("Benchmark Circuits")
menu_item_gate = menu_item.addMenu("Functions")
menu_item_realize = menu_item.addMenu("Realization Library")
menu_item_nct = menu_item_realize.addMenu("NCT")
menu_item_gt = menu_item_realize.addMenu("GT")
menu_item_nctf = menu_item_realize.addMenu("NCTF")
menu_item_gf = menu_item_realize.addMenu("GF")
menu_item_4b1_5g = menu_item_gate.addMenu("4b1_5g")
menu_item_4b1_5g.addAction("4b1_5g_1")
menu_item_4b1_5g.addAction("4b1_5g_2")
menu_item_4b1_5g.addAction("4b1_5g_3")
menu_item_4b1_5g.addAction("4b1_5g_4")
menu_item_4b1_5g.addAction("4b1_5g_5")
menu_item_adder = menu_item_gate.addMenu("Adders")
menu_item_adder.addAction("1bitadder(rd32)")
menu_item_adder.addAction("5bitadder")
menu_item_adder.addAction("8bitadder")
menu_item_div_checker = menu_item_gate.addMenu("Divisiblity Checkers")
menu_item_div_checker.addAction("4mod5")
menu_item_div_checker.addAction("5mod5")
menu_item_cyclic = menu_item_gate.addMenu("Cycle Functions")
menu_item_cyclic.addAction("cycle10_2")
menu_item_cyclic.addAction("cycle17_3")
menu_item_galois = menu_item_gate.addMenu("Galois Field Multipliers")
menu_item_galois.addAction("gf2^3mult")
menu_item_galois.addAction("gf2^4mult")
menu_item_galois.addAction("gf2^5mult")
menu_item_galois.addAction("gf2^6mult")
menu_item_galois.addAction("gf2^7mult")
menu_item_galois.addAction("gf2^8mult")
menu_item_galois.addAction("gf2^9mult")
menu_item_galois.addAction("gf2^10mult")
menu_item_galois.addAction("gf2^11mult")
menu_item_galois.addAction("gf2^12mult")
menu_item_galois.addAction("gf2^13mult")
menu_item_galois.addAction("gf2^14mult")
menu_item_galois.addAction("gf2^15mult")
menu_item_galois.addAction("gf2^16mult")
menu_item_galois.addAction("gf2^17mult")
menu_item_galois.addAction("gf2^18mult")
menu_item_galois.addAction("gf2^19mult")
menu_item_galois.addAction("gf2^20mult")
menu_item_galois.addAction("gf2^32mult")
menu_item_galois.addAction("gf2^50mult")
menu_item_galois.addAction("gf2^64mult")
menu_item_galois.addAction("gf2^100mult")
menu_item_galois.addAction("gf2^127mult")
menu_item_galois.addAction("gf2^128mult")
menu_item_galois.addAction("gf2^256mult")
menu_item_galois.addAction("gf2^512mult")
menu_item_hamming = menu_item_gate.addMenu("Hamming Code Functions")
menu_item_hamming.addAction("ham3")
menu_item_hamming.addAction("ham7")
menu_item_hamming.addAction("ham15")
menu_item_hbw = menu_item_gate.addMenu("Hidden Weight Coding Functions")
menu_item_hbw.addAction("hbw4")
menu_item_hbw.addAction("hbw5")
menu_item_hbw.addAction("hbw6")
menu_item_hbw.addAction("hbw7")
menu_item_hbw.addAction("hbw8")
menu_item_hbw.addAction("hbw9")
menu_item_hbw.addAction("hbw10")
menu_item_hbw.addAction("hbw11")
menu_item_hbw.addAction("hbw12")
menu_item_hbw.addAction("hbw13")
menu_item_hbw.addAction("hbw14")
menu_item_hbw.addAction("hbw15")
menu_item_hbw.addAction("hbw16")
menu_item_hbw.addAction("hbw20")
menu_item_hbw.addAction("hbw50")
menu_item_hbw.addAction("hbw100")
menu_item_hbw.addAction("hbw200")
menu_item_hbw.addAction("hbw500")
menu_item_hbw.addAction("hbw1000")
menu_item_mdd = menu_item_gate.addMenu("MDD Worst Case")
menu_item_mdd.addAction("3_17.tfc")
menu_item_mdd.addAction("4_49")
menu_item_modular = menu_item_gate.addMenu("Modula Adders")
menu_item_modular.addAction("mod5adder")
menu_item_modular.addAction("mod1024adder")
menu_item_modular.addAction("mod1048576adder")
menu_item_prime = menu_item_gate.addMenu("N-th Prime")
menu_item_prime.addAction("nth_prime3_inc")
menu_item_prime.addAction("nth_prim4_inc")
menu_item_prime.addAction("nth_prime5_inc")
menu_item_prime.addAction("nth_prime6_inc")
menu_item_prime.addAction("nth_prime7_inc")
menu_item_prime.addAction("nth_prime8_inc")
menu_item_prime.addAction("nth_prime9_inc")
menu_item_prime.addAction("nth_prime10_inc")
menu_item_prime.addAction("nth_prime11_inc")
menu_item_prime.addAction("nth_prime12_inc")
menu_item_prime.addAction("nth_prime13_inc")
menu_item_prime.addAction("nth_prime14_inc")
menu_item_prime.addAction("nth_prime15_inc")
menu_item_prime.addAction("nth_prime16-inc")
menu_item_permanent = menu_item_gate.addMenu("Permanent")
menu_item_permanent.addAction("permanent1x1")
menu_item_permanent.addAction("permanent2x2")
menu_item_permanent.addAction("permanent3x3")
menu_item_permanent.addAction("permanent4x4")
menu_item_rd = menu_item_gate.addMenu("RD-Input Weight functions")
menu_item_rd.addAction("rd53")
menu_item_rd.addAction("rd73")
menu_item_rd.addAction("rd84")
menu_item_sym = menu_item_gate.addMenu("Symmetric Functions")
menu_item_sym.addAction("6sym")
menu_item_sym.addAction("9sym")
menu_item_oth = menu_item_gate.addMenu("Others")
menu_item_oth.addAction("2_4dec")
menu_item_oth.addAction("2of5")
menu_item_oth.addAction("xor5")
self.setWindowTitle("Reversible Fault Testing")
menu_item.triggered[QAction].connect(self.truth_table_gen)
def windowaction(self, q):
print("triggered")
print(q.text())
if "New" == "New":
MainWindow.count += 1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("tst")
self.mdi.addSubWindow(sub)
sub.show()
# truth table display widget
def truth_table_gen(self, q):
MainWindow.count += 1
MainWindow.filename = q.text()
to_readfile = open(q.text(), 'r')
try:
reading_file = to_readfile.read()
writefile = open('a.tfc', 'w')
try:
writefile.write(reading_file)
finally:
writefile.close()
finally:
to_readfile.close()
subprocess.call(['python truth_gen.py'], shell=True)
exx = UserWindow()
self.mdi.addSubWindow(exx)
exx.show()
self.mdi.tileSubWindows()
def main():
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
#ex.resize(1366, 750)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
when i click on button inside the Qmdi area widget, the code crashes.

How to use timefield__week_day__lt?

I need to use the following sentence:
qs = FamilyActivity.objects.all()
qs = qs.filter(Q(end_time__week_day__lt = F('start_time__week_day')) or Q(F('end_time')- F('start_time')>=timedelta(days=5)) or Q(end_time__week_time__gte=6))
But I can't do it. I want to search the future including weekend activities. Cannot the __week_day__lt not be used?
My models.py :
class FamilyActivity(models.Model):
org = models.ForeignKey(Org)
name = models.CharField(verbose_name=_('name'), max_length=200)
start_time = models.DateTimeField(verbose_name=_('start_time'))
end_time = models.DateTimeField(verbose_name=_('end_time'))
cost = models.CharField(verbose_name=_('cost'), max_length=4000)
My views.py :
def search_fa_Map(request, cat=''):
qs = FamilyActivity.objects.all()
if cat != '':
cat_ids = cat.split("-")
try :
if(len(cat_ids) >= 6):
fa_district_id = int(cat_ids[0])
fa_time_id = int(cat_ids[1])
fa_type_id = int(cat_ids[2])
fa_age_id = int(cat_ids[3])
fa_cost_id = int(cat_ids[4])
fa_state_id = int(cat_ids[5])
fa_block_id = 0
if(len(cat_ids) >= 7):
fa_block_id = int(cat_ids[6])
if fa_time_id != 0:
now = datetime.datetime.now()
oneday = datetime.timedelta(days=1)
if fa_time_id == 45:#today
qs = qs.filter(Q(start_time__lte=now,end_time__gte=now))
elif fa_time_id == 46:#weekend
qs = qs.filter(Q(end_time__week_day__lt = F('start_time__week_day')) or Q(F('end_time')-F('start_time')>=timedelta(days=5)) or Q(end_time__week_time__gte=6))
I only want to the following sentence can working.
qs = qs.filter(Q(end_time__week_day__lt = F('start_time__week_day')) or Q(F('end_time')-F('start_time')>=timedelta(days=5)) or Q(end_time__week_time__gte=6))
or is the wrong operator. You want |.