New to Python & taking a course where teacher provided a code snippet to work on. The provided snippet is giving me a TabError as below, but I cannot seem to figure out why. I was hoping someone here could point out the issue.
Error Received:
Error Received
Code where error occurs (Updated to have code lines instead of screen shot):
def filterResultsAcc(self, qcoverage=0.6, scoverage=0.6, evalue=0.01, best_taxon=False):
results = []
hits_by_taxon = {}
for(qstart,qend,sacc,staxid,slen,sstart,send,evalu) in self.blasthits:
qcov = ((qend-qstart) + 1.0) / float(self.querylen)
scov = ((send-sstart) + 1.0 / float(slen)
if qcov >= qcoverage and scov >= scoverage and evalu <= evalue:
if best_taxon:
if staxid in hits_by_taxon.keys():
(sid,e,qc,sc) = hits_by_taxon[staxid]
if evalu < e:
hits_by_taxon[staxid] = (sacc,evalu,qcov,scov)
elif evalu == e:
if qcov > qc:
hits_by_taxon[staxid] = (sacc,evalu,qcov,scov)
elif qvoc == qc:
if scov > sc:
hits_by_taxon[staxid] = (sacc,evalu,qcov,scov)
else:
hits_by_taxon[staxid] = (sacc,evalu,qcov,scov)
else:
results.append(sacc)
if best_taxon:
for taxid in hits_by_taxon.keys():
(sac,e,qc,sc) = hits_by_taxon[taxid]
results.append(sacc)
results.sort()
return results
The error shows that you've mixed tab and spaces, just as it says.
If your editor supports it – turn something like "show unprintable characters" to see what your whitespaces really is.
Another way is to select all code, usually editors will distinguish between spaces and tabs.
Related
I have generated a .csv file with a list of assets and have had to go back and make some changes. which require me to regenerate my NFT Images(done this multiple times at this point) But now the script isn't recognizing my .csv file and even allowing me to run the script that has worked flawlessly up until this point...
def generateOneRandRow(ADATvID):
FILENAME = "ADA Tv" + str(ADATvID)
NO = ADATvID
BACKGROUND = randBackground()
ACCESSORIES = randAccessories()
HEAD = randHead()
HAT = randHat()
BODY = randBody()
CHEST = randChest()
ARMS = randArms()
FACE = randFace()
singleRow = [FILENAME, NO, BACKGROUND, ACCESSORIES, HEAD, HAT, BODY, CHEST, ARMS, FACE]
def checkIfExists(checkRow):
aData = pd.read_csv('adalist.csv')
index_list = aData[(aData['Background'] == checkRow[2])
& (aData['Accessories'] == checkRow[3]) &
(aData['Head'] == checkRow[4]) &
(aData['Hat'] == checkRow[5]) &
(aData['Body'] == checkRow[6]) &
(aData['Chest'] == checkRow[7]) &
(aData['Arms'] == checkRow[8]) &
(aData['Face'] == checkRow[9])].index.tolist()
if index_list == []:
return False
else:
return True
df = pd.read_csv(adalist.csv)
rowCount = df["NO"].count()
print("number of rows is:" + str(rowCount))
the first appearance of adalist.csv shows fine. the last appearance is giving me WHY!?!?!?!
The .csv is in the same Source folder as everything else... this error just occurred and wont even allow me to press Run on my script.
As stated before, this script ran FLAWLESSLY multiple times, Up until I muted some code to convert the .csv into JSON for Metadata. even removing the JSON conversion its still not recognizing the .csv
Please help... I don't have the days it took me to re organize 3500 Images to my Liking [Face Palm]
When trying to create a conditional statement i get this error. I have tried many things over the last week to get this working but everything i try is failing.
Can anyone shed some light if this is specific to pynmea nodule?
def parse_gps(incoming_data):
if incoming_data.find("GGA") > 0:
data = pynmea2.parse(incoming_data)
print("Timestamp: %s // Lat: %s // Lon: %s // Satellites: %s " % (data.timestamp, data.latitude,
data.longitude, data.num_sats))
return data
while True:
gps_fix = ser.readline().decode('ascii')
gps_data = parse_gps(gps_fix)
if gps_data.num_sats > 7:
break
else:
print("No data")```
Should find a fix of satellites greater than 7 in order to gain a valid fix then break.
while True:
gps_fix = ser.readline().decode('ascii')
gps_data = parse_gps(gps_fix)
if gps_data is not None and int(gps_data.num_sats) > 7:
break```
After a few errors about str and int i finally managed to work out the fix.
I was trying to make a python game using only characters, honestly I did it, but the end condition was too vague. To make one, I simply assigned startLocation as a normal location, and having finished the objective, I would return to the starting location and quit the game to give new line texts. However:
def locations():
startLocation = random.choice(mapaGrid)
monsterLocation = random.choice(mapaGrid)
wellLocation = random.choice(mapaGrid)
goldLocation = random.choice(mapaGrid)
arrowLocation = random.choice(mapaGrid)
if monsterLocation == goldLocation or monsterLocation == startLocation or goldLocation == startLocation or monsterLocation == arrowLocation or wellLocation == goldLocation or wellLocation == startLocation or wellLocation == monsterLocation:
return locations()
return startLocation, monsterLocation, goldLocation, arrowLocation, wellLocation
#Locais do jogador, monstro, ouro, poco, flecha e entrada.
playerLocation, monsterLocation, goldLocation, arrowLocation, wellLocation, startLocation = locations()
So this is where the code fails. When I assign startLocation to locations() in the end, I get the error in the title, even though adding any other completely made up location didn't result in this error. I did try searching but due to my inexperience I couldn't relate the answers to my code.
You return 5 elements:
return startLocation, monsterLocation, goldLocation, arrowLocation, wellLocation
^1 ^2 ^3 ^4 ^5
While in the values that you try to set from the function - you have six of them:
playerLocation, monsterLocation, goldLocation, arrowLocation, wellLocation, startLocation = locations()
^1 ^2 ^3 ^4 ^5 ^6
What do you expect from python to put in the 6th variable?
The error that you got is that you can't assign into 6 variables, because you returned only 5.
I am writing a simple python program on a raspberry pi and I am quite new to python programming. I have defined a function called GetMessage which has no parameters and returns a variable which I called data, but I am getting an error which states
File "Raspberry_pi.py", line 39
return none
^
SyntaxError: invalid syntax
import os
import glob
import time
import RPi.GPIO as GPIO
from math import *
from bluetooth import *
from RPIO import PWM
os.system('sudo hciconfig hci0 pisca')
os.system('sudo hciconfig hci0 name "De Quadcoptur"')
servo = PWM.Servo()
StartSpin()
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
GetMessage()
DecodeInput()
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
def GetMessage():
advertise_service( server_sock, "XT1032", #phone bluetooth name
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
#protocols = [ OBEX_UUID ]
)
client_sock, client_info = server_sock.accept()
try:
data = client_sock.recv(1024)
if len(data) == 0: break
print "received [%s]" % data
client_sock.close()
server_sock.close()
except IOError:
pass
break
return data
def StartSpin():
# Set servo on GPIO17 to 1200µs (1.2ms)
servo.set_servo(17, 1000)
servo.set_servo(18, 1000)
servo.set_servo(19, 1000)
servo.set_servo(20, 1000)
time.sleep(1)
servo.stop_servo(17)
servo.stop_servo(18)
servo.stop_servo(19)
servo.stop_servo(20)
#Check if more pulses is faster
time.sleep(2000)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
servo.stop_servo(17)
servo.stop_servo(18)
servo.stop_servo(19)
servo.stop_servo(20)
return None
def DecodeInput():
data = GetMessage()
if(data == 'start')
StartSpin()
return 0
else if(data[0] == 'U')
data.strip('U')
UpPower = int(data)
SetUpPower(UpPower)
else if(data[0] == 'P')
data.strip('P')
PitchPower = int(data)
SetPitchPower
else
data.strip('P')
RollPower = int(data)
SetPower(UpPower, PitchPower, RollPower)
return None
def SetPower(UpPower, PitchPower, RollPower):
#Make Arbitrary Values
Motor1Power = UpPower #Front Left
Motor2Power = UpPower #Front Right
Motor3Power = UpPower #Back Left
Motor4Power = UpPower #Back Right
PitchPower = PitchPower /2
RollPower = RollPower /2
if(PitchPower < 25)
Motor1Power = Motor1Power + abs(25-PitchPower)
Motor2Power = Motor1Power + abs(25-PitchPower)
else
Motor3Power = Motor3Power + (PitchPower-25)
Motor4Power = Motor4Power + (PitchPower-25)
if(RollPower < 25)
Motor1Power = Motor1Power + abs(25-RollPower)
Motor3Power = Motor3Power + abs(25-RollPower)
else
Motor2Power = Motor2Power + (RollPower - 25)
Motor4Power = Motor4Power + (RollPower - 25)
What is causing this error and how can I fix it?
Edit: I have defined data as a global variable and the error now is
File "Raspberry_pi.py", line 39
return data
^
SyntaxError: invalid syntax
There are a number of syntax problems in your code. Because of the nature of SyntaxError exceptions (which are raised when the interpreter doesn't understand the code syntax), the error messages may not identify the right line as the source of the problem.
The first syntax error I see is that you're using break in the GetMessage function without it being in a loop. A break statement is only useful within a for or while block, and using one elsewhere (in an except block in this case) is a syntax error.
The next set of errors have to do with missing colons. Each of the conditional branches in DecodeInput and SetPower need to have a colon after the condition: if condition1:, elif condition2:, else:
It's also an error to use else if rather than elif (you could make it work if you added a colon, a newline and an extra level of indentation after else:, then used a separate if statement, but that would be wasteful of space).
There are some additional issues, but they're not syntax errors. For instance, you're calling your functions from top-level code before they've been defined, and DecodeInput has a line with the bare expression SetPower which doesn't do anything useful (you probably want to call SetPower with some argument).
Hopefully this will get you on the right track.
Once you get your colons fixed, you'll probably run into a problem with your GetMessage syntax. You cannot break unless you're inside of a loop. If you intend to return from an exception, you don't need the pass call. An example (simplified from your code) of how this method could (should?) look:
def GetMessage():
data = None
try:
data = [1,2]
if len(data) == 0:
return None
except IOError:
return None
return data
Clearly you'll want to replace the bulk of the method with your own code, and determine if you really want to return from the function at the points where you put breaks.
First of, i'm sort of new to Python so sorry if this question is obvious. The detect english module appears to be wrong, but it functions perfectly fine when calling it and running it on its own, theres no errors when running it alone and i've rewritten it a couple times to triple check it.
Traceback (most recent call last):
File "H:\Python\Python Cipher Program\transposition hacker.py", line 49, in <module>
main()
File "H:\Python\Python Cipher Program\transposition hacker.py", line 11, in main
hackedMessage = hackTransposition(myMessage)
File "H:\Python\Python Cipher Program\transposition hacker.py", line 34, in hackTransposition
if detectEnglish.isEnglish(decryptedText):
File "H:\Python\Python Cipher Program\detectEnglish.py", line 48, in isEnglish
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
this is the error i am getting when trying to run the Transposition Hacker (copied directly from here
Here is the code for the Detect English Module
# Detect english Module
# to use this code
# import detectEnglish
# detectEnglish.isEnglish(somestring)
# returns true of false
# there must be a dictionary.txt file in the same directory
# all english words
# one per line
UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary()
dictionaryFile = open('Dictionary.txt')
englishWords = {}
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
dictionaryFile.close()
return englishWords
ENGLISH_WORDS = loadDictionary()
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possibleWords)
def removeNonLetters(message):
lettersOnly = []
for symbol in message:
if symbol in LETTERS_AND_SPACE:
lettersOnly.append(symbol)
return ''.join(lettersOnly)
def isEnglish(message, wordPercentage=20, letterPercentage=85):
# by default 20% of the words mustr exist in dictionary file
# 85% of charecters in messafe must be spaces or letters
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
numLetters = len(removeNonLetters(message))
messageLettersPercentage = float(numLetters) / len(message) * 100
lettersMatch = messageLettersPercentage >= letterPercentage
return wordsMatch and lettersMatcht
getEnglishCount looks like it is missing a return statement. If python gets to the end of a function without hitting a return statement it will return None as you're seeing.
try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
# if possibleWords == []: # redundant
# return 0.0
return len(possibleWords)
Edit: #Kevin Yea I think you're right - there was more in that function. Maybe try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0.
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return matches / len(possibleWords)
I'd guess the indentation somehow got changed when you copy and pasted the code, with the return statement nested under the if.
As the other poster has said, you're missing a return for the getEnglishCount method, so it's returning NoneType, meaning that there is no value to be returned.
You can't do math on NoneTypes, so the NoneType*100 fails, which is what the bottom of your error traceback says.