I know there's been quite a few of these but after looking through them, I wasn't able to solve my issue. I'm also still learning Python so a simple mix up could be happening.
Thus far the error is being reached on the line with the constructed for loop.
# down
column = 2
grid = [ 10, 10 ]
while range > 0:
# grab at the top
cur = genes[((grid[1] - 1) * grid[0]) + column]
prev = cur
for a in range((grid[1] - 2), -1, -1):
# start one below from the top
cur = genes[(a * grid[0]) + column]
genes[(a * grid[0]) + column] = prev
prev = cur
# now apply the change back to the top
genes[((grid[1] - 1) * grid[0]) + column] = prev
if get_fitness(genes, grid) > fitness:
print("After Down")
board = Board(genes, grid)
board.print()
print("-------------------")
return
range -= 1
As requested
Traceback (most recent call last):
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/tetris.py", line 144, in test_double_block
self.solveDouble([4, 4])
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/tetris.py", line 167, in solveDouble
best = genetic.get_best(fnGetFitness, None, optimalFitness, geneset,
fnDisplay, custom_mutate=fnCustomMutate, custom_create=fnCreate, maxAge=10)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 105, in get_best
maxAge, poolSize):
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 131, in _get_improvement
child = new_child(parent, pindex, parents)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 102, in fnNewChild
return fnMutate(parent)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 74, in fnMutate
return _mutate_custom(parent, custom_mutate, get_fitness)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 47, in _mutate_custom
custom_mutate(childGenes)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/tetris.py", line 159, in fnCustomMutate
mutate(genes, grid, window)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/tetris.py", line 65, in mutate
for a in range((grid[1] - 2), -1, -1):
TypeError: 'int' object is not callable
You defined range as a number
while range > 0:
...
range -= 1
But you later used it as a function
for a in range(...):
Rename the range integer to something else
For example, you could do a backward for loop
for r in range(top_range, 0, -1):
...
Related
Error:
Traceback (most recent call last): File
"/root/PycharmProjects/Capstone2/main", line 207, in
for paramIndex in range(0, 4): TypeError: 'list' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/root/PycharmProjects/Capstone2/main", line 249, in
print('stream ending') File "/usr/lib/python3/dist-packages/picamera/camera.py", line 758, in
exit
self.close() File "/usr/lib/python3/dist-packages/picamera/camera.py", line 737, in
close
self.stop_recording(splitter_port=port) File "/usr/lib/python3/dist-packages/picamera/camera.py", line 1198, in
stop_recording
encoder.close() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 431, in
close
self.stop() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 815, in
stop
super(PiVideoEncoder, self).stop() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 419, in
stop
self._close_output() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 349, in
_close_output
mo.close_stream(output, opened) File "/usr/lib/python3/dist-packages/picamera/mmalobj.py", line 371, in
close_stream
stream.flush() ValueError: flush of closed file
Relevant Code:
angle = []
distance = []
speed = []
current = []
timestamp = []
parameterList = []
parameterList.extend((angle, distance, speed, current, timestamp))
for paramIndex in range(0, 4): # LINE 207
# Select Range
range = getRange(index, paramIndex + 5)
cell_list = sheet.range(range[0], range[1], range[2], range[3])
cellIndex = 0
for cell in cell_list:
try:
cell.value = parameterList[paramIndex][cellIndex]
except:
print("PI: " + str(paramIndex))
print("CI: " + str(cellIndex))
print("PL LEN: " + str(len(parameterList)))
print("P LEN: " + str(len(parameterList[paramIndex])))
My Thoughts:
The error makes me think that paramIndex is a list and not an integer but the code executes fine for the first four iterations. This makes me think that there is something wrong with my last list (timestamp). The only thing that I can imagine being wrong with my last list is some sort of index out of bounds issue but...
The except block is never hit
The largest value cellIndex reaches is 30 (expected)
The length of parameterList is 5 (expected)
The length of timestamp is 31 (expected)
I am stumped. If anyone can offer some help that would be greatly appreciated.
paramIndex is fine but you need to avoid calling variables the same name as your functions. In this case, range() is a standard python function but you create a variable called 'range'. Thereafter if you tried to use the range function you'd get an 'object is not callable' error because it's trying to use your range object as the standard range function.
If you insist on wanting to keep the range object name then use xrange() instead of range() where you define your for loop and you shouldn't get any conflicts.
import random
foundwords = []
wordsDict = {}
with open("text", "r") as file:
contents = file.read().replace('\n',' ')
words = contents.split(' ')
def findwords(word):
for i in range(len(words) - 1):
if words[i] == word:
if not words[i + 1] == '':
foundwords.append(words[i + 1])
return foundwords
for word in words:
wordsDict.setdefault(word, findwords(word))
# for i in range(len(words) - 1):
# findwords(words[i])
# wordsDict.setdefault(words[i], foundwords)
# del foundwords[:]
def nextword(word):
wordList = wordsDict.get(word.lower())
new = wordList[random.randint(0, len(wordList) - 1)]
return new
def assemble():
final = [words[random.randint(0, len(words))].capitalize()]
final.append(nextword(final[-1]))
print(final)
assemble()
I have tried to create a markov-chain project, however, I get the following error:
Traceback (most recent call last):
File "main.py", line 32, in <module>
assemble()
File "main.py", line 28, in assemble
final.append(nextword(final[0]))
File "main.py", line 23, in nextword
new = wordList[random.randint(0, len(wordList) - 1)]
File "/usr/local/lib/python3.6/random.py", line 220, in randint
return self.randrange(a, b+1)
File "/usr/local/lib/python3.6/random.py", line 198, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
exited with non-zero status
And sometimes this error:
Traceback (most recent call last):
File "main.py", line 31, in <module>
assemble()
File "main.py", line 28, in assemble
final.append(nextword(final[0]))
File "main.py", line 23, in nextword
new = wordList[random.randint(0, len(wordList) - 1)]
TypeError: object of type 'NoneType' has no len()
I have no idea how to start fixing this problem. I'm only a beginner programmer, so if my code is inefficient or anything, I apologize. Also, I'm not sure if this ok to post as a question, sorry.
I'm trying to write various predicates on simple candle stick structures. For example one component of a '3 green candles in a row' predicate would require a look back of -4
To start off simple I try an test it with a 'higher_highs' predicate. If the close of the previous candle is below the current candles close the function returns true. Below is my code:
from pyalgotrade import eventprofiler
from pyalgotrade.barfeed import csvfeed
class single_event_strat( eventprofiler.Predicate ):
def __init__(self,feed):
pass
def higher_highs(self, instrument, bards):
#prev_three = bards[-4]
#prev_two = bards[-3]
prev = bards[-2]
curr = bards[-1]
if prev.getOpen() < curr.getOpen():
return True
return False
def eventOccurred(self, instrument, bards):
if self.higher_highs(instrument, bards):
return True
else:
return False
def main(plot):
feed = csvfeed.GenericBarFeed(0)
feed.addBarsFromCSV('FCT', "FCT_daily_converted.csv")
predicate = single_event_strat(feed)
eventProfiler = eventprofiler.Profiler( predicate, 20, 20)
eventProfiler.run(feed, True)
results = eventProfiler.getResults()
print "%d events found" % (results.getEventCount())
if plot:
eventprofiler.plot(results)
if __name__ == "__main__":
main(True)
However I get an IndexError :
Traceback (most recent call last):
File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 44, in <module>
main(True)
File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 36, in main
eventProfiler.run(feed, True)
File "C:\Python27\lib\site-packages\pyalgotrade\eventprofiler.py", line 215, in run
disp.run()
File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 102, in run
eof, eventsDispatched = self.__dispatch()
File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 90, in __dispatch
if self.__dispatchSubject(subject, smallestDateTime):
File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 68, in __dispatchSubject
ret = subject.dispatch() is True
File "C:\Python27\lib\site-packages\pyalgotrade\feed\__init__.py", line 105, in dispatch
self.__event.emit(dateTime, values)
File "C:\Python27\lib\site-packages\pyalgotrade\observer.py", line 59, in emit
handler(*args, **kwargs)
File "C:\Python27\lib\site-packages\pyalgotrade\eventprofiler.py", line 172, in __onBars
eventOccurred = self.__predicate.eventOccurred(instrument, self.__feed[instrument])
File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 20, in eventOccurred
if self.higher_highs(instrument, bards):
File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 11, in higher_highs
prev = bards[-2]
File "C:\Python27\lib\site-packages\pyalgotrade\dataseries\__init__.py", line 90, in __getitem__
return self.__values[key]
File "C:\Python27\lib\site-packages\pyalgotrade\utils\collections.py", line 141, in __getitem__
return self.__values[key]
IndexError: list index out of range
I'm still trying to figure out how the EP works. It's interesting because in the buyongap example there is a look back period of bards[-2],
def __gappedDown(self, instrument, bards):
ret = False
if self.__stdDev[instrument][-1] is not None:
prevBar = bards[-2]
currBar = bards[-1]
low2OpenRet = (currBar.getOpen(True) - prevBar.getLow(True)) / float(prevBar.getLow(True))
if low2OpenRet < (self.__returns[instrument][-1] - self.__stdDev[instrument][-1]):
ret = True
return ret
however it's nestled in if self.__stdDev[instrument][-1] is not None: statement, my predicate requires no TA indicators, so how could I access the previous bards?
The problem is that on the first call to eventOccurred bards only has one item, so trying to do bards[-2] will fail. Check the length of bards first.
Here is some code on python 3 using Pandas, interpreter is 3.4.1
import pandas as pd
pd.set_option('display.width', 300)
file = open('C:\PythonData\Result.csv', 'w')
file.write('"StopFirstIndex"' + ';' + '"StopLastIndex"' + ';' \
+ '"GOV_NUMBER"' + ';' + '"StopTime"' + '\n')
df1 = pd.read_csv('C:\PythonData\data4.csv', ",", header=0).sort_index(by=['CAR_ID', 'DATE_TO'])
df1.index = range(0, len(df1))
StopFirstIndex = 0
StopLastIndex = 0
CntZeroSpeedRows = 0
for index, row in df1.iterrows():
if row['SPEED'] == df1.get_value(index + 1, 'SPEED') == 0 and row['CAR_ID'] == df1.get_value(index + 1, 'CAR_ID'):
if CntZeroSpeedRows >= 1:
CntZeroSpeedRows += 1
else:
CntZeroSpeedRows = 1
else:
if CntZeroSpeedRows >= 3:
StopFirstIndex = index - CntZeroSpeedRows
StopLastIndex = index
StopTime = pd.to_datetime(df1.get_value(StopLastIndex, 'DATE_TO'), dayfirst=True) - \
pd.to_datetime(df1.get_value(StopFirstIndex, 'DATE_TO'), dayfirst=True)
tempdf1 = pd.concat([df1[StopFirstIndex:StopLastIndex+1]['LATITUDE'],
df1[StopFirstIndex:StopLastIndex+1]['LONGITUDE']], axis=1)
file.write('"' + str(StopFirstIndex) + '";"' + str(StopLastIndex) + '";"' \
+ str(df1.get_value(StopFirstIndex, 'GOV_NUMBER')) + '";"' + str(StopTime) + '"' + '\n') # making csv
print(StopFirstIndex, StopLastIndex, df1.get_value(StopFirstIndex, 'GOV_NUMBER'), StopTime) # printing results in console
CntZeroSpeedRows = 0
file.close()
Making of the csv file is ok, but if I print results in console, after printing correct results, it shows me following error:
> Traceback (most recent call last):
> File "C:/Users/Moiseev/PycharmProjects/untitled1/test1.py", line 21, in <module>
> if row['SPEED'] == df1.get_value(index + 1, 'SPEED') == 0 and row['CAR_ID'] == df1.get_value(index + 1, 'CAR_ID'):
> File "C:\Users\Moiseev\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1542, in get_value
return engine.get_value(series.values, index)
File "index.pyx", line 97, in pandas.index.IndexEngine.get_value (pandas\index.c:2993)
File "index.pyx", line 105, in pandas.index.IndexEngine.get_value (pandas\index.c:2808)
File "index.pyx", line 149, in pandas.index.IndexEngine.get_loc (pandas\index.c:3534)
File "hashtable.pyx", line 381, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:7035)
File "hashtable.pyx", line 387, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6976) KeyError: 1000
> Process finished with exit code 1
So, there is two questions:
1. Is it critical?
2. How can I remove this error?
I'm trying to segment one window in curses into several sub-windows (with derwin()).
The code creates two sub-windows and I can add a string; no problem with the first function. The second one is pretty much exactly the same but gives me an error when I try to add a string with addstr()
class Window(GUI):
'''
Window-object
'''
def __init__(self, y_max , x_max, y_pos , x_pos, Target, screen):
self.Win_Count = 0
self.y_pos = y_pos
self.x_pos = x_pos
self.y_max = y_max
self.x_max = x_max
self.parent = screen
self.Target = Target
#Window-Objects
self.Win = self.create_win_parent(y_pos)
self.Name_Win = self.create_name_win(self.Win)
self.IP_Win = self.create_ip_win(self.Win)
def create_win_parent(self, y_pos):
y_size = 1
x_size = self.x_max - self.x_pos
new_win_obj = self.parent.derwin(y_size, x_size, self.y_pos, 0)
self.Win_Count += 1
return new_win_obj
def create_name_win(self, Win_Obj):
x = Win_Obj.derwin(1,40, 0,0)
x.box()
x.addstr(0,5," CUSTOMER NAME ")
return x
def create_ip_win(self, Win_Obj):
x = Win_Obj.derwin(1,15, 0,41)
x.box()
x.addstr(0,5," IP-ADDRESS ")
return x
I'm getting this vague error:
Traceback (most recent call last):
File "./2pollng.py", line 229, in <module>
wrapper(main) # Enter the main loop
File "/usr/lib/python2.6/curses/wrapper.py", line 43, in wrapper
return func(stdscr, *args, **kwds)
File "./2pollng.py", line 222, in main
Main_App.Run(screen)
File "./2pollng.py", line 106, in Run
self.Create_Win(self.Inv.index(e), e)
File "./2pollng.py", line 90, in Create_Win
Win_Obj = Window(self.y_max, self.x_max, y_pos, x_pos, Target_x, self.screen)
File "./2pollng.py", line 141, in __init__
self.IP_Win = self.create_ip_win(self.Win)
File "./2pollng.py", line 160, in create_ip_win
x.addstr(0,5," IPADDRESS ")
_curses.error: addstr() returned ERR
def create_ip_win(self, Win_Obj):
x = Win_Obj.derwin(1,15, 0,41)
x.box()
x.addstr(0,5," IP-ADDRESS ")
return x
In this function Win_Obj.derwin(1,15, 0,41) shows that x-pos should between 0 and 14. While in the code addstr(0,5," IP-ADDRESS ") x starts at 5 and the length of string " IP-ADDRESS " is greater than (15-5). So you got the ERROR.
Not really sure about the specifics but it had ( as indicated by the interpreter, duh) something to do with the strings and them not having enough space in the subwindows i created.