I have 3 box2d bodies. All of them have user data. Their userData's tags are shown below.
BODY 1: Tag = 1
BODY 2: Tag = 1
BODY 3: Tag = 2
Further in my code, I have implemented contact listener to detect contacts between bodies and I have put condition that Body 3 will be destroyed either collision between BODY1 and BODY3 or BODY2 and BODY3
But when BODY1 and BODY2 collide with BODY3 at the same time, I am getting EXC_BAD_ACCESS. I know why this error appears : it is because there is no body to remove, as it is removed at first contact.
Anyone know how I can solve this error?
You could put a condition to check if your colliding body is == NULL.
If it's not, destroy it. If it is, it's that it has already been destroyed.
EDIT :
To keep your specific tag system, you could pass an NSDictionary as user datas of each of your body :
bodyDef.userData = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:theBodyTag], #"tag",
[NSNumber numberWithInt:theUniqueID], #"ID",
nil];
Then, when colliding you could check the bodies user datas and know if you're in presence of your body 3 or not.
if ([(id)body1->GetUserData() objectForKey:#"ID"] == 3) {
if ([(id)body2->GetUserData() objectForKey:#"ID"] == 1 ||
[(id)body2->GetUserData() objectForKey:#"ID"] == 2) {
Feed an array with the body to destroy and destroy it after your collision checks !
[myQueue addObject:[(id)body2->GetUserData() objectForKey:#"ID"]];
}
}
After the collision routine, iterate over all your bodies and destroy the ones that have your queue objects as unique ID.
Please note that I didn't check of this code works actually, but this is the idea.
Related
EDIT/TL;DR: It looks like there is a matplotlib.backends.backend_qt4.TimerQT object that hold a reference to my FuncAnimation object. How can I remove it to free the FuncAnimation object?
1 - A little context
I'm trying to animate a plot generated with matplotlib. I use matplotlib.animation.FuncAnimation.
This animated plot is contained in a FigureCanvasQTAgg (matplotlib.backends.backend_qt4agg), ie. a PyQt4 widget.
class ViewerWidget(FigureCanvasQTAgg):
def __init__(self, viewer, parent):
# viewer is my FuncAnimation, encapsulated in a class
self._viewer = viewer
FigureCanvasQTAgg.__init__(self, viewer.figure)
When a change of configuration occure in the GUI, the Figure is cleared (figure.clf()) and its subplots (axes and lines) replaced by new ones.
2 - Source code from Class Viewer (encapsulating FuncAnimation)
This is the most relevant part of my method Viewer.show(...), that instanciate the FuncAnimation
2.a - First, I tried:
animation.FuncAnimation(..., blit=True)
Of course, the instance was garbage collected immediatly
2.b - Then, I stored it in a class variable:
self._anim = animation.FuncAnimation(..., blit=True)
It worked for the first animation, but as soon as the configuration changed, I had artifacts from previous animations all over the new ones
2.c - So I manually added a del:
# Delete previous FuncAnimation if any
if self._anim:
del self._anim
self._anim = animation.FuncAnimation(..., blit=True)
Nothing changed
2.d - After some debugging, I checked the garbage collector:
# DEBUG: check garbage collector
def objects_by_id(id_):
for obj in gc.get_objects():
if id(obj) == id_:
return obj
self._id.remove(id_)
return "garbage collected"
# Delete previous FuncAnimation if any
if self._anim:
del self._anim
# DEBUG
print "-"*10
for i in self._id.copy():
print i, objects_by_id(i)
print "-"*10
self._anim = animation.FuncAnimation(self._figure_handler.figure,
update,
init_func=init,
interval=self._update_anim,
blit=True)
# DEBUG: store ids only, to enable object being garbage collected
self._anim_id.add(id(anim))
After 3 configuration changes, it showed:
----------
140488264081616 <matplotlib.animation.FuncAnimation object at 0x7fc5f91360d0>
140488264169104 <matplotlib.animation.FuncAnimation object at 0x7fc5f914b690>
140488145151824 <matplotlib.animation.FuncAnimation object at 0x7fc5f1fca750>
140488262315984 <matplotlib.animation.FuncAnimation object at 0x7fc5f8f86fd0>
----------
So, it confirmed that none of the FuncAnimation were garbage collected
2.e - Last try, with weakref:
# DEBUG: check garbage collector
def objects_by_id(id_):
for obj in gc.get_objects():
if id(obj) == id_:
return obj
self._id.remove(id_)
return "garbage collected"
# Delete previous FuncAnimation if any
if self._anim_ref:
anim = self._anim_ref()
del anim
# DEBUG
print "-"*10
for i in self._id.copy():
print i, objects_by_id(i)
print "-"*10
anim = animation.FuncAnimation(self._figure_handler.figure,
update,
init_func=init,
interval=self._update_anim,
blit=True)
self._anim_ref = weakref.ref(anim)
# DEBUG: store ids only, to enable object being garbage collected
self._id.add(id(anim))
This time, logs where confusing, I'm not sure what's going on.
----------
140141921353872 <built-in method alignment>
----------
----------
140141921353872 <built-in method alignment>
140141920643152 Bbox('array([[ 0., 0.],\n [ 1., 1.]])')
----------
----------
140141921353872 <built-in method alignment>
140141920643152 <viewer.FftPlot object at 0x7f755565e850>
140141903645328 Bbox('array([[ 0., 0.],\n [ 1., 1.]])')
----------
(...)
Where are my <matplotlib.animation.FuncAnimation object at 0x...>?
There were no more previous animation artifacts, so far so good, but... FuncAnimation is no longer able to execute the "update". Only the "init" part. My guess is the FuncAnimation is garbage collected as soon as the method Viewer.show(...) returns, sinces anim ids are already recycled.
3 - Help
I don't know where to look from here. Any suggestion?
EDIT:
I installed objgraph to visualize all back references to FuncAnimation, I got this:
import objgraph, time
objgraph.show_backrefs([self._anim],
max_depth=5,
filename="/tmp/debug/func_graph_%d.png"
% int(time.time()))
So, there is a matplotlib.backends.backend_qt4.TimerQT that still hold a reference. Any way to remove it?
To sort out what is going on here involves going down into the guts of how the animation module and two callback registries work.
When you create the Animation object it registers a callback into the mpl callback registry on the draw_event so that after the first time that the canvas is drawn after the Animation object is created the timed animation sets it self up (by registering a callback into a timer object) and a callback into the mpl callback registry on the close_event to tear the timer down.
The mpl callback registry does a bunch of introspection of the callables that come in and reconstructs bound methods into a weakref to the object an the relevant function. Thus, if you you create an animation object but don't keep a ref to it, it's refcount will go to zero, the weakref to it in the mpl callback registry will fail, and the animation will never start.
The way that the timer works it Qt is that you register a callable which is added to a list (I am getting this from your diagram at the bottom) so it is holding a hard reference to the Animation object, thus removing the ref you hold in your object is not enough to drive the ref count to zero. In the case of timers callbacks this is probably a feature, not a bug.
By artifacts, I now understand to mean you are creating a second Animation object and what you get is both of them running in parallel (which I am not sure what I expect to happen there).
To stop a running Animation and remove it from the timer's callback list use the private method (which should be public) _stop which is what responsible for the tear down (and is the method registered on close_event).
When you try to close Swing application and you change same value in field, application ask you if you want to save changes.
My first question is why RAP application doesn't ask same question ?
Second and more important question is how to force validation of fields change and how to manipulate this.
for example :
I have table with rows and some fields below table. If I click on row some value is entered in fields. I can change this value and click button save.
I would like to force change validation on row click. So if changes ware applied and if I click on row, application should warn me that some changes are not saved.
But I should be able to manipulate what is change and what is not. For example if table on row click fill some data if fields this is not change, but if I entered value is same fields this is change.
I discovered method
checkSaveNeeded();
But it does nothing. (if I change values or not)
I see that every field has mathod
#Override
public final void checkSaveNeeded() {
if (isInitialized()) {
try {
propertySupport.setPropertyBool(PROP_SAVE_NEEDED, m_touched || execIsSaveNeeded());
}
catch (ProcessingException e) {
SERVICES.getService(IExceptionHandlerService.class).handleException(e);
}
}
}
so I should manipulate changes throw m_touched ?
How is this handled in Scout ?
ADD
I am looking for function that check for dirty fields and pops up message dialog, same as when closing form, and way to set fields dirty or not.
I look here and here, but all it describes is how values is stored for popup messages and dot how to fire this messages (validation).
My first question is why RAP application doesn't ask same question ?
I am not sure to know which message box you mean but it should be the case.
There are several questions about unsaved changes and form lifecycle in the Eclipse Scout Forum. I think you can find them with Google.
I have also taken the time to start to document it in the Eclipse Wiki:
Scout Field > Contribution to unsaved changes
Form lifecycle
I think you should implement execIsSaveNeeded() in the corresponding field. The default implementation in AbstractTableField uses the state of the rows, but you can imagine the logic you want.
#Order(10.0)
public class MyTableField extends AbstractTableField<MyTableField.Table> {
#Override
protected boolean execIsSaveNeeded() throws ProcessingException {
boolean result;
//some logic that computes if the table field contains modification (result = true) or not (result = false)
return result;
}
//...
I hope this helps.
I am looking for function that check for dirty fields and pops up message dialog, same as when closing form.
Are you speaking from this message box that appears when the user clicks on Cancel in the form?
There is no specific function that you can call for that. But you can check the beginning of the AbstractForm.doCancel() function. It is exactly what you are looking for.
I have rewritten it like this:
// ensure all fields have the right save-needed-state
checkSaveNeeded();
// find any fields that needs save
AbstractCollectingFieldVisitor<IFormField> collector = new AbstractCollectingFieldVisitor<IFormField>() {
#Override
public boolean visitField(IFormField field, int level, int fieldIndex) {
if (field instanceof IValueField && field.isSaveNeeded()) {
collect(field);
}
return true;
}
};
SomeTestForm.this.visitFields(collector);
MessageBox.showOkMessage("DEBUG", "You have " + collector.getCollectionCount() + " fields containing a change in your form", null);
I have changed the Visitor to collect all value fields with unchanged changes. But you can stick to the original visitField(..) implementation. You cannot use P_AbstractCollectingFieldVisitor because it is private, but you can have a similar field visitor somewhere else.
I am looking for a way to set fields dirty or not.
As I told you: execIsSaveNeeded() in each field for some custom logic. You can also call touch() / markSaved() on a field to indicate that it contains modifications or not. But unless you cannot do otherwise, I do not think that this is the correct approach for you.
What's CCCallBlockN alternative for Cocos2d 3.0 ?
Here is my Cocos2d 2.0 Code:
id calBlock = [CCCallBlockN actionWithBlock:^(CCNode *node){
node.position = orign;
}];
The CCCallBlockN and CCCallBlockND variants have always been superfluous since blocks can reference objects in the local scope:
id someData = (some data however created or obtained);
CCNode* someNode = (some node however created or obtained);
id callBlock = [CCActionCallBlock actionWithBlock:^{
someNode.position = origin;
[someData quickDoSomething];
}];
[someNode runAction:callBlock];
You just need to have a reference like someNode in the outer scope of the block in order to use it inside the block.
You will usually have the desired node reference because after all you're going to run the action on the desired node after creating the action. Only in cases where you create the actions first and run them later would the passed-in node be useful, but I guess that's a rare situation and probably not good style anyway.
I have a Schedulable class which will get called once per night. I have run the code anonymously and everything works as it should. The problem I am having is that I cannot get proper test coverage on it! I have written a test class that I believe should work, but for some reason any lines within my for-loops are not being covered.
I assume that it is because no data is being returned from these queries, however there are thousands of records that should be returned. I have run the queries on the production environment without any issues.
Is there a separate process for running queries in a schedulable class?
Here's part of my class:
global class UpdateUnitPrice implements Schedulable{
global void execute(SchedulableContext sc){
// OwnerId -> List of Strings with Row Contents
Map<Id,Map<Id,Map<String,String>>> updateContainer = new Map<Id,Map<Id,Map<String,String>>>{}; // Covered
List<Id> ownerContainer = new List<Id>{}; // Covered
String EmailMessage; // Covered
String EmailLine; // Covered
String EmailAddedLines; // Covered
String CurrentEmailLine; // Covered
String NewEmailLine; // Covered
List<Id> opportunityList = new List<Id>{}; // Covered
for(Opportunity thisOpp :[SELECT Id,Name FROM Opportunity WHERE Order_Proposed__c = null])
{
// Thousands of records should be returned
opportunityList.add(thisOpp.Id); // NOT COVERED!!
}
List<OpportunityLineItem> OppLineItemList = new List<OpportunityLineItem>{}; // Covered
for(OpportunityLineItem thisOppProd : [SELECT Id,OpportunityId,Opportunity.OwnerId,Opportunity.Name,Product_Name__c,UnitPrice,ListPrice
FROM OpportunityLineItem
WHERE OpportunityId IN :opportunityList
AND UnitPrice_lt_ListPrice__c = 'True'
ORDER BY OpportunityId ASC])
{
. . . // NO LINES COVERED WITHIN THIS LOOP
}
. . .
}
}
Here's my test class:
#isTest
private class UpdateUnitPriceTest {
static testMethod void myUnitTest() {
Test.startTest();
// Schedule the test job
String jobId = System.schedule('UpdateUnitPrice','0 0 0 3 9 ? 2022',new UpdateUnitPrice());
// Get the information from the CronTrigger API object
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
// Verify the expressions are the same
System.assertEquals(ct.CronExpression,'0 0 0 3 9 ? 2022');
// Verify the job has not run
System.assertEquals(0, ct.TimesTriggered);
// Verify the next time the job will run
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
Test.stopTest();
}
}
Am I supposed to specifically reference something within these for-loops for them to fire? This Class should be able to just run everything on it's own without inserting records for testing. What am I missing?
Thanks in advance for any help given!
There was a lovely feature added to API 24.0 which requires test classes to include a small (new) line of code in order to view queried data. I have no idea why this was implemented, but it sure did trip me up.
For our test classes to run properly, they now must have the following at the top:
#isTest (SeeAllData = true)
Previously, all that was needed was:
#isTest
You can read more on test classes and this new "feature" here: Apex Test Class Annotations
I'm having a problem with my picker in one of my apps. I have an NSDictionary obtained from a property list that contains a bunch of keys, which in turn contain a bunch of strings. I have two components, each one should have the same list of strings within. I also have a slider that I want to use to allow the user to change keys. So when the slider's value goes from 0 to 1 the key at index 1 in the dictionary should load its contents into the pickerview's components.
It's working as far as loading the new contents into the picker based on the slider. I've been using the slider's tag as the variable to dictate which contents get loaded. The problem is that after loading a new list of items the program crashes, I'm thinking that the number of rows needed isn't getting update or something but I'm just not experienced enough with UIPickerView to isolate the problem myself without spending more hours than I've already used trying to figure this out myself.
Here are my delegate/data methods for the picker:
#pragma mark -
#pragma mark Picker Delegate/Data Methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
//aryNames is an NSArray instance variable that contains the values for the components of the picker
if (component == 0)
return [self.aryNames count];
return [self.aryNames count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
//I think this is where my problem is
//I'm using a string to select the object
// at the index of the slider's location to
// fill up the instance variable with new data.
//Anyway, it works fine if I have two different arrays hardcoded
//but I'd really like to have this load dynamically because
//there are a lot of keys and this way I could add and remove keys without
//worrying about changing code
NSString *selectedType = [self.aryKeys objectAtIndex:slideUnitTypes.tag];
NSArray *newNames = [dictAllNames objectForKey:selectedType];
self.aryNames = newNames;
return [aryNames objectAtIndex:row];
}
//I'm pretty sure that the method below is not the problem
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:
(NSInteger)component
{
if (component == 0)
{
[firstValueHeading setText:[aryNames objectAtIndex:row]];
}
else
{
[secondValueHeading setText:[aryNames objectAtIndex:row]];
}
}
If it wasn't descriptive enough or you need to see more of my code please tell me. This problem has been a real bugger in an otherwise smooth project. Thanks.
I am still fairly new to this myself, but in Troy Brant's book (chapter 9) he does this. You should grab the book from the library/bookstore and review the source code at http://troybrant.net/iphonebook/chapter9/Ruralfork-done.zip
It should help.
i've actually solved this long since. here is the code for that delegate if it helps:
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSUInteger index = slideUnitTypes.value;
NSString *placeString = [self.aryKeys objectAtIndex:index];
NSArray *returnThisArray = [dictAllNames objectForKey:placeString];
return [returnThisArray objectAtIndex:row];
}
if anyone out there needs to see any of my other delegates just comment on this answer and hopefully SO should send me an email.