How to solve a list indexi error in python - python

Hellor pythoneers,
I was doing a python program where it reads a group of circles of a file and, once it demands information to the user of a certain circle, determine whether this circle is an inner circumference, an outer circumference or a secant one.
However, i'm experiencing an error I've never seen before.
Traceback (most recent call last):
File "d:\Exercici.py", line 68, in <module>
main()
File "d:\Exercici.py", line 41, in main
x=io.obtReal(i)
File "d:\modul_lect_escr.py", line 93, in obtReal
return float(sequencia[i])
IndexError: list index out of range
I know for a fact the error is in this line of code:
def main():
M=20
N=3
mat=np.zeros((M,N),float)
nomf="circumferencies.txt"
io.obrirFitxer(nomf)
i=0
x=io.obtReal(i) <------
y=io.obtReal(i) <------ Error
radi=io.obtReal(i) <------
while not(x==-999.999 and y==999.999 and radi==999.999):
i=i+1
mat[i,0]=x
mat[i,1]=y
mat[i,2]=radi
x=io.obtReal(i)
y=io.obtReal(i)
radi=io.obtReal(i)
num_circumferencies=i
The function called obtReal comes from a library I was given to read files. Here's the extract of the function:
def obtReal(i): # 1st test ok
return float(sequencia[i])
If anyone has any clue to where the error is, I'd love to hear their opinion.

Related

Python throwing exception for function I didn't call

I have a function with the following logic:
def align(val, al): # This is technically imported from a separate file
return (val + (al - 1)) & -al
def compileFont(font, output, audiobank_off=0):
# Get used slot counts
icount = font.instSlotCount()
pcount = font.percSlotCount()
xcount = font.sfxSlotCount()
# Calculate head offset table size
current_pos = (2 + icount) * packspecs.pointerSize()
current_pos = align(current_pos, 16)
To be clear, current_pos is an integer by the last line. When it gets to that last line, though, Python ends up throwing the following exception:
Exception has occurred: TypeError (note: full exception trace is
shown but execution is paused at: <module>)
object of type 'int' has no len()
File "tools/assemble_sound.py", line 311, in compileFont
current_pos = align(current_pos, 16)
File "tools/assemble_sound.py", line 1020, in main
compileFont(font, f, aboff)
File "tools/assemble_sound.py", line 1136, in <module> (Current frame)
main()
I have no idea how len() is coming into play here. I double-checked and the align() function doesn't even call len(). Has anyone ever seen this before? What do I do to troubleshoot this?
Edit: I've added some more of the code and stacktrace to provide additional context. In terms of the types, current_pos is of type int.
The traceback was apparently the right clue. For some reason, when I ran this in VS Code, the exception stacktrace it showed was incomplete (as posted above). When I ran it from the command line, I got this:
Traceback (most recent call last):
File "oot/tools/assemble_sound.py", line 1136, in <module>
main()
File "oot/tools/assemble_sound.py", line 1020, in main
compileFont(font, f, aboff)
File "oot/tools/assemble_sound.py", line 311, in compileFont
current_pos = align(current_pos, 16)
File "~/.local/lib/python3.9/site-packages/makeelf/type/align.py", line 8, in align
full = ceil(len(b) / alignment)
TypeError: object of type 'int' has no len()
This pointed me in the right direction that it was calling the wrong align() method. VS Code couldn't step into align(), so I wasn't able to figure it out until I tried the command line.

pyautogui.pixel works perfectly for a while, and then randomly stops working and gives errors

I have been implementing pyautogui.pixel in many forms of code, I will get a normal desirable output for a random short while, and at some point, the function will stop working, and I will get error messages.
Simple example code:
while True:
print(pyautogui.pixel(1766, 1539))
Output:
(30, 30, 30)
The eventual error message:
Traceback (most recent call last):
File "c:\Users\zyoli\Desktop\scrap_bot\gathering.py", line 14, in <module>
print(pyautogui.pixel(1766, 1539))
File "C:\Users\zyoli\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line 584, in pixel
return (r, g, b)
File "C:\Users\zyoli\AppData\Local\Programs\Python\Python39\lib\contextlib.py", line 124, in __exit__
next(self.gen)
File "C:\Users\zyoli\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line 113, in __win32_openDC
raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0
I suppose you are switching some windows/app while running the code. Maybe because of the animation(while opening a new window), Pyautogui raises an error. get_pixel from the screen is slow. Maybe this thread can help you:
Quickly getting the color of some pixels on the screen in Python on Windows 7

"ValueError: negative count return bytes(bytearray(seq))" on raspberry pi

I wanna send a negative string from a raspberry pi to an arduino and got this error on the raspis cmd:
Traceback (most recent call last):
File "program.py", line 363, in <module>
ser.write(LinePosLastLoop[6])
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 532, in write
d = to_bytes(data)
File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 66, in to_bytes
return bytes(bytearray(seq))
ValueError: negative count
Program:
value = str(linePos).encode()
value = int(float(value))
LinePosLastLoop[6] = value
ser.write(LinePosLastLoop[6])
I tried to shorten my program as much as possible to make it easier to understand, but if I miss something or anything is unclear, please comment that and I will all the information you need.
Thanks for possible answers
The mistake was that
LinePosLastLoop[6]
is a string which have to be converted to a byte before sending via uart. So to fix this error just change
ser.write(LinePosLastLoop[6])
to
ser.write(str(LinePosLastLoop[6]/10).encode())
I hope I could help any futher readers!

Memory Error Python while processing large database

When I run this on Pycharm 4 on windows I got an error in this code:
PDBSumWWW = urllib.urlopen("https://www.ebi.ac.uk/thornton-srv/databases/pdbsum/data/seqdata.dat")
PDBSum = PDBSumWWW.read().splitlines()
PDBSumWWW.close()
This is the error message:
Traceback (most recent call last):
File "C:/Users/LuisAlberto/PycharmProjects/MSc/SeqPDBSumIRIndex.py", line 98, in
main()
File "C:/Users/LuisAlberto/PycharmProjects/MSc/SeqPDBSumIRIndex.py", line 40, in main
PDBSum = PDBSumWWW.read().splitlines()
MemoryError
However when running in on a Macbook Air it doesnt happen.
how do I get over this?
This is the most simple solution that I can think of to solve your problem.
In this solution the for loop will iterate over every line in the database.every line will be assigned to the line variable.
PDBSumWWW = urllib.urlopen("https://www.ebi.ac.uk/thornton-srv/databases/pdbsum/data/seqdata.dat")
for line in PDBSumWWW:
# Do necessary calculations.
PDBSumWWW.close()

Python speech recognition 'module' object has no attribute 'VARIANT'

I'm trying to get started using speech recognition in python. First I tried PySpeech (https://code.google.com/p/pyspeech/) using this code:
def listen():
while 1:
said = speech.input()
print said
if said == "off":
break
and got the following traceback:
Traceback (most recent call last):
File "C:/Users/REDACTED/Documents/Python Projects/listen.py", line 59, in <module> useful.listen()
File "C:/Users/REDACTED/Documents/Python Projects/listen.py", line 48, in listen
said = speech.input()
File "C:\Python27\lib\site-packages\speech.py", line 162, in input
listener = listenforanything(response)
File "C:\Python27\lib\site-packages\speech.py", line 193, in listenforanything
return _startlistening(None, callback)
File "C:\Python27\lib\site-packages\speech.py", line 223, in _startlistening
grammar = context.CreateGrammar()
File "C:\Users\REDACTED\AppData\Local\Temp\gen_py\2.7\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x4.py", line 2298, in CreateGrammar
ret = self._oleobj_.InvokeTypes(14, LCID, 1, (9, 0), ((12, 49),),GrammarId
AttributeError: 'module' object has no attribute 'VARIANT'
Then I tried dragonfly per the suggestion at the top of the GoogleCode page for PySpeech using the following example code commonly found on dragonfly docs:
from dragonfly.all import Grammar, CompoundRule
# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
spec = "do something computer" # Spoken form of command.
def _process_recognition(self, node, extras): # Callback when command is spoken.
print "Voice command spoken."
# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar") # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule()) # Add the command rule to the grammar.
grammar.load() # Load the grammar.
and got this very similar traceback:
Traceback (most recent call last):
File "C:/Users/REDACTED/Documents/Python Projects/listen.py", line 14, in <module>
grammar.load() # Load the grammar.
File "C:\Python27\lib\site-packages\dragonfly\grammar\grammar_base.py", line 302, in load
self._engine.load_grammar(self)
File "C:\Python27\lib\site-packages\dragonfly\engines\engine_sapi5.py", line 79, in load_grammar
handle = self._compiler.compile_grammar(grammar, context)
File "C:\Python27\lib\site-packages\dragonfly\engines\compiler_sapi5.py", line 68, in compile_grammar
grammar_handle = context.CreateGrammar()
File "C:\Users\REDACTED\AppData\Local\Temp\gen_py\2.7\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x4.py", line 2298, in CreateGrammar
ret = self._oleobj_.InvokeTypes(14, LCID, 1, (9, 0), ((12, 49),),GrammarId
AttributeError: 'module' object has no attribute 'VARIANT'
Both modules were installed using PIP and run using python 2.7 interpreter. It seems like a python version issue to me given that the same error is thrown for two different modules implementing the same thing but I'm pretty stuck on how to proceed.
Any help is greatly appreciated and I'm happy to provide more code/info as its requested. Thanks!
EDIT 1: For anyone experiencing a similar problem who happens to stumble across this post, try https://pypi.python.org/pypi/SpeechRecognition/ as an alternative on py2.7. If it runs without error but behaves inconsistently or infinite loops, try modifying the init method of the recognizer class in init.py around line 100. The energy threshold required some tinkering for me (100->300) which is likely due to the specifics of your mic setup. I also increased my quiet duration (0.5->0.7) because it would cut me off sometimes. After these changes it works fairly well for me, returning very accurate text of the input speech in ~2 seconds after capture ends.

Categories

Resources