I'm working on a project and this error keeps showing up:
class PRNG:
def __init__(self):
# parameters
# P-256 prime
self.p=115792089210356248762697446949407573530086143415290314195533631308867097853951
self.a=self.p-3
self.b=41058363725152142129326129780047268409114441015993725554835256314039467401291
self.E=curve(self.a,self.b,self.p)
self.E.n=115792089210356248762697446949407573529996955224135760342422259061068512044369
self.P=point(0,46263761741508638697010950048709651021688891777877937875096931459006746039284)
self.k=183521403747637560534595403690771364941493702673414885451510208165414833985
self.Q=mult(self.k,self.P,self.E)
self.t=bytes_to_int(os.urandom(32)) # initial seed
#print self.t
self.output_length=240
self.truncate_length=16
def function_attack(self, nbytes, predicted_state):
calls = ((nbytes*8-1)/self.output_length)+1
out = ''
for i in xrange(calls):
tP=mult(predicted_state,self.P,self.E)
s=tP.x
sQ=mult(s,self.Q,self.E)
r=sQ.x
r_out=r % (2**self.output_length)
self.t=s
out = out + int_to_bytes(r_out, self.output_length/8)
return out[:nbytes]
def function(self, nbytes):
calls = ((nbytes*8-1)/self.output_length)+1
out = ''
for i in xrange(calls):
tP=mult(self.t,self.P,self.E)
s=tP.x
sQ=mult(s,self.Q,self.E)
r=sQ.x
r_out=r % (2**self.output_length)
self.t=s
out = out + int_to_bytes(r_out, self.output_length/8)
return out[:nbytes]
The first method is being called in a separate file and the output is always the following(regardless if I change the name of the local variable calls):
File "C:\file1.py", line 32, in <module>
prng = PRNG()
File "C:\file_where_error_occurs.py", line 286, in __init__
for i in xrange(calls):
NameError: global name 'calls' is not defined
What is python doing?
you have indentation errors ... this is typically caused by mixing tabs and spaces ... most decent editors can fix this for you easily ... to see your indentation errors run your program as
python -tt my_program.py
Related
I try to start a timer to do some file arvchival job. the code is like this:
from threading import Timer
message_archive_dir = "achivedir"
message_archive_format = "zip"
archive_timer = Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
archive_timer.start()
class messageachiver(object):
def __init__(self, **kwargs):
self.message_archive_dir = dir
self.message_archive_format = fmt
def archive(self):
print("message_archive_dir is " + self.message_archive_dir)
print("message_archive_format is " + self.message_archive_format)
print("Archiving trade messages")
I got below error:
Traceback (most recent call last):
File "sa_listener.py", line 43, in <module>
archive_timer = Timer(archive_interval, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
TypeError: __init__() got an unexpected keyword argument 'dir'
I'm not sure why _init_ does not accept **kwargs.
This specific init error is because you are passing multiple variables to the timer class.
In this line:
Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
You are passing the archive function, the dir variable, and the fmt variable to TIMER and not to the messageachiver class. Timer has no named variables for dir and fmt.
So the line should be Timer(86400, messageachiver.archive)
This only partially fixes your problem though. Because you are never actually initializing the class with the variables you need them to have. So before you call timer, you need to initialize the class messageachiver by adding mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)
Also you need to put your class definition before you try to initialize it.
The final code:
from threading import Timer
class messageachiver(object):
def __init__(self, **kwargs):
self.message_archive_dir = kwargs['dir']
self.message_archive_format = kwargs['fmt']
def archive(self):
print("message_archive_dir is " + self.message_archive_dir)
print("message_archive_format is " + self.message_archive_format)
print("Archiving trade messages")
message_archive_dir = "achivedir"
message_archive_format = "zip"
mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)
# That's a huge wait time, try something like 10 for a smaller wait during testing.
archive_timer = Timer(86400, mymessageachiver.archive)
archive_timer.start()
I am trying to implement a factor graph. I would like to read the factor functions from a sperate file. Unfortunately when I read a function from a file just for test I get the error:
eval(lines[0])(1,2,3)
File "<string>", line 1
def f(x0,x1,x2):
^
SyntaxError: invalid syntax
My code is as follows:
class Node:
def __init__(self,name,graph):
self.name = name
self.graph = graph
self.neighbourFactors=[];
class Factor:
def __init__(self,name,neighbours,graph):
self.name = name
self.value = 1
self.graph = graph
self.neighbourNodes=[];
class Graph:
def __init__(self,factorNumber,nodeNumber,factorNeighboursList):
self.factorNumber = factorNumber
self.factors=[Factor(i,factorNeighboursList[i],self) for i in range(factorNumber)]
self.nodes=[Node(i,self) for i in range(nodeNumber)]
factorNumber=0;
for neighbourNodes in factorNeighboursList:
for i in range(len(neighbourNodes)):
self.factors[factorNumber].neighbourNodes.append(self.nodes[int(neighbourNodes[i])]);
self.nodes[int(neighbourNodes[i])].neighbourFactors.append(self.factors[factorNumber])
factorNumber+=1;
def makeGraph(factorNumber,nodeNumber):
factorNeighboursList=[]*factorNumber
f = open('factorNeighboursInput.txt', 'r')
for line in f:
factorNeighboursList.append(line.split())
g=Graph(factorNumber,nodeNumber,factorNeighboursList)
return g
factorNumber=input('Please specify number of Factors:')
nodeNumber=input('Please specify number of Nodes:')
g=makeGraph(factorNumber,nodeNumber)
f = open('factorFunctionInput.txt', 'r')
lines=f.read().split(';')
print lines
eval(lines[0])(1,2,3)
my separate input file for functions is:
def f(x0,x1,x2):
return x0*x1*x2
;
def f(x1):
return x1+1
;
def f(x2):
return x2
;
def f(x3):
return x3+2
;
I think in case of calling eval with multiple line eval function, it fails.
You should use eg.exec instead of eval:solution
Furthermore i think you have to call the functions, the definition doesn't seems enough:
def f(x0,x1,x2):
return x0*x1*x2
f(x0,x1,x2)
Sorry if this question is stupid. I created an unittest class which needs to take given inputs and outputs from outside. Thus, I guess these values should be initiated. However, I met some errors in the following code:
CODE:
import unittest
from StringIO import StringIO
##########Inputs and outputs from outside#######
a=[1,2]
b=[2,3]
out=[3,4]
####################################
def func1(a,b):
return a+b
class MyTestCase(unittest.TestCase):
def __init__(self,a,b,out):
self.a=a
self.b=b
self.out=out
def testMsed(self):
for i in range(self.tot_iter):
print i
fun = func1(self.a[i],self.b[i])
value = self.out[i]
testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("func1",i,value,fun)
self.assertEqual(round(fun,3),round(value,3),testFailureMessage)
if __name__ == '__main__':
f = MyTestCase(a,b,out)
from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream, verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
print 'Tests run', result.testsRun
However, I got the following error
Traceback (most recent call last):
File "C:testing.py", line 33, in <module>
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
File "C:\Python27\lib\unittest\loader.py", line 310, in makeSuite
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
File "C:\Python27\lib\unittest\loader.py", line 50, in loadTestsFromTestCase
if issubclass(testCaseClass, suite.TestSuite):
TypeError: issubclass() arg 1 must be a class
Can anyone give me some suggestions? Thanks!
The root of the problem is this line,
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
unittest.makeSuite expects a class, not an instance of a class. So just MyTestCase, not MyTestCase(a, b, out). This means that you can't pass parameters to your test case in the manner you are attempting to. You should probably move the code from init to a setUp function. Either access a, b, and out as globals inside setUp or take a look at this link for information regarding passing parameters to a unit test.
By the way, here is the source file within python where the problem originated. Might be informative to read.
def make_pdf(self):
self.get_filez()
self.get_client()
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
style = libxslt.parseStylesheetDoc(self.xsl_file)
transformation = style.applyStylesheet(self.xml_file,None)
style.saveResultToFilename("tmp/"+file_name+".fo",transformation,0)
style.freeStylesheet()
self.xml_file.freeDoc()
transformation.freeDoc()
fop_cmd = "/usr/bin/xmlgraphics-fop"
#file_name = self.tpa+"_"+self.be+"_"+self.batch_num
cmd = [fop_cmd,"-fo","tmp/"+file_name+".fo","-pdf","tmp/"+file_name+".pdf"]
#fop_transform = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
#fop_log = "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"
#fop_log = fop_log + time.strftime('%Y-%m-%d %R:%S')+"\n"
#fop_log = fop_log + file_name+".fo" + "\n"
#fop_log = fop_transform.communicate()[0]+"\n"
#f = open("/tmp/error_log","a")
#f.write(fop_log)
#f.close()
OK If I comment out the cmd variable declaration the code runs and makes an fo file correctly. With is uncommented like it is above, I get a NameError on file_name is not defined (which it is in the top). If I uncomment the second declaration of file_name right above the cmd declaratioin, it thows a NameError on self. '.' In the past when this sort of thing happens, it is a syntax error. I am missing it, please helpz!
When the second declaration of file_name is commented out:
Traceback (most recent call last):
File "make_pdfs.py", line 11, in ?
from MakePdfs import MakePdfs
File "/home/khouser/removed/removed/MakePdfs.py", line 16, in ?
class MakePdfs:
File "/home/khouser/removed/removed/MakePdfs.py", line 39, in MakePdfs
cmd = [fop_cmd,"-fo","tmp/"+file_name+".fo","-pdf","tmp/"+file_name+".pdf"]
NameError: name 'file_name' is not defined
When the second declaration of file_name is uncommented:
Traceback (most recent call last):
File "make_pdfs.py", line 11, in ?
from MakePdfs import MakePdfs
File "/home/khouser/removed/removed/MakePdfs.py", line 16, in ?
class MakePdfs:
File "/home/khouser/removed/removed/MakePdfs.py", line 38, in MakePdfs
file_name = self.tpa+"_"+self.be+"_"+self.batch_num
NameError: name 'self' is not defined
Mysterious NameErrors may arise from your file containing invisible control characters. On unix machines, you can spot these errors by looking at the output of
cat -A filename.py
Try to print file_name after each line, to see if somebody is removing the "file_name" variable from your namespace.
In addition, to be more pythonic (and efficient), use
file_name = "_".join((self.client_id, self.client_name, self.batch_num))
to concatenate strings.
If you're assigning file_name here:
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
And you're getting a NameError reporting, that file_name is not defined, then try wrapping the operation in a try..except, to see what is going wrong:
try:
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
except NameError as err:
print err, 'failed, here is some debug stuff:'
print "CLIENT ID =", self.client_id
print "CLIENT NAME =", self.client_name
print "BATCH NUM =", self.batch_num
If any of this is failing, this will set you on the course to finding out why and narrowing down the cause of it.
I get a weird error:
Traceback (most recent call last):
File "/remote/us01home15/ldagan/python/add_parallel_definition.py", line 36, in <module>
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 70, in add_parallel_extention
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 52, in gen_parallel_hierarchy
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
NameError: global name 'self' is not defined
From all the tutorials that I have seen, calling a different method from the same class is via self.method_name
It's a script instantiating a class.
The script is:
#!/depot/Python-3.1.1/bin/python3.1
#gets a netlist and a cell name.
#generates a new netlist with the parallel instanciation
import sys
import re
from operator import itemgetter
sys.path.append('/remote/us01home15/ldagan/python/')
from hspice_netlist import hspice_netlist
command="" # initializing argument string
for l in sys.argv:
command=command + " " + "".join(l)
print (len(sys.argv))
print (command)
if (len(sys.argv) <4):
sys.exit("Pleas input original file name & new file name")
orig_netlist=hspice_netlist("file=" + "".join(sys.argv[1])) #reading new netlist
new_netlist=hspice_netlist("") #empty netlist
match=re.search(r"subckt\s*=\s*(\S+)",command)
if (match):
cell_name=match.group(1) #cell to be parallelized name
else:
sys.exit("Please input subckt= <subckt name>")
match=re.search(r"level\s*=\s*(\S+)",command)
if (match):
level=match.group(1) #levels of netlist name
else:
sys.exit("Please input level=<level name>")
match=re.search(r"parallel\s*=\s*(\S+)",command)
if (match):
parallel=match.group(1) #new netlist name
else:
sys.exit("Please input parallel=<parallel name>")
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
match=re.search(r"outfile\s*=\s*(\S+)",command)
if (match):
output_filename=match.group[1]
outfile=open(output_filename,'w')
outfile.write("".join(new_netlist.lines))
The class code is:
import sys
import re
from collections import defaultdict
class hspice_netlist:
def __init__(self,cmd):
cmd_match=re.search(r"file\s*=\s*(\S+)",cmd)
if (cmd_match):
filename=cmd_match.group(1)
self.infile = open(filename, 'r')
self.lines=self.infile.readlines() #reading the lines
self.infile.close() #closing filehandle
def input_lines(self,lines):
self.lines=lines
def get_subckt_lines(self,name):
gotit=0
ret_lines=[]
find_sub=re.compile("^.sub\S*\s+"+name, re.IGNORECASE)
find_end=re.compile('^.ends', re.IGNORECASE)
for line in self.lines:
if (not gotit):
if (find_sub.search(line)):
gotit=1
ret_lines.append(line)
else:
ret_lines.append(line)
if (find_end.search(line)):
return ret_lines
sys.exit("Could not find the lines for circuit " + name + '\n')
def gen_parallel_inst(num,cell_1st_line):
ret_lines=[] #starting a fresh!!
cell_data=re.search(r"^\S+\s+(\S+)(\s+.*)", cell_1st_line)
cell_name=cell_data.group(1) # got the cell name
new_cell_name=cell_name + '__' + str(num) # new cell name
nodes=cell_data.group(2) # interface
ret_lines.append("".join([".sub ", new_cell_name,nodes,"\n"]))
iter=num
if (not (re.search(r"\s+$",nodes))):
nodes=nodes + ' ' #need a space before the cell name, add if it doesn't exist
while(iter > 0):
line="x" + str(iter) + nodes + cell_name + "\n"
ret_lines.append(line)
iter=iter-1
ret_lines.append(".ends\n") #end of subcircuit definition
return return_lines
def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
'''What that it does: Gets a cell name, then finds that cell's interface definition. It then simply relicates the cell, in parallel, then into hierarchies, ending with new cells' definitions. It is useful for the HSPICE BA issue. It runs recusively. Currently it supports 1 line for interface definition, and no parameters for the cell # this time '''
ret_lines=[]
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
ret_lines.extend(cell_lines)
if (level>0):
ret_lines.extend(self.gen_parallel_hierarchy(num_of_parallel,level-1,cell_lines[0]))
return ret_lines
def add_parallel_extention(self,cell_name,num,level):
''' Get a cell name + definitions and generates a new netlist '''
i=0
regi=re.compile("^.sub\S*\s+" + cell_name)
m=-1
while ( (i+1 < len(self.lines)) & ( not m )):
i=i+1
m=regi.search(lines[i]) #finding the line
if (not m):
sys.exit("could not find subcircuit definition of " + cell_name + "\n")
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
i=i-1
ret_lines=self.lines[0:i] # creating return variable, using extend for performance
ret_lines.extend(new_cells_definition)
ret_lines.extend(self.lines[i+1:len(self.lines)])
return ret_lines
#get the cell
#write the level
I am definitely doing something fundamentally wrong, but I don't know what.
Thanks for helping an EE newbe (to Python).
You are missing self in two method declarations.
These
def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
def gen_parallel_inst(num,cell_1st_line):
should be
def gen_parallel_hierarchy(self,num_of_parallel,level,cell_1st_line):
def gen_parallel_inst(self,num,cell_1st_line):
The error happens because you haven't put the self parameter in gen_parallel_hierarchy() but are referring to it in the line which fails:
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)