I'm trying to simulate a substring in Python but I'm getting an error:
length_message = len(update)
if length_message > 140:
length_url = len(short['url'])
count_message = 140 - length_url
update = update["msg"][0:count_message] # Substring update variable
print update
return 0
The error is the following:
Traceback (most recent call last):
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 54, in <module>
x.updateTwitterStatus({"url": "http://xxx.com/?cat=49s", "msg": "Searching for some ....... tips?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffff "})
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 35, in updateTwitterStatus
update = update["msg"][0:count_message]
TypeError: string indices must be integers
I can't do this?
update = update["msg"][0:count_message]
The variable "count_message" return "120"
Give me a clue.
Best Regards,
UPDATE
I make this call, update["msg"] comes from here
x = TwitterC()
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=49", "msg": "Searching for some ...... ....?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffffddddddddddddddddd"})
Are you looping through this code more than once?
If so, perhaps the first time through update is a dict, and update["msg"] returns a string. Fine.
But you set update equal to the result:
update = update["msg"][0:int(count_message)]
which is (presumably) a string.
If you are looping, the next time through the loop you will have an error because now update is a string, not a dict (and therefore update["msg"] no longer makes sense).
You can debug this by putting in a print statement before the error:
print(type(update))
or, if it is not too large,
print(repr(update))
Related
I want to access large range value as this higher end value will be change sometimes as I couldnt able to print last value, If I give lower range it is getting printed but when I give higher range like 73138176 or more than 7 digits it is getting memory error,as I am using Python 2.7.10, can anyone help me to get print the value of last range in this version of Python
lbas_on_bank = []
start=0
end=73138176
for lba in range(start,end):
if len(lbas_on_bank)>50:
lbas_on_bank = []
else:
lbas_on_bank.append(lba)
last_written_lba = lbas_on_bank[-1]
print(last_written_lba)
output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
Use xrange() instead of range()
Or
try:
your code..
except MemoryError as er:
print(er)
Trying to adapt a basic profiler for bash scripts, block of code below.
Can't figure out why profiling code with a "if branch" throws exception (for example when running this code with a duplicate file). From what I've traced, it somewhere creates an extra index value. My apologies if this is trivial as I'm new to Python, but any suggestions on where could be the issue or how to remedy it would be greatly appreciated
def collect_timings(profiled_line, i):
if i == len(results) - 1:
return [0] + profiled_line
timing = float(results[i+1][1].replace(".N", "")) - float(profiled_line[1].replace(".N", ""))
return [timing] + profiled_line
Error:
Traceback (most recent call last):
File "./profile", line 67, in <module>
main(sys.argv)
File "./profile", line 51, in main
profiling_time = map(collect_timings, results, range(len(results)))
File "./profile", line 24, in collect_timings
timing = float(results[i+1][1].replace(".N", "")) - float(profiled_line[1].replace(".N", ""))
IndexError: list index out of range
Found the answer, posting in case it proves useful for someone.
The issues was a with a output redirection:
echo "Found '$file' is a duplicate of '${filecksums[$cksum]}'" >&2
That got passed as a separate entry to results:
["Found 'txt2/0122file.bck' is a duplicate of 'txt2/0113file.txt'\n"]
No idea how to make the code run with redirects, but it's not necessary, so I'll just avoid it.
you say:
if i == len(results) - 1:
below you say :
timing = float(results[i+1][1].replace(".N", ""))
so you check if "i" show the last element of results array (i.e. results has 5 cells from 0 to 4 and you check if i == 4( len(results) == 5 in this case AND NOT 4) ) and then you say results[i+1] which in the example above is equal to results[5] which is out of bounds.
Maybe you meant results[i]?
I have this code that will allow me to count the number of missing rows of numbers within the csv for a script in Python 3.6. However, these are the following errors in the program:
Error:
Traceback (most recent call last):
File "C:\Users\GapReport.py", line 14, in <module>
EndDoc_Padded, EndDoc_Padded = (int(s.strip()[2:]) for s in line)
File "C:\Users\GapReport.py", line 14, in <genexpr>
EndDoc_Padded, EndDoc_Padded = (int(s.strip()[2:]) for s in line)
ValueError: invalid literal for int() with base 10: 'AC-SEC 000000001'
Code:
import csv
def out(*args):
print('{},{}'.format(*(str(i).rjust(4, "0") for i in args)))
prev = 0
data = csv.reader(open('Padded Numbers_export.csv'))
print(*next(data), sep=', ') # header
for line in data:
EndDoc_Padded, EndDoc_Padded = (int(s.strip()[2:]) for s in line)
if start != prev+1:
out(prev+1, start-1)
prev = end
out(start, end)
I'm stumped on how to fix these issues.Also, I think the csv many lines in it, so if there's a section that limits it to a few numbers, please feel free to update me on so.
CSV Snippet (Sorry if I wasn't clear before!):
The values you have in your CSV file are not numeric.
For example, FMAC-SEC 000000001 is not a number. So when you run int(s.strip()[2:]), it is not able to convert it to an int.
Some more comments on the code:
What is the utility of doing EndDoc_Padded, EndDoc_Padded = (...)? Currently you are assigning values to two variables with the same name. Either name one of them something else, or just have one variable there.
Are you trying to get the two different values from each column? In that case, you need to split line into two first. Are the contents of your file comma separated? If yes, then do for s in line.split(','), otherwise use the appropriate separator value in split().
You are running this inside a loop, so each time the values of the two variables would get updated to the values from the last line. If you're trying to obtain 2 lists of all the values, then this won't work.
I am processing a tab-delimited data set of almost three million lines. Since I have enough memory, I am loading the entire data file into memory via a list. I then go and clean up inconsistencies with the data row-by-row. After 150,000 lines of successful computation, the program halts with this error:
Traceback (most recent call last):
File "C:/Users/me/dataset_cleanup_utility/dataset_cleanup.py", line 466, in <module>
ROWS_PASSED = passed
File "C:/Users/me/dataset_cleanup_utility/dataset_cleanup.py", line 43, in dataset_cleanup
row = make_consistent(row, row_count)
File "C:/Users/me/dataset_cleanup_utility/dataset_cleanup.py", line 180, in make_consistent
row[11] = remove("(STAFF)", "", str(row[11]))
IndexError: string index out of range
The code sample that causes this is below:
if "(STAFF)" in str(row[11]):
row[11] = remove("(STAFF)", "", str(row[11]))
def remove(unwanted, wanted, _str):
s = str(_str).rsplit(unwanted, 1)
if len(s) == 2:
return str(s[0]) + wanted + str(s[1])
else:
return str(s[0]) + wanted
Here, row is the list containing all of the columns for a given row and the IndexError is being thrown INSIDE the if statement that checks row[11]. So what this error is telling me is that the row[11] was okay when evaluating the if statement, but inside the if statement, when evaluated again, row[11] no longer exists. How could this be if no changes to row[11] occurred after the if statement was evaluated?
Error:
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "/Users/georg/Programmierung/Glyphs/Glyphs/Glyphs/Scripts/GlyphsApp.py", line 59, in __iter__
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_convenience.py", line 589, in enumeratorGenerator
yield container_unwrap(anEnumerator.nextObject(), StopIteration)
objc.error: NSGenericException - *** Collection <__NSArrayM: 0x7f9906245480> was mutated while being enumerated.
I know this error occurs because I'm trying to delete objects from the array while also enumerating these objects. But I don't know how to solve it. I'm fairly new to object orientated programming and am limiting myself to scripting.
I searched the web and it seems to solve the error, I have to copy the array before deleting objects from it. When I'm tying to copy the array via deepcopy
import copy
pathcopy = copy.deepcopy(thisLayer.paths)
right before for path in thisLayer.paths:
But in this case I get the following error:
Cannot pickle Objective-C objects
Usually the program crashes after the first Glyph. For clarification: I work in Glyphsapp, a Typedesigning software.
Here is the Code:
# loops through every Glyph and deletes every path with nodes on the left half
for myGlyph in Glyphs.font.glyphs:
glname = myGlyph.name
thisLayer = Glyphs.font.glyphs[glname].layers[1]
middle = thisLayer.bounds.size.width/2+thisLayer.LSB
thisGlyph = thisLayer.parent
for path in thisLayer.paths: # this is where the code crashes
for thisNode in path.nodes:
if thisNode.position.x < middle:
#print thisNode.position.x
try:
thisLayer = path.parent()
except Exception as e:
thisLayer = path.parent
try:
thisLayer.removePath_ ( thisNode.parent() )
except AttributeError:
pass
Thank you in advance
Thank you very much Andreas,
with your help I was able to fix my code :-)
Here is the outcome:
for myGlyph in Glyphs.font.glyphs:
glname = myGlyph.name
thisLayer = Glyphs.font.glyphs[glname].layers[1]
middle = thisLayer.bounds.size.width/2+thisLayer.LSB
thisGlyph = thisLayer.parent
for path in thisLayer.paths:
for thisNode in path.nodes:
if thisNode.position.x < middle:
nodeList = []
nodeList.append(thisNode.parent())
nLCopy = nodeList[:]
for ncontainer in nLCopy:
thisLayer.removePath_ ( ncontainer )