when i try to run the program, at the end its gives an error saying 'unexpected eof while parsing' how can i fix? - eoferror

def main():
randOperation = Randomchoice(operation)
while True:
try:
randOperation()
randOperation = choice(operation)
userAns=int(input("Answer: "))
if userAns == answers:
print("Correct!" + "\n")
score = score + 1
NumOfTries =NumOfTries + 1
else:
print("Incorrect!" + "\n")
NumOfTries = NumOfTries + 1 #here is where the issue is

Related

User input in panda, Can't stop the loop

Please see my below code, I'm trying to use user input to select specific rows within a dataframe. I'm not sure if it's my loop that is causing the issues? As when I run the code outside of the function the code seems to work. Any help would be great.
Thanks
def option3():
print("---------------------------")
print("please select from the following options")
print(Ndata[" workclass"].unique())
print("---------------------------")
loop3 = True
while loop3:
print("---------------------------")
Op1 = input('Please enter first working class: ')
Op2 = input('Please enter second working class: ')
print("Options selected ", Op1, "&", Op2)
print("---------------------------")
if Op1 and Op2 in Ndata[" workclass"]:
loop3 = False
sub = Ndata.loc[Ndata[" workclass"].isin([Op1, Op2])]
print("---------------------------")
print("PLease select frome the following")
print("[1] Most educated countries ")
print("[2] Marital status ")
print("---------------------------")
Op3 = int(input("PLease enter 1 or 2 : "))
loop4 = True
while loop4:
if Op3 == 1 or 2 :
loop4 = False
else:
print('PLease select 1 or 2')
else:
print("Please check", Op1, "&", Op2, " are in the working class")
print(Ndata[" workclass"].unique())

Trying to do a gaussian bell in Scilab

I'm trying to do a Gaussian bell using the data I am obtaining from a matrix but everytime I try to run the program I obtain this message:
"Error: syntax error, unexpected identifier, expecting end"
The data used to obtain the gaussina bell is a matrix which includes the last point of every n displacements, which are the last position of a particle. I want to know if there is an easier way to obtain the gaussian bell in scilab because I have to also do a fit with an histogram using the same data.
function bla7()
t=4000
n=1000
l=0.067
p=%pi*2
w1=zeros(t,1);
w2=zeros(t,1);
for I=1:t
a=(grand(n,1,"unf",0,p));
x=l*cos(a)
y=l*sin(a)
z1=zeros(n,1);
z2=zeros(n,1);
for i=2:n
z1(i)=z1(i-1)+x(i);
z2(i)=z2(i-1)+y(i);
end
w1(I)=z1($)
w2(I)=z2($)
end
n=10000
w10=zeros(t,1);
w20=zeros(t,1);
for I=1:t
a=(grand(n,1,"unf",0,p));
x=l*cos(a)
y=l*sin(a)
z1=zeros(n,1);
z2=zeros(n,1);
for i=2:n
z1(i)=z1(i-1)+x(i);
z2(i)=z2(i-1)+y(i);
end
w10(I)=z1($)
w20(I)=z2($)
end
n=100
w100=zeros(t,1);
w200=zeros(t,1);
for I=1:t
a=(grand(n,1,"unf",0,p));
x=l*cos(a)
y=l*sin(a)
z1=zeros(n,1);
z2=zeros(n,1);
for i=2:n
z1(i)=z1(i-1)+x(i);
z2(i)=z2(i-1)+y(i);
end
w100(I)=z1($)
w200(I)=z2($)
end
k=70
v=12/k
c1=zeros(k,1)
for r=1:t
c=w1(r)
m=-6+v
n=-6
for g=1:k
if (c<m & c>=n) then
c1(g)=c1(g)+1
m=m+v
n=n+v
else
m=m+v
n=n+v
end
end
end
c2=zeros(k,1)
c2(1)=-6+(6/k)
for b=2:k
c2(b)=c2(b-1)+v
end
y = stdev(w1)
normal1=zeros(k,1)
normal2=zeros(k,1)
bb=-6
bc=-6+v
for wa=1:k
bd=(bb+bc)/2
gauss1=(1/(y*sqrt(2*%pi)))exp(-0.5(bb/y)^2)
gauss2=(1/(y*sqrt(2*%pi)))exp(-0.5(bc/y)^2)
gauss3=(1/(y*sqrt(2*%pi)))exp(-0.5(bd/y)^2)
gauss4=((bc-bb)/6)*(gauss1+gauss2+4*gauss3)
bb=bb+v
bc=bc+v
normal2(wa,1)=gauss4
end
normal3=normal2*4000
k=100
v=24/k
c10=zeros(k,1)
for r=1:t
c=w10(r)
m=-12+v
n=-12
for g=1:k
if (c<m & c>=n) then
c10(g)=c10(g)+1
m=m+v
n=n+v
else
m=m+v
n=n+v
end
end
end
c20=zeros(k,1)
c20(1)=-12+(12/k)
for b=2:k
c20(b)=c20(b-1)+v
end
y = stdev(w10)
normal10=zeros(k,1)
normal20=zeros(k,1)
bb=-12
bc=-12+v
for wa=1:k
bd=(bb+bc)/2
gauss10=(1/(y*sqrt(2*%pi)))exp(-0.5(bb/y)^2)
gauss20=(1/(y*sqrt(2*%pi)))exp(-0.5(bc/y)^2)
gauss30=(1/(y*sqrt(2*%pi)))exp(-0.5(bd/y)^2)
gauss40=((bc-bb)/6)*(gauss10+gauss20+4*gauss30)
bb=bb+v
bc=bc+v
normal20(wa,1)=gauss40
end
normal30=normal20*4000
k=70
v=12/k
c100=zeros(k,1)
for r=1:t
c=w100(r)
m=-6+v
n=-6
for g=1:k
if (c<m & c>=n) then
c100(g)=c100(g)+1
m=m+v
n=n+v
else
m=m+v
n=n+v
end
end
end
c200=zeros(k,1)
c200(1)=-6+(6/k)
for b=2:k
c200(b)=c200(b-1)+v
end
y = stdev(w100)
normal100=zeros(k,1)
normal200=zeros(k,1)
bb=-6
bc=-6+v
for wa=1:k
bd=(bb+bc)/2
gauss100=(1/(y*sqrt(2*%pi)))exp(-0.5(bb/y)^2)
gauss200=(1/(y*sqrt(2*%pi)))exp(-0.5(bc/y)^2)
gauss300=(1/(y*sqrt(2*%pi)))exp(-0.5(bd/y)^2)
gauss400=((bc-bb)/6)*(gauss100+gauss200+4*gauss300)
bb=bb+v
bc=bc+v
normal200(wa,1)=gauss400
end
normal300=normal200*4000
bar(c20,c10,1.0,'white')
plot(c20, normal30, 'b-')
bar(c2,c1,1.0,'white')
plot(c2, normal3, 'r-')
bar(c200,c100,1.0,'white')
plot(c200, normal300, 'm-')
poly1.thickness=3;
xlabel(["x / um"]);
ylabel("molecules");
gcf().axes_size=[500,500]
a=gca();
a.zoom_box=[-12,12;0,600];
a.font_size=4;
a.labels_font_size=5;
a.x_label.font_size = 5;
a.y_label.font_size = 5;
ticks = a.x_ticks
ticks.labels =["-12";"-10";"-8";"-6";"-4";"-2";"0";"2";"4";"6";"8";"10";"12"]
ticks.locations = [-12;-10;-8;-6;-4;-2;0;2;4;6;8;10;12]
a.x_ticks = ticks
endfunction
Each and every one of your gauss variables are missing the multiplication operator in two places. Check every line at it will run. For example, this:
gauss1=(1/(y*sqrt(2*%pi)))exp(-0.5(bb/y)^2)
should be this:
gauss1=(1/(y*sqrt(2*%pi))) * exp(-0.5 * (bb/y)^2)
As for the Gaussian bell, there is no standard function in Scilab. However, you could define a new function to make things more clear in your case:
function x = myGauss(s,b_)
x = (1/(s*sqrt(2*%pi)))*exp(-0.5*(b_/s)^2)
endfunction
Actually, while we're at it, your whole code is really difficult to read. You should define functions instead of repeating code: it helps clarify what you mean, and if there is a mistake, you need to fix only one place. Also, I personally do not recommend that you enclose everything in a function like bla7() because it makes things harder to debug. Your example could be rewritten like this:
The myGauss function;
A function w_ to calculate w1, w2, w10, w20, w100 and w200;
A function c_ to calculate c1, c2, c10, c20, c100 and c200;
A function normal_ to calculate normal1, normal2, normal10, normal20, normal100 and normal200;
Call all four functions as many times as needed with different inputs for different results.
If you do that, your could will look like this:
function x = myGauss(s,b_)
x = (1 / (s * sqrt(2 * %pi))) * exp(-0.5 * (b_/s)^2);
endfunction
function [w1_,w2_] = w_(t_,l_,n_,p_)
w1_ = zeros(t_,1);
w2_ = zeros(t_,1);
for I = 1 : t_
a = (grand(n_,1,"unf",0,p_));
x = l_ * cos(a);
y = l_ * sin(a);
z1 = zeros(n_,1);
z2 = zeros(n_,1);
for i = 2 : n_
z1(i) = z1(i-1) + x(i);
z2(i) = z2(i-1) + y(i);
end
w1_(I) = z1($);
w2_(I) = z2($);
end
endfunction
function [c1_,c2_] = c_(t_,k_,v_,w1_,x_)
c1_ = zeros(k_,1)
for r = 1 : t_
c = w1_(r);
m = -x_ + v_;
n = -x_;
for g = 1 : k_
if (c < m & c >= n) then
c1_(g) = c1_(g) + 1;
m = m + v_;
n = n + v_;
else
m = m + v_;
n = n + v_;
end
end
end
c2_ = zeros(k_,1);
c2_(1) = -x_ + (x_/k_);
for b = 2 : k_
c2_(b) = c2_(b-1) + v_;
end
endfunction
function [normal1_,normal2_,normal3_] = normal_(k_,bb_,bc_,v_,w1_)
y = stdev(w1_);
normal1_ = zeros(k_,1);
normal2_ = zeros(k_,1);
for wa = 1 : k_
bd_ = (bb_ + bc_) / 2;
gauss1 = myGauss(y,bb_);
gauss2 = myGauss(y,bc_);
gauss3 = myGauss(y,bd_);
gauss4 = ((bc_ - bb_) / 6) * (gauss1 + gauss2 + 4 * gauss3);
bb_ = bb_ + v_;
bc_ = bc_ + v_;
normal2_(wa,1) = gauss4;
end
normal3_ = normal2_ * 4000;
endfunction
t = 4000;
l = 0.067;
p = 2 * %pi;
n = 1000;
k = 70;
v = 12 / k;
x = 6;
bb = -x;
bc = -x + v;
[w1,w2] = w_(t,l,n,p);
[c1,c2] = c_(t,k,v,w1,x);
[normal1,normal2,normal3] = normal_(k,bb,bc,v,w1);
bar(c2,c1,1.0,'white');
plot(c2, normal3, 'r-');
n = 10000;
k = 100;
v = 24 / k;
x = 12;
bb = -x;
bc = -x + v;
[w10,w20] = w_(t,l,n,p);
[c10,c20] = c_(t,k,v,w10,x);
[normal10,normal20,normal30] = normal_(k,bb,bc,v,w10);
bar(c20,c10,1.0,'white');
plot(c20, normal30, 'b-');
n = 100;
k = 70;
v = 12 / k;
x = 6;
bb = -x;
bc = -x + v;
[w100,w200] = w_(t,l,n,p);
[c100,c200] = c_(t,k,v,w100,x);
[normal100,normal200,normal300] = normal_(k,bb,bc,v,w100);
bar(c200,c100,1.0,'white');
plot(c200, normal300, 'm-');
poly1.thickness=3;
xlabel(["x / um"]);
ylabel("molecules");
gcf().axes_size=[500,500]
a=gca();
a.zoom_box=[-12,12;0,600];
a.font_size=4;
a.labels_font_size=5;
a.x_label.font_size = 5;
a.y_label.font_size = 5;
ticks = a.x_ticks
ticks.labels =["-12";"-10";"-8";"-6";"-4";"-2";"0";"2";"4";"6";"8";"10";"12"]
ticks.locations = [-12;-10;-8;-6;-4;-2;0;2;4;6;8;10;12]
a.x_ticks = ticks

Trouble with break statement in While loop

I'm trying to write a program that collects information from the user, then outputs to a text file. The program collects input correctly, as the print statement I inserted tells me, but the break statement doesn't break the loop when the specified value is input, and the output file is never updated. Any suggestions you could give would really help. Thanks!
# 1. Define Greeting:
def greeting():
print("Welcome, user! Please enter the address data, or type 'quit'.")
# 2. Input
def inputData():
name = input("Enter the name: ")
address = input("Enter the address: ")
city = input("Enter the city: ")
state = input("Enter the state: ")
zipCode = input("Enter the zip: ")
phone = input("Enter the phone number: ")
addressData = str(name + ", " + address + ", " +
city + ", " + state + ", "+ zipCode +
", " + phone)
print(addressData)
return(name)
# 3. Write data to text file
def dataWrite():
f.write(addressData + "\n")
# 4. Display the goodbye message:
def goodbye():
print("Have a nice day!")
# 5. Define Main function:
def main():
greeting()
while name != "quit":
inputData()
if name == "quit":
break
else:
dataWrite()
f.close()
goodbye()
main()
def main():
greeting()
while name != "quit":
name = inputData()
if name == "quit":
break
else:
dataWrite()
f.close()
goodbye()
You are not getting the return value of inputData().

How to get a list of failed job from SGE

How do I get a list of (recently) failed jobs (failed=100 or exit_status=137) from the SGE? From the qacct help:
[-j [job_id|job_name|pattern]] list all [matching] jobs
How do I use the pattern? I tried the following, does not work.
qacct -j failed=100
"pattern" in this case refers to a simple globbing expression to match against a job name, e.g. qacct -j 'myjob*'
qacct unfortunately doesn't have the filtration capability you're looking for - it's possible to filter on complex job attributes, but not fundamental ones like exit_status or failed.
You CAN retrieve that information from the SGE accounting file(assuming you have access to it) with just a little work. When SGE finishes a job, it writes out a simple record to $SGE_ROOT/$SGE_CELL/common/accounting - this is the file that qacct reads. You'll want to check the accounting(5) man page on your qmaster for details specific to your GridEngine version, but a job record in your accounting file should more or less look like this:
all.q:myexechost:group:user:myjobstep16:1126971:sge:0:1369755166:1369768897:1369769771:0:0:874:796.564903:30.676336:15788.000000:0:0:0:0:17009:2:0:47987400.000000:34033048:0:0:0:9468:27604:NONE:defaultdepartment:NONE:1:0:827.241239:96.445328:39.111400:-q all.q:0.000000:NONE:237133824.000000:0:0
In this particular record, failed and exit_status are the 12th and 13th fields, respectively. For a quick and dirty "recent failures" list, we can use these along with fields 6(job id) and 11(job end time) like so to reveal any failures in the most recent 100 jobs:
$ cut -d':' -f6,11,12,13 $SGE_ROOT/$SGE_CELL/common/accounting|sort -t':' -k2|tail -100|grep ':100:137'
I wrote a python script to parse the accounting file for failed jobs. You should edit it to your own use.
#!/usr/local/bin/python2.7
import os
from sys import *
import sys
import getopt
import datetime
#Variables
program = "parse_acct.py"
ifile = "/local/cluster/sge/default/common/accounting"
failed = 0
failedswitch = 0
subtime = 0
subtimeswitch = 0
begtime = 0
begtimeswitch = 0
endtime = 0
endtimeswitch = 0
user = 0
userswitch = 0
node = ""
nodeswitch = 0
### Read command line args
try:
myopts, args = getopt.getopt(sys.argv[1:],"i:f:n:t:u:b:e:h")
except getopt.GetoptError:
print program + " -i <input> -u <username> -n <node_name> -f"
sys.exit(2)
###############################
# o == option
# a == argument passed to the o
###############################
for o, a in myopts:
if o == '-f':
failed = a
failedswitch = 1
elif o == '-i':
ifile = a
elif o == '-u':
user = a
userswitch = 1
elif o == '-t':
subtime = a
subtimeswitch = 1
elif o == '-b':
begtime = a
begtimeswitch = 1
elif o == '-e':
endtime = a
endtimeswitch = 1
elif o == '-n':
node = a
nodeswitch = 1
elif o == '-h':
print program + " -i <input> -u <username> -n <node_name> -f"
sys.exit(0)
else:
print("Usage: %s -i <input> -u <username> -n <node_name> -f" % sys.argv[0])
sys.exit(0)
### --- Read line by line and import in to a list of lists --- ###
loi = []
f = open(ifile, "r")
for var in f:
line = var.rstrip().split(":")
if len(line) >= 10:
loi.append(line)
#print line
f.close()
### --- Parse through the list of lists and put a 0 to the beginning if it fails a test --- ###
for i in range(len(loi)):
if failedswitch == 1 and loi[i][11] >= 1: #!= failed:
loi[i][0] = [0]
elif userswitch == 1 and loi[i][3] != user:
loi[i][0] = [0]
elif nodeswitch == 1 and node != loi[i][1]:
loi[i][0] = [0]
# elif nodeswitch == 1 and node not in loi[i][1]:
# loi[i][0] = [0]
# elif nodeswitch == 1 and node not in loi[i][1]:
# loi[i][0] = [0]
# elif nodeswitch == 1 and node not in loi[i][1]:
# loi[i][0] = [0]
# elif nodeswitch == 1 and node not in loi[i][1]:
# loi[i][0] = [0]
### --- Remove all entries that have the "0" at the beginning --- ###
loidedup = [x for x in loi if x[0] != [0]
### --- Print out the files that passed all tests --- ###
for i in range(len(loidedup)):
print "=============================================================="
print "qname " + loidedup[i][0]
print "hostname " + loidedup[i][1]
print "group " + loidedup[i][2]
print "owner " + loidedup[i][3]
print "job_name " + loidedup[i][4]
print "job_number " + loidedup[i][5]
print "account " + loidedup[i][6]
print "priority " + loidedup[i][7]
print "submission_time " + datetime.datetime.fromtimestamp(int(loidedup[i][8])).strftime('%Y-%m-%d %H:%M:%S')
print "start_time " + datetime.datetime.fromtimestamp(int(loidedup[i][9])).strftime('%Y-%m-%d %H:%M:%S')
print "end_time " + datetime.datetime.fromtimestamp(int(loidedup[i][10])).strftime('%Y-%m-%d %H:%M:%S')
print "failed " + loidedup[i][11]
print "exit_status " + loidedup[i][12]
print "ru_wallclock " + loidedup[i][13]
print " ru_utime " + loidedup[i][14]
print " ru_stime " + loidedup[i][15]
print " ru_maxrss " + loidedup[i][16]
print " ru_ixrss " + loidedup[i][17]
print " ru_ismrss " + loidedup[i][18]
print " ru_idrss " + loidedup[i][19]
print " ru_isrss " + loidedup[i][20]
print " ru_minflt " + loidedup[i][21]
print " ru_majflt " + loidedup[i][22]
print " ru_nswap " + loidedup[i][23]
print " ru_inblock " + loidedup[i][24]
print " ru_oublock " + loidedup[i][25]
print " ru_msgsnd " + loidedup[i][26]
print " ru_msgrcv " + loidedup[i][27]
print " ru_nsignals " + loidedup[i][28]
print " ru_nvcsw " + loidedup[i][29]
print " ru_nivcsw " + loidedup[i][30]
print "project " + loidedup[i][31]
print "department " + loidedup[i][32]
print "granted_pe " + loidedup[i][33]
print "slots " + loidedup[i][34]
print "task_number " + loidedup[i][35]
print "cpu " + loidedup[i][36]
print "mem " + loidedup[i][37]
print "io " + loidedup[i][38]
print "category " + loidedup[i][39]
print "iow " + loidedup[i][40]
print "pe_taskid " + loidedup[i][41]
print "maxvmem " + loidedup[i][42]
print "arid " + loidedup[i][43]
print "ar_submission_time " + loidedup[i][44]
# print loidedup[i]

wxPython; passing a value to wx.TextCtrl from another class

I'd like to thank everyone in advance for taking the time to review this question and I'm sure a lot of people get hung up on this at first and I am also a bit new to OOP, I've primarily done vbscripts in the past, so this is a new frontier to me.
My problem is that I need to:
pass a value from one panel to another...
I'm sure its something simple, but my hair is getting grey over this one.
import wx
import win32com.client
class FinanceInfo(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
zbox = wx.BoxSizer(wx.VERTICAL)
self.Description = wx.TextCtrl(self, -1, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(200,204))
zbox.Add(self.Description,0, wx.EXPAND,15)
self.SetSizer(zbox)
class Frame(wx.Frame):
def __init__(self, *args, **kwargs):
super(Frame, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
panel = wx.Panel(self, -1)
box1 = wx.BoxSizer(wx.HORIZONTAL)
box2 = wx.BoxSizer(wx.HORIZONTAL)
box3 = wx.BoxSizer(wx.HORIZONTAL)
box4 = wx.BoxSizer(wx.HORIZONTAL)
box5 = wx.BoxSizer(wx.HORIZONTAL)
all_box = wx.BoxSizer(wx.VERTICAL)
overall = wx.BoxSizer(wx.HORIZONTAL)
nb = wx.Notebook(panel)
page2 = FinanceInfo(nb)
nb.AddPage(page2, "Finance Information")
first = wx.StaticText(panel, label="First Name: ")
last = wx.StaticText(panel, label="Last Name: ")
self.DATA = wx.ListBox(panel, style=wx.LB_SINGLE, size=(100,100))
self.Bind(wx.EVT_LISTBOX, self.OnSelection, id=self.DATA.GetId())
self.CLYa = wx.StaticText(panel, label="")
self.P2Da = wx.StaticText(panel, label="")
self.PLYa = wx.StaticText(panel, label="")
self.FN = wx.TextCtrl(panel, size=(75,-1))
self.LN = wx.TextCtrl(panel, size=(75,-1))
Search = wx.Button(panel, label="Search Patient")
self.Bind(wx.EVT_BUTTON, self.pulldata, id=Search.GetId())
Close = wx.Button(panel, label="Close Viewer")
self.Bind(wx.EVT_BUTTON, self.OnClose, id=Close.GetId())
box1.Add(first, 0, wx.ALL, 5)
box2.Add(last, 0, wx.ALL, 5)
box1.Add(self.FN, 1, wx.ALL, 5)
box2.Add(self.LN, 1, wx.ALL, 5)
box3.Add(self.DATA, 1 , wx.ALL, 5)
box4.Add(Search, 0, wx.ALL, 5)
box5.Add(Close, 0, wx.ALL, 5)
all_box.Add(box1, 0, wx.LEFT)
all_box.Add(box2, 0, wx.LEFT)
all_box.Add(wx.StaticLine(panel), 0, wx.ALL|wx.EXPAND, 5)
all_box.Add(box3, 0, wx.CENTER)
all_box.Add(box4, 0, wx.CENTER)
all_box.Add(box5, 0, wx.CENTER)
overall.Add(all_box,0,wx.EXPAND)
overall.Add(nb, 1, wx.EXPAND)
panel.SetSizer(overall)
self.SetSize((500, 275))
self.SetTitle("Maxident Historical Data Viewer")
self.Centre()
self.Show(True)
def OnClose(self, event):
quit()
def pulldata(self, event):
firstname = str(self.FN.GetValue())
lastname = str(self.LN.GetValue())
access = pullID(lastname.strip(), firstname.strip())
access.MoveFirst
dat = ""
while not access.EOF:
a = str(access.Fields("First Name").value)
b = str(access.Fields("Last Name").value)
PID = str(access.Fields("Patient Number").value)
name = str(a + " " + b + " :" + PID)
self.DATA.Insert(name, 0)
access.MoveNext()
def OnSelection(self, event):
x = str(self.DATA.GetStringSelection())
y = x.split(":")
PID = y[1]
pullfinancedata(PID)
def pullID(lastname, firstname):
DB = r"C:\Converted DBases\DATA.mdb"
engine = win32com.client.Dispatch("DAO.DBEngine.36")
db = engine.OpenDatabase(DB)
sql = "select [Patient Number], [First Name], [Last Name] from [tPatients] where [Last Name]='" + lastname.upper() + "' and [First Name]='" + firstname.upper() + "'"
access = db.OpenRecordset(sql)
return access
def pullfinancedata(PID):
DB = r"C:\Converted DBases\DATA.mdb"
engine = win32com.client.Dispatch("DAO.DBEngine.36")
db = engine.OpenDatabase(DB)
sql = "select * from [tPayment History] where [Patient Number]=" + PID
access = db.OpenRecordset(sql)
dat = ""
while not access.EOF:
PD = "Payment Date:\t" + str(access.Fields("Payment Date").value) + '\n'
PM = "Payment Method:\t" + str(access.Fields("Payment Method").value) + '\n'
PP = "Patient Payment:\t" + str(access.Fields("Patient Payment").value) + '\n'
IP = "Insurance Payment:\t" + str(access.Fields("Insurance Payment").value) + '\n'
dat = dat + PD + PM + PP + IP + "\n ------------------ \n"
access.MoveNext()
"""
THIS IS WHERE I NEED HELP!
"""
print dat
"""
I need this dat variable to be passed to the FinanceInfo class and
i've tried FinanceInfo.Description.SetValue(dat) but its not working
"""
def main():
ex = wx.App()
Frame(None)
ex.MainLoop()
if __name__ == '__main__':
main()
I would also be grateful for any other tips or tricks. Not sure if my BoxSizer's make any sense, I mostly got the examples around other places.
There are several ways to do this:
Keep a reference to each panel and pass them around willy nilly. Then you can do stuff like self.panelOne.MyTextCtrl.SetValue(self.otherText.GetValue())
Use wx.PostEvent to pass around the information
Use pubsub
There are probably other ways too, but I prefer the last one for this sort of thing. You can read a simple example here: http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/
The answer from Mike is correct. For simple communication between a few classes I however prefer to just send a reference to the other class. It is a clean/transparent method that doesnt needs any additional library. See here an example
I hope you already solved ... but if not I revised your example using pubsub and adodbapi.
I used my mdb and adodbapi becouse logic using OpendDataBase and .movenext not works in my Python 2.7 installation .
enter code here
import wx
from wx.lib.pubsub import Publisher
import win32com.client
import adodbapi
adodbapi.adodbapi.verbose = True
# adds details to the sample printout
class FinanceInfo(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
Publisher().subscribe(self.showFrame, ("show.mainframe"))
zbox = wx.BoxSizer(wx.VERTICAL)
self.Description = wx.TextCtrl(self, -1, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(200,204))
zbox.Add(self.Description,0, wx.EXPAND,15)
self.SetSizer(zbox)
def showFrame(self, msg):
"""
Shows the frame and shows the message sent in the
text control
"""
self.Description.SetValue(msg.data)
class Frame(wx.Frame):
def __init__(self, *args, **kwargs):
super(Frame, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
#self.FinancePanelInfo = FinanceInfo(self)
panel = wx.Panel(self, -1)
box1 = wx.BoxSizer(wx.HORIZONTAL)
box2 = wx.BoxSizer(wx.HORIZONTAL)
box3 = wx.BoxSizer(wx.HORIZONTAL)
box4 = wx.BoxSizer(wx.HORIZONTAL)
box5 = wx.BoxSizer(wx.HORIZONTAL)
all_box = wx.BoxSizer(wx.VERTICAL)
overall = wx.BoxSizer(wx.HORIZONTAL)
nb = wx.Notebook(panel)
page2 = FinanceInfo(nb)
nb.AddPage(page2, "Finance Information")
first = wx.StaticText(panel, label="First Name: ")
last = wx.StaticText(panel, label="Last Name: ")
self.DATA = wx.ListBox(panel, style=wx.LB_SINGLE, size=(100,100))
self.Bind(wx.EVT_LISTBOX, self.OnSelection, id=self.DATA.GetId())
self.CLYa = wx.StaticText(panel, label="")
self.P2Da = wx.StaticText(panel, label="")
self.PLYa = wx.StaticText(panel, label="")
self.FN = wx.TextCtrl(panel, size=(75,-1))
self.LN = wx.TextCtrl(panel, size=(75,-1))
Search = wx.Button(panel, label="Search Patient")
self.Bind(wx.EVT_BUTTON, self.pulldata, id=Search.GetId())
Close = wx.Button(panel, label="Close Viewer")
self.Bind(wx.EVT_BUTTON, self.OnClose, id=Close.GetId())
box1.Add(first, 0, wx.ALL, 5)
box2.Add(last, 0, wx.ALL, 5)
box1.Add(self.FN, 1, wx.ALL, 5)
box2.Add(self.LN, 1, wx.ALL, 5)
box3.Add(self.DATA, 1 , wx.ALL, 5)
box4.Add(Search, 0, wx.ALL, 5)
box5.Add(Close, 0, wx.ALL, 5)
all_box.Add(box1, 0, wx.LEFT)
all_box.Add(box2, 0, wx.LEFT)
all_box.Add(wx.StaticLine(panel), 0, wx.ALL|wx.EXPAND, 5)
all_box.Add(box3, 0, wx.CENTER)
all_box.Add(box4, 0, wx.CENTER)
all_box.Add(box5, 0, wx.CENTER)
overall.Add(all_box,0,wx.EXPAND)
overall.Add(nb, 1, wx.EXPAND)
panel.SetSizer(overall)
self.SetSize((500, 275))
self.SetTitle("Maxident Historical Data Viewer")
self.Centre()
self.Show(True)
def OnClose(self, event):
quit()
def pulldata(self, event):
firstname = str(self.FN.GetValue())
lastname = str(self.LN.GetValue())
access = pullID(firstname.strip(), lastname.strip())
dat = ""
for rec in access:
a = str(rec[0])
b = str(rec[1])
#PID = str(access.Fields("Patient Number").value)
name = str(a + ":" + b)
print name
self.DATA.Insert(name, 0)
#access.MoveNext()
access.close
def OnSelection(self, event):
x = str(self.DATA.GetStringSelection())
y = x.split(":")
PID = y[0]
#PID = "Rossini Gianni"
dati = pullfinancedata(PID)
righe =""
for line in dati:
print line
riga = str(line)
righe = righe + riga + "\n"
Publisher().sendMessage(("show.mainframe"), righe)
def pullID(name, firstname):
#name = "ROSSINI GIANNI"
#DB = r"d:\coop&mie_doc\pdci\iscritti_2007.mdb"
# db = engine.OpenDatabase(DB)
# data_source = "D:\coop&mie_doc\pdci\iscritti_2007.mdb"
# mdw ="C:\Programmi\File comuni\System\System.mdw"
# DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=%s;Jet OLEDB:System Database=%s;" % (data_source, mdw)
SQL_statement = "select [name], [address] from [tessere_2008] where [name] LIKE '" + name.upper() + "%'"
#SQL_statement = "select [name], [address] from [tessere_2008] "
#access = db.OpenRecordset(sql)
# access = engine.Open(sql,conAccess,1,3)
_databasename = "d:\coop&mie_doc\pdci\iscritti_2007.mdb"
_table_name= 'tessere_2008'
_username = ''
_password = ''
_mdw = "C:\Programmi\File comuni\System\System.mdw"
constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;User Id=%s;Password=%s;Jet OLEDB:System Database=%s;' % (_databasename, _username, _password, _mdw)
#constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:System Database=%s;' % (_databasename, _mdw)
conAccess = adodbapi.connect(constr)
accessdb = conAccess.cursor()
# accessdb = msaccess.AccessDb()
# connAccess = accessdb.connect("D:\coop&mie_doc\pdci\iscritti_2007.mdb", "Yram", "","C:\Programmi\File comuni\System\System.mdw")
print SQL_statement
accessdb.execute(SQL_statement)
print 'result rowcount shows as= %d. (Note: -1 means "not known")' \
% (accessdb.rowcount,)
# fields = access.getFields()
# print fields
# for item in access:
# print item
#get the results
access = accessdb.fetchmany(1)
#print them
for rec in access:
print rec
return accessdb
def pullfinancedata(PID):
print "pullfinancedata"
print PID
#DB = r"d:\coop&mie_doc\pdci\iscritti_2007.mdb"
#engine = win32com.client.Dispatch(r'ADODB.Recordset')
#db = engine.OpenDatabase(DB)
_databasename = "d:\coop&mie_doc\pdci\iscritti_2007.mdb"
_table_name= 'tessere_2008'
_username = ''
_password = ''
_mdw = "C:\Programmi\File comuni\System\System.mdw"
constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;User Id=%s;Password=%s;Jet OLEDB:System Database=%s;' % (_databasename, _username, _password, _mdw)
#constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:System Database=%s;' % (_databasename, _mdw)
conAccess = adodbapi.connect(constr)
accessdb = conAccess.cursor()
#SQL_statement = "select [name], [address] from [tessere_2008] where [name] LIKE '" + name.upper() + "%'"
SQL_statement = "select * from [Tesseramento] where [anagra_iscritto]='" + PID + "'"
#access = db.OpenRecordset(sql)
print SQL_statement
accessdb.execute(SQL_statement)
print 'result rowcount shows as= %d. (Note: -1 means "not known")' \
% (accessdb.rowcount,)
dat = ""
#while not access.EOF:
# PD = "Payment Date:\t" + str(access.Fields("Payment Date").value) + '\n'
# PM = "Payment Method:\t" + str(access.Fields("Payment Method").value) + '\n'
# PP = "Patient Payment:\t" + str(access.Fields("Patient Payment").value) + '\n'
# IP = "Insurance Payment:\t" + str(access.Fields("Insurance Payment").value) + '\n'
# dat = dat + PD + PM + PP + IP + "\n ------------------ \n"
# access.MoveNext()
"""
THIS IS WHERE I NEED HELP!
"""
#get the results
access = accessdb.fetchmany(accessdb.rowcount)
#print them
#for rec in access:
# print rec
"""
I need this dat variable to be passed to the FinanceInfo class and
i've tried FinanceInfo.Description.SetValue(dat) but its not working
"""
return access
def main():
ex = wx.App()
Frame(None)
ex.MainLoop()
if __name__ == '__main__':
main()