swift (spritekit) - how to get callback after block / closure enumeration? - objective-c

I'm trying to do a check inside of an enumeration. if my conditional statement is triggered, then i want to exit the parent function. the problem is that i think this is happening asynchronously, so once in a while it will exit the function while the loop is still executing and cause a memory error.
self.gameScene!.physicsWorld.enumerateBodiesAlongRayStart(self.position, end: randomPt, usingBlock: {
body, point, normal, stop in
if let node = body.node {
// we're intersecting with the enemy. lets try again
if node.name != nil && node.name == "shieldBox" {
abort = true
stop.memory = true
}
}
})
// this sometimes causes an error. the closure above is still executing!
if abort {
self.checkWayPoint()
return
}
i need to make sure enumerateBodiesAlongRayStart is finished before moving along. is there any way to do this? A regular loop alternative would be great too.. but cant find anything like that.

Related

Understanding cancelParent function in coroutines

I was reading some source code on coroutines and run into this function;
private fun cancelParent(cause: Throwable): Boolean {
// CancellationException is considered "normal" and parent is not cancelled when child produces it.
// This allow parent to cancel its children (normally) without being cancelled itself, unless
// child crashes and produce some other exception during its completion.
if (cause is CancellationException) return true
if (!cancelsParent) return false
return parentHandle?.childCancelled(cause) == true
}
The point that I don't quite get is the very first line of code. It feels like it contradicts with what's stated in the comment. If the exception is CancellationException then it's a "normal" cancellation and the parent should not be cancelled, right? However, the function returns true which is read like - "Ok, I'm gonna cancel the parent".
By the way, the rest of the lines/checks in the function make sense to me when I look into what, for example supervisorScope or launch, returns.
Can someone please explain?
That's one of the cases where naming return values would be valuable.
If you look at the usage of this code, you'll see the following:
// Now handle the final exception
if (finalException != null) {
val handled = cancelParent(finalException) || handleJobException(finalException)
if (handled) (finalState as CompletedExceptionally).makeHandled()
}
So, true means not shouldParentBeCancelled?, as one may assume, but wasCancellationAlreadyHandledOrShouldBeHandledByParent?

Binary Search Tree Inorder Traversal

I am confused by this code:
void in_order_traversal_iterative(BinaryTree *root) {
stack<BinaryTree*> s;
BinaryTree *current = root;
while (!s.empty() || current) {
if (current) {
s.push(current);
current = current->left;
} else {
current = s.top();
s.pop();
cout << current->data << " ";
current = current->right;
}
}
}
We set a pointer to point to root. Then if it exists, then push the current (which is root currently) into the stack. I do not see why we push the whole tree into the stack initially, instead of just the value of the data the node holds. Am I missing something completely or not understanding why it would work this way? I cannot comprehend why we push the whole tree in, rather than a single node...
You're missing the fact that after a node is popped, its right child must still be traversed:
current = s.top();
s.pop();
cout << current->data << " ";
current = current->right;
If you had only the data on the stack, this would be impossible. The loop invariant is that the stack holds exactly those nodes with un-traversed right children.
Another way to see what's going on is to transform the recursive traversal to the iterative by algebra:
traverse(node) {
if (node) {
traverse(node->left);
visit(node);
traverse(node->right);
}
}
First convert the tail call to iteration. We do this by updating the argument and replacing the recursive call with a goto the start of the function:
traverse(node) {
start:
if (node) {
traverse(node->left);
visit(node);
node = node->right;
goto start;
}
}
The goto and if are the same as a while, so we have so far
traverse(node) {
while (node) {
traverse(node->left);
visit(node);
node = node->right;
}
}
Replacing the other recursive call requires us to simulate the call stack of the compiler's runtime environment. We do that with an explicit stack.
traverse(node) {
start:
while (node) {
stack.push(node); // save the value of the argument.
node = node->left; // redefine it the same way the recursive call would have
goto start; // simulate the recursive call
// recursive call was here; it's gone now!
recursive_return: // branch here to simulate return from recursive call
visit(node);
node = node->right;
}
// simulate the recursive return: if stack has args, restore and go to return site
if (!stack.empty()) {
node = stack.pop(); // restore the saved parameter value
goto recursive_return;
}
}
Though it's ugly, this is a way that always works to implement iterative versions of recursive code. (It's more complicated if there are multiple non-tail recursive calls, but not much.) And I'm sure you can see the similarity to your code.
We can even get rid of the ugliness with more algebra. First, it's not hard to see this code:
start:
while (node) {
stack.push(node); // save the value of the argument.
node = node->left; // redefine it the same way the recursive call would have
goto start; // simulate the recursive call
when executed beginning with start is equivalent to
while (node) {
stack.push(node); // save the value of the argument.
node = node->left; // redefine it the same way the recursive call would have
}
We can also replace
if (!stack.empty()) {
node = stack.pop(); // restore the saved parameter value
goto recursive_return;
}
with the following
if (!stack.empty()) {
node = stack.pop(); // restore the saved parameter value
visit(node);
node = node->right;
goto start;
}
We have merely copied the three instructions after recursive_return: into the if body.
With this, there is no way left to arrive at the recursive_return label, so we can delete it along with the two following statements:
// Dead code! Delete me!
recursive_return:
visit(node);
node = node->right;
We now have:
traverse(node) {
start:
while (node) {
stack.push(node); // save the value of the argument.
node = node->left; // redefine it the same way the recursive call would have
}
if (!stack.empty()) {
node = stack.pop(); // restore the saved parameter value
visit(node);
node = node->right;
goto start;
}
}
We can get rid of the last goto start by replacing it with an endless loop:
traverse(node) {
loop {
while (node) {
stack.push(node); // save the value of the argument
node = node->left; // redefine it the same way the recursive call would have
}
if (stack.empty()) break; // original code returns, so does this!
node = stack.pop(); // restore the saved parameter value
visit(node);
node = node->right;
}
}
Note we are returning under the same conditions as the previous code: the stack is empty!
I will let you prove to yourself that this code does the same as what you presented, only it's a bit more efficient because it avoids some comparisons! We never had to reason at all about pointers and stack elements. It "just happened."
It's not pushing the whole tree into the stack, it pushes the left-most part of the tree. Then it begin to pop the elements and push their right-most counterparts, in ascending order.

While statement causing freeze/crash in LibGDX?

I have the following code in the update method of a base level class:
while(entities.iterator().hasNext()){
if(entities.iterator().next() != null){
entities.iterator().next().update();
Gdx.app.log(Game.LOG, "Updated Entity "+entities.iterator().next().getName()+".");
}
else{
Gdx.app.log(Game.LOG, "Could not update Entity.");
}
}
However, this statement will freeze the program when it is run, and will have to be force closed without providing any crash information. I can stop the freezing by using an if statement instead of a while, however, it will only update the first entity in the array.
What could be causing the freeze, and how can the iterator be looped without causing it?
Don't call the iterator() and next() methods more than required. The iterator() method will reset the iterator on every call. The next() method will fetch the next item on every call. Instead use something like this:
Iterator<T> iterator = entities.iterator();
while(iterator.hasNext()) {
T entity = iterator.next();
entity.update();
}
Where T should be replaced by the class of your entity.
Edit, easier would be using the syntactic sugar:
for (T entity : entities) {
entity.update();
}

Writing Custom Rule for Android-Lint

Q (tldr;): How do I use the JavaScanner in android-lint to check if a particular function call with a specific string as a parameter has been surrounded by a try/catch block.
Details: I have completed the android-lint tutorials on the official site and have gone through the source of the existing lint-checks. However, I can't seem to grasp the workflow for this AST-based parsing of JavaScanner. What I'm trying to achieve is to catch a function that sets a specific property and surround it with a try/catch block. For example:
MyPropertySettings.set("SOME_PROPERTY", "SOME_VAL");
should not trigger the lint rule but:
MyPropertySettings.set("SOME_SENSITIVE_PROPERTY", "SOME_VAL");
should because it's not surrounded by a try/catch block with SetPropertyException. I don't want to introduce the try/catch to the function itself because it only throws the exception in extremely rare cases (and the internals of the function are based on some reflection mojo).
For this question, even a workflow/hint would be fine. If I can get the first few steps, I might be able to grasp it better.
Update:
After some more study, I have found that I need to set the set function above in getApplicableMethodNames() and then, somehow read the property of that function to decide if the check applies. That part should be easy.
Surrounding try/catch would be more difficult and I gather I would need to do some "flow analysis". How is the question now.
Well, along with the getApplicableMethodNames() method, you need to override the visitMethod() function. You will get the MethodInvocationNode. Just fetch the arguments passed in the invocation using the node.astArguments() function. This returns a list of arguments that you can iterate through using a StrictListAccessor. Check the arguments passed and if it matches your criterion, run a loop and keep calculating the parent node of the invocation node till a try node is found. If it is a try node, then you can get a list of catches using node.astCatches(). Scan the list and find the appropriate exception. If not found, then report.
You can code like this:
check if it is surrounded by try/catch:
#Override
public void visitMethod(JavaContext context, AstVisitor visitor, MethodInvocation node) {
// check the specified class that invoke the method
JavaParser.ResolvedMethod method = (JavaParser.ResolvedMethod) context.resolve(node);
JavaParser.ResolvedClass clzz = method.getContainingClass();
boolean isSubClass = false;
// sSupportSuperType = {"class name"};
for (int i = 0; i < sSupportSuperType.length; i++) {
if (clzz.isSubclassOf(sSupportSuperType[i], false)) {
isSubClass = true;
break;
}
}
if (!isSubClass) return;
// check if surrounded by try/catch
Node parent = node;
while (true) {
Try tryCatch = context.getParentOfType(parent, Try.class);
if (tryCatch == null) {
break;
} else {
for (Catch aCatch : tryCatch.astCatches()) {
TypeReference catchType = aCatch.astExceptionDeclaration().astTypeReference();
}
parent = tryCatch;
}
}
// get the arguments string
String str = node.astArguments().first().toString();
if (!str.startsWith("\"SOME_PROPERTY\"")) {
context.report(ISSUE, node, context.getLocation(node), "message");
}
}
before this you have to define the specific method by override:
#Override
public List<String> getApplicableMethodNames() {
return Collections.singletonList("set");
}

Getting the code of released key

I'm trying to make a simple platformer using action script 2.0 but I have a problem with getting input from keyboard. I have two function "myKeyDown" and "myKeyUp" that get called whenever a key is pressed down/released.
keyListener.onKeyDown = function(){
myKeyDown();
}
keyListener.onKeyUp = function(){
myKeyUp();
}
The functions check which key was pressed by using Key.getCode() method. It works for myKeyDown but it's buggy for myKeyUp. The bug happens if (for example) I first press A (to move left), then W (to jump), then release W and then release A. The player won't stop moving (even though that's what should happen when you release A)
I understand the problem here. Key.getcode return the code of the last pressed key and what I want is the code for the last released key. I've been searching for hours for a function like this but I haven't found anything.
Here's the code for both myKeyDown and myKeyUp functions
function myKeyDown(){
//A
if(Key.getCode() == 65){
velX=-3;
}else
//D
if(Key.getCode() == 68){
velX=3;
}else
//W
if(Key.getCode() == 87){
if(isInAir == false){
jump();
}
}
}
function myKeyUp(){
//A
if(Key.getCode() == 65){
if(velX==-3){
velX=0;
}
}else
//D
if(Key.getCode() == 68){
if(velX==3){
velX=0;
}
}
}
for cases like this, when you need to hold/release multiple keys a little bit different approach would be better for key handling.
what you can do is use onEnterFrame event listener to check for the pressed keys in case of events when something has to be continuous.
an example
var my_keys:Array = new Array();
my_keys["jump"]=false;
my_keys["right"]=false;
my_keys["left"]=false;
//keydown sets the variables to true
keyListener.onKeyDown = function(){
code=Key.getCode();
if(code==65){
my_keys["left"]=true;
}
if(code==68){
my_keys["right"]=true;
}
if(code==87){
my_keys["jump"]=true;
}
//etc, etc, anything else you wish
//of course, this doesn't prevent you from calling additional one-time events from the keydown!
}
//keyup unsets the button variables
keyListener.onKeyUp = function(){
code=Key.getCode();
if(code==65){
my_keys["left"]=false;
}
if(code==68){
my_keys["right"]=false;
}
if(code==87){
my_keys["jump"]=false;
}
}
now at every point of your game you have a set of keys that are pressed stored in the my_keys array. of course you could use a more generic function inside the keyDown/keyUp and pass the Key.getCode itself directly into the array as indexes instead of the captioned array (like my_keys[Key.getCode()]=true;), it would be even shorter to write. however, i found this to be more illustrative as an example, feel free to modify the code as you need
what you want now is a function that would handle the behavior based on what keys are pressed.
in your case this could, for example, be:
this.onEnterFrame=function(){ //you don't have to use "this" movieclip reference if you have other enterframe events in the movieclip. just don't forget to modify the objcet paths
if(my_keys["left"]){
velX=-3;
}
if(my_keys["right"]){
velX=+3;
}
if((my_keys["jump"])&&(!isInAir)){ //note that i added !isInAir instead of (isInAir==false). this is an equivalent expression, it's just shorter and nicer
jump();
}
}