I'm trying to port a project from Python 2 to 3 but am getting stuck with some errors. The code runs without a problem under Python 2.7.8. The error is the following:
[INFO ] [Text ] Provider: sdl2
Traceback (most recent call last):
File "C:\Users\xx\PycharmProjects\Simulator\simulator.pyw", line 2, in <module>
from bin.ui.ui import start
File "C:\Users\xx\PycharmProjects\Simulator\bin\ui\ui.py", line 30, in <module>
import bin.global_variables as global_variables
File "C:\Users\xx\PycharmProjects\Simulator\bin\global_variables.py", line 19, in <module>
ANTIBIOTICS = {"Generic Antibiotic": Antibiotic("Generic Antibiotic")}
File "C:\Users\DrPai\PycharmProjects\Simulator\bin\classes\Antibiotic.py", line 17, in __init__
line_width=1.01) # SmoothLinePlot
File "C:\Users\xx\PycharmProjects\Simulator\bin\deps\kivy_graph\__init__.py", line 1031, in __init__
super(Plot, self).__init__(**kwargs)
File "kivy\_event.pyx", line 243, in kivy._event.EventDispatcher.__init__
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
The relevant part of the code that the error is pointing too are:
global_variables.py
ANTIBIOTICS = {"Generic Antibiotic": Antibiotic("Generic Antibiotic")}
Antibiotic.py
class Antibiotic(object):
_total_antibiotics = 0 # int
def __init__(self, name):
self._id = 'ant' + str(Antibiotic._total_antibiotics) # str
self._name = name # str
self._line_color = hsv_to_rgb(*NewColor.new_color()) # (R,G,B)
self._plot = SmoothLinePlot(points=[(0, 0)],
color=self._line_color,
line_width=1.01) # SmoothLinePlot
Antibiotic._total_antibiotics += 1
To draw the plots I'm relying on Kivy Graph widget accessible from here (https://github.com/kivy-garden/graph) and the error seems to be related to the code there:
__ init __.py
class Plot(EventDispatcher):
def __init__(self, **kwargs):
super(Plot, self).__init__(**kwargs)
self.ask_draw = Clock.create_trigger(self.draw)
self.bind(params=self.ask_draw, points=self.ask_draw)
self._drawings = self.create_drawings()
Kivy graph doesn't support line_width and removal of it solves the problem.
Related
I am trying to do a cdk deployment, where I am just copying the example from the documentation. See example below (https://docs.aws.amazon.com/cdk/api/v2/python/aws_cdk.aws_stepfunctions/StateMachineFragment.html#aws_cdk.aws_stepfunctions.StateMachineFragment)
from aws_cdk import (
# Duration,
Stack,
aws_stepfunctions as sfn,
aws_stepfunctions_tasks as tasks,
)
from constructs import Construct
class MyJob(sfn.StateMachineFragment):
def __init__(self, parent, id, *, job_flavor):
super().__init__(parent, id)
choice = sfn.Choice(self, "Choice").when(sfn.Condition.string_equals("$.branch", "left"), sfn.Pass(self, "Left Branch")).when(sfn.Condition.string_equals("$.branch", "right"), sfn.Pass(self, "Right Branch"))
# ...
self.start_state = choice
self.end_states = choice.afterwards().end_states
def start_state(self):
return self._start_state
def end_states(self):
return self._end_states
class CdkStateMachineFragmentStack(Stack):
def __init__(self, scope, id):
super().__init__(scope, id)
# Do 3 different variants of MyJob in parallel
parallel = sfn.Parallel(self, "All jobs").branch(MyJob(self, "Quick", job_flavor="quick").prefix_states()).branch(MyJob(self, "Medium", job_flavor="medium").prefix_states()).branch(MyJob(self, "Slow", job_flavor="slow").prefix_states())
sfn.StateMachine(self, "MyStateMachineFragmentTest",
definition=parallel
)
When deploying, I get the following error:
Traceback (most recent call last):
File "app.py", line 10, in
CdkStateMachineFragmentStack(app, "CdkStateMachineFragmentStack",
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/.venv/lib/python3.8/site-packages/jsii/_runtime.py", line 111, in call
inst = super().call(*args, **kwargs)
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/cdk_state_machine_fragment/cdk_state_machine_fragment_stack.py", line 34, in init
sfn.StateMachine(self, "MyStateMachineFragmentTest",
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/.venv/lib/python3.8/site-packages/jsii/_runtime.py", line 111, in call
inst = super().call(*args, **kwargs)
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/.venv/lib/python3.8/site-packages/aws_cdk/aws_stepfunctions/init.py", line 6871, in init
jsii.create(self.class, self, [scope, id, props])
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/.venv/lib/python3.8/site-packages/jsii/_kernel/init.py", line 336, in create
response = self.provider.create(
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/.venv/lib/python3.8/site-packages/jsii/_kernel/providers/process.py", line 363, in create
return self._process.send(request, CreateResponse)
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/.venv/lib/python3.8/site-packages/jsii/_kernel/providers/process.py", line 340, in send
raise RuntimeError(resp.error) from JavaScriptError(resp.stack)
RuntimeError: Cannot read properties of undefined (reading 'bindToGraph')
I tried already what is suggested in the following stack overflow post [https://stackoverflow.com/questions/70553737/cannot-read-properties-of-undefined-reading-bindtograph] getting a different error:
Traceback (most recent call last):
File "app.py", line 10, in
CdkStateMachineFragmentStack(app, "CdkStateMachineFragmentStack",
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/.venv/lib/python3.8/site-packages/jsii/_runtime.py", line 111, in call
inst = super().call(*args, **kwargs)
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/cdk_state_machine_fragment/cdk_state_machine_fragment_stack.py", line 34, in init
parallel = sfn.Parallel(self, "All jobs").branch(MyJob(self, "Quick", job_flavor="quick").prefix_states()).branch(MyJob(self, "Medium", job_flavor="medium").prefix_states()).branch(MyJob(self, "Slow", job_flavor="slow").prefix_states())
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/.venv/lib/python3.8/site-packages/jsii/_runtime.py", line 111, in call
inst = super().call(*args, **kwargs)
File "/home/workspace/development/cdk/cdk_test/cdk_state_machine_fragment/cdk_state_machine_fragment/cdk_state_machine_fragment_stack.py", line 18, in init
self.start_state = choice
AttributeError: can't set attribute
Could you support me?
Thanks,
Pablo
I am trying to do a tensorforce tutorial with a DQN algorithm, but I am running into some errors. It seems that tensorforce has been updated since this tutorial was written, so I am trying to figure things out on my own with the documentation. Anywho, here is my code.
import logging
from tensorforce.environments.openai_gym import OpenAIGym
from tensorforce.agents import DQNAgent
from tensorforce.execution import Runner
# def main():
gym_id = 'CartPole-v0'
max_episodes = 10000
max_timesteps = 1000
total_memory = 100
env = OpenAIGym(gym_id)
network_spec = [
dict(type='dense', size=32, activation='tanh'),
dict(type='dense', size=32, activation='tanh')
]
agent = DQNAgent(
# states_spec=env.states,
# actions_spec=env.actions,
states=env.states,
actions=env.actions,
# network_spec=network_spec,
batch_size=64,
memory=total_memory <-- Here is where my error is coming from.
)
runner = Runner(agent, env)
report_episodes = 10
def episode_finished(r):
if r.episode % report_episodes == 0:
logging.info("Finished episode {ep} after {ts} timesteps".format(ep=r.episode, ts=r.timestep))
logging.info("Episode reward: {}".format(r.episode_rewards[-1]))
logging.info("Average of last 100 rewards: {}".format(sum(r.episode_rewards[-100:]) / 100))
return True
print("Starting {agent} for Environment '{env}'".format(agent=agent, env=env))
runner.run(max_episodes, max_timesteps, episode_finished=episode_finished)
runner.close()
print("Learning finished. Total episodes: {ep}".format(ep=runner.episode))
# if __name__ == '__main__':
# main
With the error originating from
memory=total_memory
The documentation found here says that memory is required and that it must be an int>0, so I am confused. Any help would be sweet.
EDIT
Here is the traceback code.
Traceback (most recent call last):
File "test3.py", line 19, in <module>
agent = DQNAgent(
File "/home/dskinner/.local/lib/python3.8/site-packages/tensorforce/agents/dqn.py", line 217, in __init__
super().__init__(
File "/home/dskinner/.local/lib/python3.8/site-packages/tensorforce/agents/tensorforce.py", line 441, in __init__
super().__init__(
File "/home/dskinner/.local/lib/python3.8/site-packages/tensorforce/agents/agent.py", line 243, in __init__
super().__init__(
File "/home/dskinner/.local/lib/python3.8/site-packages/tensorforce/agents/recorder.py", line 50, in __init__
if 'type' in states or 'shape' in states:
TypeError: argument of type 'method' is not iterable
I'm a beginner with myhdl.
I try to translate the following Verilog code to MyHDL:
module ModuleA(data_in, data_out, clk);
input data_in;
output reg data_out;
input clk;
always #(posedge clk) begin
data_out <= data_in;
end
endmodule
module ModuleB(data_in, data_out, clk);
input [1:0] data_in;
output [1:0] data_out;
input clk;
ModuleA instance1(data_in[0], data_out[0], clk);
ModuleA instance2(data_in[1], data_out[1], clk);
endmodule
Currently, I have this code:
import myhdl
#myhdl.block
def ModuleA(data_in, data_out, clk):
#myhdl.always(clk.posedge)
def logic():
data_out.next = data_in
return myhdl.instances()
#myhdl.block
def ModuleB(data_in, data_out, clk):
instance1 = ModuleA(data_in(0), data_out(0), clk)
instance2 = ModuleA(data_in(1), data_out(1), clk)
return myhdl.instances()
# Create signals
data_in = myhdl.Signal(myhdl.intbv()[2:])
data_out = myhdl.Signal(myhdl.intbv()[2:])
clk = myhdl.Signal(bool())
# Instantiate the DUT
dut = ModuleB(data_in, data_out, clk)
# Convert tfe DUT to Verilog
dut.convert()
But it doesn't works because signal slicing produce a read-only shadow signal (cf MEP-105).
So, what is it the good way in MyHDL to have a writable slice of a signal?
Edit:
This is the error I get
$ python demo.py
Traceback (most recent call last):
File "demo.py", line 29, in <module>
dut.convert()
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/_block.py", line 342, in convert
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/conversion/_toVerilog.py", line 177, in __call__
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/conversion/_analyze.py", line 170, in _analyzeGens
File "/usr/lib/python3.6/ast.py", line 253, in visit
return visitor(node)
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/conversion/_analyze.py", line 1072, in visit_Module
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/conversion/_misc.py", line 148, in raiseError
myhdl.ConversionError: in file demo.py, line 4:
Signal has multiple drivers: data_out
You can use an intermediate list of Signal(bool()) as placeholder.
#myhdl.block
def ModuleB(data_in, data_out, clk):
tsig = [myhdl.Signal(bool(0)) for _ in range(len(data_in))]
instances = []
for i in range(len(data_in)):
instances.append(ModuleA(data_in(i), tsig[i], clk))
#myhdl.always_comb
def assign():
for i in range(len(data_out)):
data_out.next[i] = tsig[i]
return myhdl.instances()
A quick (probably non-fulfilling) comment, is that the intbv is treated as a single entity that can't have multiple drives. Two references that might help shed some light:
http://jandecaluwe.com/hdldesign/counting.html
http://docs.myhdl.org/en/stable/manual/structure.html#converting-between-lists-of-signals-and-bit-vectors
I want to create a custom ListCtrl "MyListCtrlCrafting" which pulls the data from a different class called "DBInterface" (actually it is not a real database, but a sophisticated python dictionary). There are tutorials on how to do that, I followed "Python in Action". The main points are: inherit from ListCtrl an set the style parameter to wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_VIRTUAL, call SetItemCount() during init() and override some methods.
To test how that works I made a small App which consists only of one (main-)frame, the virtual ListCtrl and a rudimentary version of DBInterface. Everything works out fine in this setting. But when I connect the classes of the real App, I get a Traceback:
Traceback (most recent call last):
File "DesktopCrafter.py", line 198, in <module>
controller = AppCtrl()
File "DesktopCrafter.py", line 186, in __init__
self.frame = GUI.MainWindow(back_end=self.back_end, crafting_controller=self.crafting_controller, parent=None, title='Desktop Crafter')
...
self.view = MyListCtrlCrafting(name='crafting-hand', back_end=self.db, crafting_controller=self.cc, parent=self, id=wx.ID_ANY)
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 107, in __init__
self.bindData()
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 121, in bindData
self.SetItemCount(count)
wx._core.wxAssertionError: C++ assertion "m_count == ListView_GetItemCount(GetHwnd())" failed at ..\..\src\msw\listctrl.cpp(3120) in wxListCtrl::SetItemCount(): m_count should match ListView_GetItemCount
In contrast to the simple App, the virtualListCtrl is now deeply nested. Can this error just be produced by wrong connections inside this nesting or between DBInterface and the ListCtrl? Or do I have to understand how m_count is calculated, to solve this error? If so, how can I read the _core file? I already read about ListCtrl in the core.py file, but it doesn't contain the relevant parts.
My problem with this traceback is that I don't understand why it is raised during SetItemCount(). This method should be something like a definition and since it is dealing with rows of a list, it should accept positive integers, and maybe 0, and maybe also -1 for standard. I plug in 5, so this cannot be the real problem going on here(?)
Any help or hint is much appreciated!
The complete Traceback:
Traceback (most recent call last):
File "DesktopCrafter.py", line 198, in <module>
controller = AppCtrl()
File "DesktopCrafter.py", line 186, in __init__
self.frame = GUI.MainWindow(back_end=self.back_end, crafting_controller=self.crafting_controller, parent=None, title='Desktop Crafter')
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 285, in __init__
self.InitUI()
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 299, in InitUI
self.panel = MainPanel(back_end=self.db, crafting_controller=self.cc)
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 251, in __init__
self.splitter = MySplitter(back_end=back_end, crafting_controller=crafting_controller)
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 229, in __init__
self.l_frame = LPanel(back_end=back_end, crafting_controller=crafting_controller)
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 188, in __init__
self.panel = CraftingPanel(back_end=back_end, crafting_controller=crafting_controller, *args, **kwargs)
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 154, in __init__
self.view = MyListCtrlCrafting(name='crafting-hand', back_end=self.db, crafting_controller=self.cc, parent=self, id=wx.ID_ANY)
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 107, in __init__
self.bindData()
File "d:\workspace-fun\DesktopCrafter\dc\util\DCUI.py", line 121, in bindData
self.SetItemCount(count)
wx._core.wxAssertionError: C++ assertion "m_count == ListView_GetItemCount(GetHwnd())" failed at ..\..\src\msw\listctrl.cpp(3120) in wxListCtrl::SetItemCount(): m_count should match ListView_GetItemCount
The virtual ListCtrl (both print's give me the expected results):
class MyListCtrlCrafting(wx.ListCtrl):
def __init__(self, name, back_end, crafting_controller, *args, **kwargs):
wx.ListCtrl.__init__(self, style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_VIRTUAL, *args, **kwargs)
self.name = name
self.db = back_end
self.cc = crafting_controller
#print(self.db.retrieveValue(['player', self.name]))
self.Bind(wx.EVT_LIST_CACHE_HINT, self.DoCacheItems)
self.bindData()
self.InsertColumn(0, "Slot")
self.InsertColumn(1, "Item")
self.InsertColumn(2, "Amount")
print("initialized MyListCtrl")
def bindData(self):
data = self.db.retrieveValue(['player', self.name])
count = len(data)
#print(count)
self.itemDataMap = {i: ('slot'+str(i+1), data[str(i)]['item'], data[str(i)]['amount']) for i in range(count)}
self.SetItemCount(count)
def DoCacheItems(self, e):
self.db.updateCache(e.GetCacheFrom(), e.GetCacheTo())
def OnGetItemText(self, row_no, col_no):
data = self.db.retrieveValue(['player', self.name, str(row_no)])
return data[col_no]
def OnGetItemAttr(self, item): return None
def OnGetItemImage(self, item): return -1
def OnBackEndUpdated(self):
self.bindData()
self.RefreshItems(0, self.GetItemCount())
The DBInterface:
class DBInterface(dict):
def __init__(self, path, *args, **kwargs):
super(DBInterface, self).__init__(*args, **kwargs)
self.path = path
def load(self):
with open(self.path, 'r') as f:
try:
self.update(json.loads(f.read()))
except Exception as e:
print(e); print(self.path)
def save(self):
self.path.ensure()
with open(self.path, 'w') as f:
f.write(json.dumps(self))
def retrieveValue(self, path):
a = self
for i in range(len(path)):
a = a[path[i]]
return a
That assert is basically a check to ensure that the operation (setting the count) was successful, by asking the native control how many items it has (which should have been set by the prior API call. It seems like something that really shouldn't be able to fail, although obviously it is. Perhaps something is resetting or changing the native control somehow? Are there any threads involved?
I don't have a solid answer for you, but as advice I would suggest taking the small sample that works and build it up step by step until it matches the window hierarchy and environment and basic features of that part of the full application where it is broken. Eventually it should start failing the same way and then you'll know what changed that triggered it and can look more closely at that.
Well, I bought the book Spring Python 1.1 and I have been facing some problems that I cannot solve. I am going to write the code of each file in order to make sure everything is clear. If some of you know what is the problem, please let me know because I am desperate.
simple_service.py
class Service(object):
def happy_birthday(self, name):
results = []
for i in range(4):
if i <= 2:
results.append("Happy birthday dear %s!" % name)
else:
results.append("Happy birthday to you!")
return results
simple_service_server_ctx.py
from springpython.config import *
from springpython.remoting.pyro import *
from simple_service import *
class HappyBirthdayContext(PythonConfig):
def __init__(self):
PythonConfig.__init__(self)
#Object
def target_service(self):
return Service()
#Object
def service_exporter(self):
exporter = PyroServiceExporter()
exporter.service = self.target_service()
exporter.service_name = "service"
exporter.service_host = "127.0.0.1"
exporter.service_port = "7766"
exporter.after_properties_set()
return exporter
simple_server.py
from springpython.context import *
from simple_service_server_ctx import *
if __name__ == "__main__":
ctx = ApplicationContext(HappyBirthdayContext())
ctx.get_object("service_exporter")
I run on a terminal: python simple_server
and then I got the following error:
(spring)kiko#kiko-laptop:~/examples/spring$ python simple_server.py
Traceback (most recent call last):
File "simple_server.py", line 6, in <module>
ctx = ApplicationContext(HappyBirthdayContext())
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/context/__init__.py", line 45, in __init__
self.get_object(object_def.id, ignore_abstract=True)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/container/__init__.py", line 80, in get_object
comp = self._create_object(object_def)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/container/__init__.py", line 129, in _create_object
self._get_constructors_kw(object_def.named_constr))
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/factory/__init__.py", line 62, in create_object
return self.method()
File "<string>", line 2, in service_exporter
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1370, in object_wrapper
return _object_wrapper(f, theScope, parent, log_func_name, *args, **kwargs)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1350, in _object_wrapper
return _deco(f, scope, parent, log_func_name, *args, **kwargs)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1345, in _deco
results = f(*args, **kwargs)
File "/home/kiko/examples/spring/simple_service_server_ctx.py", line 22, in service_exporter
exporter.after_properties_set()
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/remoting/pyro/__init__.py", line 58, in after_properties_set
pyro_obj = Pyro.core.ObjBase()
AttributeError: 'module' object has no attribute 'ObjBase'
I have added on my own the line (file:simple_service_server_ctx.py):
exporter.after_properties_set()
since I read that it must be declared (line 19, link to source code).
Thanks in advance.
I wonder what your Pyro version is. Here using Pyro 3.9.1-1 from Ubuntu 10.04 I have no problems with running your code. Could it be that you're using Pyro 4.x which if I recall correctly was released after the book had been published?