Ethereum generating genesis Python Syntax - python

Hi I tried to generate the genesis file but get this error:
C:\Python34>python mk_genesis_block.py --extradata 0x11bbe8db4e347b4e8c937c1c837
0e4b5ed33adb3db69cbdb7a38e1e50b1b82fa > genesis_block.json
File "mk_genesis_block.py", line 293
print json.dumps(evaluate(), indent=4)
^
SyntaxError: invalid syntax
Edit:
Here is the surrounding lines:
if __name__ == '__main__':
print json.dumps(evaluate(), indent=4)
Then it's EOF. The whole file can be viewed here
Since the offending line seems to be only output, I commented it and got another error:
C:\Python34>python -tt mk_genesis_block.py --extradata 0x11bbe8db4e347b4e8c937c1
c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa > genesis_block.json
Traceback (most recent call last):
File "mk_genesis_block.py", line 124, in <module>
EXTRADATA = (d[2:] if d[:2] == '0x' else d).decode('hex')
AttributeError: 'str' object has no attribute 'decode'
which in conjunction with the other error makes me wonder whether a string instead of a json object is being operated on? Here is the whole arg parsing part:
# Grab the extra data command line argument
if '--extradata' in sys.argv:
d = (sys.argv+[None])[sys.argv.index('--extradata') + 1]
EXTRADATA = (d[2:] if d[:2] == '0x' else d).decode('hex')
else:
EXTRADATA = ''
I also made a test file importing the json package, dumps and decode methods work.

print in python3 is a method not a statement print( "text" ) ... also I believe str.decode was remove in python3 ... instead use codecs.decode(my_str,encoding)

Related

ValueError: substring not found in midi

Let me first start this off by stating that I am a complete beginner to coding and my attempts to fix this have been limited. I am trying to follow this Arduino controlled piano robot. It takes a textified midi file and uses python to translate it into 8-bit. The code is attached near the bottom of the link, I had some formatting issues when placing it here.
This link to the textified midi file used. before running the code I changed the input_file = open to text file path like so,
input_file = open("C:\\Users\\nby20\\Downloads\\megalovania.txt")
After running the code I get a text output file as expected however it is blank and I get a few errors:
Traceback (most recent call last):
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 184, in <module>
main()
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 23, in main
result[-1] = str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1)
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 178, in on_off_finder
end = in_string.index("ch=") - 1
ValueError: substring not found
Any suggestions on how to fix this would be greatly appreciated.
The Traceback is like debugging information you can use to trace which functions were called when the error was thrown. It seems the error occurred when it was executing this bit of conditional logic, lines 22-23, of the main function:
elif time_finder_comm(result[-1]) == temp_time:
result[-1] = str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1)
which called the on_off_finder function which just tries to figure out if the line says 'On' or 'Off'.
It seems the file reader only expects lines like this:
55248 Off ch=10 n=40 v=64
However, in the file you uploaded, there also lines like this:
55248 Meta TrkEnd
TrkEnd
The index function throws ValueError: substring not found if the substring passed in does not exist in the string, which in this case (line 178 below) is the string "ch":
end = in_string.index("ch=") - 1
Try removing those kind of lines and re-run the script? Find all lines with "Trk" and and remove them, or make 3 separate files because there seem to be 3 blocks of lines in 'megalovania.txt' that will trip up the script:
(starting at line 2469):
55248 Meta TrkEnd
TrkEnd
MTrk
...
(starting at line 4071):
58368 Meta TrkEnd
TrkEnd
MTrk
...
(starting at line 6431):
55296 Meta TrkEnd
TrkEnd

Problems with pickle python

I recently made a program using an external document with pickle. But when it tries to load the file with pickle, I got this error (the file is already existing but it also fails when the file in't existing):
python3.6 check-graph_amazon.py
a
b
g
URL to follow www.amazon.com
Product to follow Pool_table
h
i
[' www.amazon.com', ' Pool_table', []]
p
Traceback (most recent call last):
File "check-graph_amazon.py", line 17, in <module>
tab_simple = pickle.load(doc_simple)
io.UnsupportedOperation: read
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "check-graph_amazon.py", line 42, in <module>
pickle.dump(tab_simple, 'simple_data.dat')
TypeError: file must have a 'write' attribute
Here is the code :
import pickle5 as pickle
#import os
try:
print("a")
with open('simple_data.dat', 'rb') as doc_simple:
print("b")
tab_simple = pickle.load(doc_simple)
print("c")
print(tab_simple)
print("d")
URL = tab_simple[0]
produit_nom = tab_simple[1]
tous_jours = tab_simple[2]
print("f")
except :
print("g")
URL = str(input("URL to follow"))
produit_nom = str(input("Product to follow"))
with open('simple_data.dat', 'wb+') as doc_simple:
print("h")
#os.system('chmod +x simple_data.dat')
tab_simple = []
tab_simple.append(URL)
tab_simple.append(produit_nom)
tab_simple.append([])
print(tab_simple)
print("c'est le 2")
print("p")
pickle.dump(tab_simple, 'simple_data.dat')
print("q")
The prints are here to show which lines are executed. The os.system is here to allow writing on the file but the error is persisting.
I don't understand why it's said that the document doesn't have a write attribute because I opened it in writing mode. And I neither understand the first error where it can't load the file.
If it can help you the goal of this script is to initialise the program, with a try. It tries to open the document in reading mode in the try part and then set variables. If the document doesn't exist (because the program is lauched for the first time) it goes in the except part and create the document, before writing informations on it.
I hope you will have any clue, including changing the architecture of the code if you have a better way to make an initialisation for the 1st time the program is launched.
Thanks you in advance and sorry if the code isn't well formated, I'm a beginner with this website.
Quote from the docs for pickle.dump:
pickle.dumps(obj, protocol=None, *, fix_imports=True)
Write a pickled representation of obj to the open file object file. ...
...
The file argument must have a write() method that accepts a single bytes argument. It can thus be an on-disk file opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface.
So, you should pass to this function a file object, not a file name, like this:
with open("simple_data.dat", "wb"): as File:
pickle.dump(tab_simple, File)
Yeah, in your case the file has already been opened, so you should write to doc_simple.

Syntax error using ast.literal_eval(open("filename").readlines()[0]) in python

When I try to run my code and import an array from another file I keep getting a Syntax Error saying:
Traceback (most recent call last):
File "run.py", line 21, in <module>
passwords = ast.literal_eval(open("passwords.txt").readlines()[0])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
[‘test’]
^
SyntaxError: invalid syntax
The piece ['test'] is the contents of the external file "passwords.txt", however what confuses me is that in the following code if I include only the first 2 variables the code runs perfectly fine but when the second is added it throws an error (also the file contents is the same in all of the variables)
adjectives = ast.literal_eval(open("Adjectives.txt").readlines()[0])
nouns = ast.literal_eval(open("Nouns.txt").readlines()[0])
passwords = ast.literal_eval(open("passwords.txt").readlines()[0])
usernames = ast.literal_eval(open("usernames.txt").readlines()[0])
The only other related new code is this:
def WOPR():
login = raw_input("Username: ")
login_password = raw_input("Password: ")
login_password = psudo_encrypt(login_password)
for name in usernames:
if name == login:
for word in passwords:
if word == login_password:
print("Greetings " + login)
play(true, login)
else:
print("Incorrect Password \n-------Connection Terminated-------")
elif login == "Joshua":
print("Greetings Professor Falken \nWould you like to play a game?")
play(true, "Professor")
else:
WOPR()
Anyone any idea what could be causing this? Have I missed a really obvious syntax issue? Thanks in advance
[‘test’]
^ ^
The two characters I've marked are curly apostrophes (‘’), not straight apostrophes ('). You probably got them by copying and pasting code from a web site, or by editing your code in a text editor that isn't intended for working with code.
Replace those characters with normal apostrophes.

Better debugging: expected a character buffer object

I am trying to pass a string section to the the python function below it
I am uncertain why I am seeing this error. My understanding of this is that it is not getting a string, where it is expected. I have tried casting, but that is not working either. How can I solve this or get more debug info?
section = str('[log]')
some_var = 'filename ='
edit_ini('./bench_config.ini', section, some_var, 'logs/ops_log_1')
The function causing the error
def edit_ini(filename, section, some_var, value):
section = False
flist = open(filename, 'r').readlines()
f = open(filename+'test', 'w')
for line in flist:
line = str(line)
print line
if line.startswith(section):
section = True
if( section == True ):
if( line.startswith(some_var) ):
modified = "%s = $s", variable, value
print >> f, modified
section = False
else:
print >> f, line
f.close()
However I see the error:
Traceback (most recent call last):
File "bench.py", line 89, in <module>
edit_ini('./config.ini', section, some_var, 'logs/log_1')
File "bench.py", line 68, in edit_ini
if line.startswith(section):
TypeError: expected a character buffer object
You overwrite the passed-in section with section=False. The error is because you cannot call string.startswith( False ).
A way to debug python is to use pdb. This would have helped you find your problem here. You should read the spec, but heres a quick guide on how to use pdb.
import pdb
# your code ...
pdb.set_trace() # put this right before line.startswith(section)
Then when you run your code, you will execute up to right before the failure. Then you can print section in pdb, and see that it is False, and then try to figure out why it is False.

Error when using astWCS trying to create WCS object

I'm running python2.5 and trying to use the astLib library to analyse WCS information in astronomical images. I try and get the object instanciated with the following skeleton code:
from astLib import astWCS
w = astWCS.WCS('file.fits') # error here
where file.fits is a string pointing to a valid fits file.
I have tried using the alternate method of passing a pyfits header object and this fails also:
import pyfits
from astLib import astWCS
f = pyfits.open('file.fits')
header = f[0].header
f.close()
w = astWCS.WCS(header, mode='pyfits') # error here also
The error is this:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 79, in __init__
self.updateFromHeader()
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 119, in updateFromHeader
self.WCSStructure=wcs.wcsinit(cardstring)
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/PyWCSTools/wcs.py", line 70, in wcsinit
return _wcs.wcsinit(*args)
TypeError: in method 'wcsinit', argument 1 of type 'char *'
When I run in ipython, I get the full error here on the pastebin
I know the astWCS module is a wrapped version of WCStools but i'd prefer to use the Python module as the rest of my code is in Python
Can anyone help with this problem?
Just found out the updated version of this library has fixed the problem, thanks for everyone's help
Oh sorry, I should have seen. Looking at the pastebin in more detail, the only error I can think of is that, for some reason the header has unicode in it. It can't be converted to char *, and you get the error. I tried searching for something in the header, but everything looks okay. Can you do this and post the output in another pastebin?
import pyfits
f = pyfits.open('file.fits')
header = f[0].header
f.close()
for x, i in enumerate(header.iteritems()):
if len(str(i[1])) >= 70:
print x, str(i[1])
cardlist = header.ascardlist()
cardstring = ""
for card in cardlist:
cardstring = cardstring + str(card)
print repr(cardstring)
Or, if you can check the header of your fits file for "funny" characters, getting rid of them should solve the issue.

Categories

Resources