Error setting attribute of an sdl2 Entity - python

I am using the pysdl2 library. self.velocity will print, but self.forward_tick with throw a key error.
What is causing only part of the self attributes from being assigned. I am thinking it has something to do with the inheritance.
class Robot(sdl2.ext.Entity):
def __init__(self, world, sprite, posx=0, posy=0):
self.sprite = sprite
self.sprite.position = posx, posy
self.velocity = Velocity()
self.forward_tick = 0
self.go_forward = 0
self.unit_forward = (1,0)
print(self.velocity)
print(self.forward_tick)
Here is the output:
Collins-MacBook-Air:soccer_bots collinbell$ python test_simulation_world.py
<simulation_world.Velocity object at 0x108ecb5c0>
Traceback (most recent call last):
File "/Users/collinbell/.pyenv/versions/3.4.3/lib/python3.4/site-packages/sdl2/ext/ebs.py", line 53, in __getattr__
ctype = self._world._componenttypes[name]
KeyError: 'forward_tick'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test_simulation_world.py", line 3, in <module>
world = Simulation_World("Test Simulation", 1080, 720)
File "/Users/collinbell/Programs/soccer_bots/simulation_world.py", line 100, in __init__
self.player1 = Robot(self.world, sp_paddle1, 0, 250)
File "/Users/collinbell/Programs/soccer_bots/simulation_world.py", line 22, in __init__
print(self.forward_tick)
File "/Users/collinbell/.pyenv/versions/3.4.3/lib/python3.4/site-packages/sdl2/ext/ebs.py", line 56, in __getattr__
(self.__class__.__name__, name))
AttributeError: object ''Robot'' has no attribute ''forward_tick''

From the docs on component-based design with sdl2.ext, the Entity type is special, and doesn't follow normal Python idioms. In particular, you can't just create arbitrary attributes; you can only create attributes whose value is a component type, and whose name is a lowercased version of that type:
Entity objects define the in-application objects and only consist of component-based attributes.
…
The Entity also requries its attributes to be named exactly as their component class name, but in lowercase letters.
So, when you try to add an attribute named forward_tick, that causes Entity.__setattr__ to go looking for a class named Forward_Tick in the world's component types. Which it apparently does by looking up self._world._componentypes[name], which is the line that's actually raising the exception, as you can see in the tracebacks.
Without knowing anything more about your code and your design than the tiny fragment you showed us, I can't tell you how to fix this. But most likely, it's one of the following:
You actually wanted to create a Component, not an Entity,
You wanted to wrap up forward_tick in a Component type that this Entity can contain, or
You didn't want a Component-oriented design in the first place.
At any rate, as the docs say:
If you are just starting with such a [component-oriented] design, it is recommended to read through the The Pong Game tutorial.

Related

python-pcl Segmentation_PointXYZI' object has no attribute 'set_MaxIterations'

I'm new in C++. So, I'm trying to use python-pcl, but I got an error:
AttributeError: 'pcl._pcl.Segmentation_PointXYZI' object has no attribute 'set_MaxIterations'
I'm trying to create the segmentation object for the planar model and set the parameters with the PointXYZI type. I have to use PointXYZI. How can I solve this problem?
My code:
def cluster_extraction(self,data):
print("Type1: ", type(data))
cloud_filtered = self.downsampling(data,0.3)
print("Type2: ", type(cloud_filtered))
seg = cloud_filtered.make_segmenter()
seg.set_optimize_coefficients (True)
seg.set_model_type (pcl.SACMODEL_PLANE)
seg.set_method_type (pcl.SAC_RANSAC)
seg.set_MaxIterations (100)
seg.set_distance_threshold (0.02)
Output:
('Type1: ', <type 'pcl._pcl.PointCloud_PointXYZI'>)
('Type2: ', <type 'pcl._pcl.PointCloud_PointXYZI'>)
[ERROR] [1596926303.890116]: bad callback: <bound method sub_pub_node.callback of <__main__.sub_pub_node object at 0x7f154be44ad0>>
Traceback (most recent call last):
File "/opt/ros/melodic/lib/python2.7/dist-packages/rospy/topics.py", line 750, in _invoke_callback
cb(msg)
File "node.py", line 154, in callback
downsampled_data = self.processing(pcl2_data)
File "node.py", line 103, in processing
processing.cluster_extraction(pcl2_data)
File "node.py", line 43, in cluster_extraction
seg.set_MaxIterations (100)
AttributeError: 'pcl._pcl.Segmentation_PointXYZI' object has no attribute 'set_MaxIterations'
I am not sure from where you got your python-pcl package, but I will assume that you used this one, therefore, and because there is no method called set_MaxIterations(int ) in the Segmentation_PointXYZI class (Sample Consensus), you can try to replace it with setMaxIterations(int ).
Inside the definition of the PointCloud_PointXYZI class, you can find that the Segmentation method used for this type of point clouds is an instance from pcl_seg.SACSegmentation_PointXYZI_t which defines the method for setting the max number of iterations as setMaxIterations(int ).
Please check the documentation provided here and check the functions that you are using and how are they defined. (I know that can be tedious but it is necessary).
I hope this helped in solving the issue.
According to strawlab's official example the correct call is:
seg.set_max_iterations(100)

Python jsonpickle error: 'OrderedDict' object has no attribute '_OrderedDict__root'

I'm hitting this exception with jsonpickle, when trying to pickle a rather complex object that unfortunately I'm not sure how to describe here. I know that makes it tough to say much, but for what it's worth:
>>> frozen = jsonpickle.encode(my_complex_object_instance)
>>> thawed = jsonpickle.decode(frozen)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/jsonpickle/__init__.py",
line 152, in decode
return unpickler.decode(string, backend=backend, keys=keys)
:
:
File "/Library/Python/2.7/site-packages/jsonpickle/unpickler.py",
line 336, in _restore_from_dict
instance[k] = value
File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/packages/ordered_dict.py",
line 49, in __setitem__
root = self.__root
AttributeError: 'OrderedDict' object has no attribute '_OrderedDict__root'
I don't find much of assistance when googling the error. I do see what looks like the same issue was resolved at some time past for simpler objects:
https://github.com/jsonpickle/jsonpickle/issues/33
The cited example in that report works for me:
>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict()))
OrderedDict()
>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict(a=1)))
OrderedDict([(u'a', 1)])
Has anyone ever run into this themselves and found a solution? I ask with the understanding that my case may be "differently idiosynchratic" than another known example.
The requests module for me seems to be running into problems when I .decode(). After looking at the jsonpickle code a bit, I decided to fork it and change the following lines to see what was going on (and I ended up keeping a private copy of jsonpickle with the changes so I can move forward).
In jsonpickle/unpickler.py (in my version it's line 368), search for the if statement section in the method _restore_from_dict():
if (util.is_noncomplex(instance) or
util.is_dictionary_subclass(instance)):
instance[k] = value
else:
setattr(instance, k, value)
and change it to this (it will logERROR the ones that are failing and then you can either keep the code in place or change your OrderedDict's version that have __root)
if (util.is_noncomplex(instance) or
util.is_dictionary_subclass(instance)):
# Currently requests.adapters.HTTPAdapter is using a non-standard
# version of OrderedDict which doesn't have a _OrderedDict__root
# attribute
try:
instance[k] = value
except AttributeError as e:
import logging
import pprint
warnmsg = 'Unable to unpickle {}[{}]={}'.format(pprint.pformat(instance), pprint.pformat(k), pprint.pformat(value))
logging.error(warnmsg)
else:
setattr(instance, k, value)

Django queryset.first bug? May involve django-polymorphic and mixins

I have a model, and I have instantiated several instances and persisted them to the database. Through the python shell I can confirm that the objects exist, but I run into trouble as soon as I try to work with the queryset via the queryset.first() call, as well as indexing into the queryset.all() result. I'm using the django-polymorphic plugin.
>>> Thing.objects.all()
[<Thing: thing1>, <Thing: thing2>, <Thing: thing3>]
>>> Thing.objects.first()
>>> str(Thing.objects.first())
'None'
>>> Thing.objects.all()[0]
Traceback (most recent call last):
File "<console>", line 1, in <module>
File ".../python3.4/site-packages/django/db/models/query.py", line 201, in __getitem__
return list(qs)[0]
IndexError: list index out of range
>>> Thing.objects.all().__class__
<class 'polymorphic.query.PolymorphicQuerySet'>
>>>
I strongly suspect this involves the fact that I'm using a mixin for Thing on top of the polymorphic base class. Here's what my hierarchy looks like (boiled down to make it easier for y'all):
from django.db import models
from polymorphic.polymorphic_model import PolymorphicModel
class AwesomeMixin(object):
def reallyUsefulMethod(self):
print('show me your MOVES')
class BaseThing(PolymorphicModel, AwesomeMixin):
pass
class Thing(BaseThing):
pass
class Doohickey(BaseThing):
pass
class SomethingElse(models.Model, AwesomeMixin):
pass
Anyone know what's going on here? Am I using mixins correctly? Is the issue related to django-polymorphic? Thanks!

AssertRaises fails even though exception is raised

I am running into the following rather strange problem:
I am developing a django app and in my models class I am defining an exception that should be raised when a validation fails:
class MissingValueException(Exception):
"""Raise when a required attribute is missing."""
def __init__(self, message):
super(MissingValueException, self).__init__()
self.message = message
def __str__(self):
return repr(self.message)
This code is called from a publication class in a validation method:
def validate_required_fields(self):
# Here is the validation code.
if all_fields_present:
return True
else:
raise MissingValueException(errors)
In my unit test I create a case where the exception should be raised:
def test_raise_exception_incomplete_publication(self):
publication = Publication(publication_type="book")
self.assertRaises(MissingValueException, publication.validate_required_fields)
This produces the following output:
======================================================================
ERROR: test_raise_exception_incomplete_publication (core_knowledge_platform.core_web_service.tests.logic_tests.BusinessLogicTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/tests/logic_tests.py", line 45, in test_raise_exception_incomplete_publication
self.assertRaises(MissingValueException, method, )
File "/usr/lib/python2.7/unittest/case.py", line 465, in assertRaises
callableObj(*args, **kwargs)
File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/models.py", line 150, in validate_required_fields
raise MissingValueException(errors)
MissingValueException: 'Publication of type book is missing field publisherPublication of type book is missing field titlePublication of type book is missing field year'
So it looks like the exception is raised (which is the case - I even checked it in an interactive IPython session), but it seems that assertRaises is not catching it.
Anyone has any idea why this might happen?
Thanks
This could happen if your tests and your product code are importing your exception class through two different paths, so asserRaises doesn't realize that the exception you got was the one you were looking for.
Look at your imports, make sure that they are the same in both places. Having the same directories available in two different ways in your PYTHONPATH can make this happen. Symbolic links in those entries can also confuse things.

AppEngine -> "AttributeError: 'unicode' object has no attribute 'has_key'" when using blobstore

There have been a number of other questions on AttributeErrors here, but I've read through them and am still not sure what's causing the type mismatch in my specific case.
Thanks in advance for any thoughts on this.
My model:
class Object(db.Model):
notes = db.StringProperty(multiline=False)
other_item = db.ReferenceProperty(Other)
time = db.DateTimeProperty(auto_now_add=True)
new_files = blobstore.BlobReferenceProperty(required=True)
email = db.EmailProperty()
is_purple = db.BooleanProperty()
My BlobstoreUploadHandler:
class FormUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
try:
note = self.request.get('notes')
email_addr = self.request.get('email')
o = self.request.get('other')
upload_file = self.get_uploads()[0]
# Save the object record
new_object = Object(notes=note,
other=o,
email=email_addr,
is_purple=False,
new_files=upload_file.key())
db.put(new_object)
# Redirect to let user know everything's peachy.
self.redirect('/upload_success.html')
except:
self.redirect('/upload_failure.html')
And every time I submit the form that uploads the file, it throws the following exception:
ERROR 2010-10-30 21:31:01,045 __init__.py:391] 'unicode' object has no attribute 'has_key'
Traceback (most recent call last):
File "/home/user/Public/dir/google_appengine/google/appengine/ext/webapp/__init__.py", line 513, in __call__
handler.post(*groups)
File "/home/user/Public/dir/myapp/myapp.py", line 187, in post
new_files=upload_file.key())
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 813, in __init__
prop.__set__(self, value)
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 3216, in __set__
value = self.validate(value)
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 3246, in validate
if value is not None and not value.has_key():
AttributeError: 'unicode' object has no attribute 'has_key'
What perplexes me most is that this code is nearly straight out of the documentation, and jives with other examples of blob upload handler's I've found online in tutorials as well.
I've run --clear-datastore to ensure that any changes I've made to the DB schema aren't causing problems, and have tried casting upload_file as all sorts of things to see if it would appease Python - any ideas on what I've screwed up?
Edit: I've found a workaround, but it's suboptimal.
Altering the UploadHandler to this instead resolves the issue:
...
# Save the object record
new_object = Object()
new_object.notes = note
new_object.other = o
new_object.email = email.addr
new_object.is_purple = False
new_object.new_files = upload_file.key()
db.put(new_object)
...
I made this switch after noticing that commenting out the files line threw the same issues for the other line, and so on. This isn't an optimal solution, though, as I can't enforce validation this way (in the model, if I set anything as required, I can't declare an empty entity like above without throwing an exception).
Any thoughts on why I can't declare the entity and populate it at the same time?
You're passing in o as the value of other_item (in your sample code, you call it other, but I presume that's a typo). o is a string fetched from the request, though, and the model definition specifies that it's a ReferenceProperty, so it should either be an instance of the Other class, or a db.Key object.
If o is supposed to be a stringified key, pass in db.Key(o) instead, to deserialize it.
Object is a really terrible name for a datastore class (or any class, really), by the way - the Python base object is called object, and that's only one capitalized letter away - very easy to mistake.
has_key error is due to the ReferenceProperty other_items. You are most likely passing in '' for other_items when appengine's api expects a dict. In order to get around this, you need to convert other_items to hash.
[caveat lector: I know zilch about "google_app_engine"]
The message indicates that it is expecting a dict (the only known object that has a has_key attribute) or a work-alike object, not the unicode object that you supplied. Perhaps you should be passing upload_file, not upload_file.key() ...

Categories