SetUp() and TearDown() Methods in DalekJs - dalekjs

Is there a simple way to add a setUp() and/or a tearDown() Method to every DalekJs test?
For example:
I want to resize my browserwindow before and after every test.
Edit:
I played with it around over the weekend and came up with this, it is the easiest solution that i came up with.
test.open(url);
setUp(test);
test.assert.exists('#logo', 'Logo exists');
tearDown(test);
test.done();
function setUp(test) {
test.resize({width:1280, height: 1024})
/*...*/
}
function tearDown(test) {
test.resize({width:1280, height: 1024})
}

Related

What can/should be in setup()'s return {}, and what must be directly in setup()?

I started with Vue3 some time ago (moving from Vue2) and I find the Composition API great (at least at my amateur/hobby dev level).
I got used to the structure
setup() {
let a = ref(0)
const standaloneFunction = () => 5;
const functionUsingRefs = () => 10 * a.value
return {
a,
standaloneFunction,
functionusingRefs,
}
}
To my surprise, I discovered today some code that would rather
setup() {
return {
a: ref(0),
standaloneFunction() { return 5 },
functionUsingRefs() { 10 * a.value },
}
}
In other words, what is returned is defined on the spot. This leads to shorter and more readable code (which is certainly a matter of taste).
My question: taking functionUsingRefs() in the example above, can I always assume that a reactive variable, decalred either right under setup() or in its return {} will be available in return {}?
Or said differently: are there elements (refs, functions, ...) that must be declared right in setup() to be available for other elements (specifically to the ones in return {})?

Android: ASyncTask's behavior contrary to documentation

First time writing an AsyncTask and I seem to have a subtle design flaw that prevents both ProgressDialog, ProgressBar, and even Log.d() from working properly. I suspect that somehow I am not actually creating a new thread/task.
Short: the symptoms
A ProgressDialog is created in the constructor, and the code orders Android to show it in onPreExecute(), but the dialog never shows.
onProgressUpdate() is supposed to execute whenever I call publishProgress() from within doInBackground(), correct? Well, it doesn't. Instead, it executes when doInBackground() completes.
Long: investigations
Things I have verified through the emulator and, when possible, on a phone:
onPreExecute() is definitely called
the progress bar is not reset until after doInBackground() completes
update_dialog.show() is definitely executed, but the dialog does not appear unless I remove the .dismiss() in onPostExecute(); I imagine dialog is, like the progress bar, not shown until after doInBackground() completes, but is naturally immediately dismissed
the code will happily show dialogs when no computation is involved
doInBackground() definitely invokes publishProgress()
when it does, onProgressUpdate() does not execute immediately! that is, I have a breakpoint in the function, and the debugger does not stop there until after doInBackground() completes! (perhaps this is a phenomenon of the debugger, rather than doInBackground(), but I observe the same symptoms on a mobile device)
the progress bar gets updated... only after doInBackground() completes everything
similarly, the Log.d() data shows up in Android Monitor only after doInBackground() completes everything
and of course the dialog does not show up either in the emulator or on a device (unless I remove .dismiss() from onPostExecute())
Can anyone help find the problem? Ideally I'd like a working dialog, but as Android has deprecated that anyway I'd be fine with a working progress bar.
Code
Here are the essentials, less the details of computation &c.:
Where I call the AsyncTask from the main thread:
if (searching) { // this block does get executed!
Compute_Task my_task = new Compute_Task(overall_context, count);
my_task.execute(field, count, max_x, max_y);
try { result = my_task.get(); } catch (Exception e) { }
}
The AsyncTask itself:
private class Compute_Task extends AsyncTask<Object, Integer, Integer> {
public Compute_Task(Context context, int count) {
super();
current_positions = 0;
update_dialog = new ProgressDialog(context);
update_dialog.setIndeterminate(true);
update_dialog.setCancelable(false);
update_dialog.setTitle("Thinking");
update_dialog.setMessage("Please wait");
}
protected void onPreExecute() {
super.onPreExecute();
update_dialog.show();
ProgressBar pb = ((ProgressBar) ((Activity) overall_context).findViewById(R.id.progress_bar));
pb.setMax(base_count);
pb.setProgress(0);
}
protected void onPostExecute() {
super.onPostExecute();
update_dialog.dismiss();
}
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
ProgressBar pb = ((ProgressBar) ((Activity) overall_context).findViewById(R.id.progress_bar));
pb.setMax(base_count);
pb.incrementProgressBy(1);
Log.d(tag, values[0].toString());
}
protected Integer doInBackground(Object... params) {
Integer result = compute_scores(
(boolean[][]) params[0], (Integer) params[1], (Integer) params[2], (Integer) params[3], 0)
);
return result;
}
public int compute_scores(boolean[][] field, int count, int max_x, int max_y, int level) {
int result, completed = 0;
switch(count) {
// LOTS of computation goes on here,
// including a recursive call where all params are modified
if (level == 0)
publishProgress(++completed);
}
}
ProgressDialog update_dialog;
}
Turns out this is basically the same issue as the one given here. The "fatal" line is this one:
try { result = my_task.get(); } catch (Exception e) { }
Apparently this puts the UI thread into deep sleep. One should not use get() with an AsyncTask unless one is willing to suspend the UI thread. We have to perform a little magic in onPostExecute() instead.
Although it turns out that this was a duplicate, I didn't find it until after I wrote it, because I didn't realize the thread was blocking.

OnCollisionEnter2D isn't working and I don't know why

I'm new to Unity and c# and I'm trying to get the basics down but I seem to be having some trouble with the collision. I want to get a falling object to destroy when it collides with another object that is stationary. All of the objects are set to Box Collider 2D in Unity and after hours of searching I can't seem to figure out what's wrong with it. Any help would be much appreciated!
using UnityEngine;
using System.Collections;
public class Destroy : MonoBehaviour {
// Use this for initialization
void Start () {
transform.position = new Vector2 (0, -10);
Debug.Log ("Game Start");
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Target") //|| (col.gameObject.tag == "fallingCube2"))
{
Debug.Log ("There has been a collision!");
Destroy (col.gameObject);
}
else
if (col.gameObject.tag == "otherTarget")
{
Debug.Log ("There has been a collision!");
Destroy (col.gameObject);
}
}
}
Make sure that the Tag is the same (care with uppercase), and use col.tag == "Target".
The GameObject must have and BoxCollider2D or other Collider2D with the property isTrigger to false.
I always use OnTriggerEnter2D(Collider2D col) because I dont want that my pj stops falling or whatever

TypeScript: Check if derived class implements method

I got two classes, one deriving from the other, and on the base class I need to check if the derived class is implementing a method with a specific name:
class Foo {
constructor() { }
childHasMethod() {
if(this.method) {
console.log('Yay');
} else {
console.log('Nay');
}
}
}
class Bar extends Foo {
constructor() {
super();
this.childHasMethod();
}
method() {
}
}
var bar = new Bar();
Even though the line if(this.method) { is marked red on the playground, it works. But the local compiler throws a compilation error: The property 'method' does not exist on value of type 'Foo'.
Is there a clean way to achieve what I'm trying to do?
In order to "sneak it past the compiler" you can treat this as dynamic:
(<any>this).method
I have made a full example of this on the TypeScript Playground.
childHasMethod() {
if((<any>this).method) {
alert('Yay');
} else {
alert('Nay');
}
}
Having said this, having a base class know details about its sub-classes could get you into tricky places. Usually I would try to avoid this as it sounds like the specialisations are leaking into the base class - but you may have a particular thing you are doing and know your program better than me so I'm not saying "don't do this" - just "are you sure" :)

Best way to execute a function after exactly one frame?

With ActionScript3 for Flash Player 9+, what is the nicest way to call a "once-off" function after exactly one frame?
I am aware of the Timer class and it's uses, and the callLater method on Flex UIComponents (which, glancing through the source, doesn't look very efficient in this scenario). I'm also aware of setTimeout (in flash.utils).
The Timer class and setTimeout utility are both time based, so how would we guarantee that our function will get called after exactly one frame?
From my limited testing it seems that functions passed to setTimeout only execute after at least one frame (try setting the delay to 0). But this is not guaranteed.
Of course, we could listen for Event.ENTER_FRAME events from a DisplayObject, but that seems like overkill for a once-off delayed function call.
Flex was intended to abstract away the frame-based nature of the Flash Player so you will not find much to help you with your problem. The best approach is to listen for ENTER_FRAME as you suggest. If that's overkill (and I'm not sure why you think it is), you could create a helper class which takes a DisplayObject and Function as arguments which will automatically add/remove the ENTER_FRAME event listener for you.
public class NextFrameCommand() {
private var functionToCall : Function;
public function NextFrameCommand(dObj: DisplayObject, func : Function) {
functionToCall = func;
}
public function start() : void {
dObj.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(e : Event) : void {
e.target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
functionToCall.call();
}
}
I haven't tested that code but hopefully you get the idea....
Playing with the solutions provided by Theo and brd6644 I came us with this. It allows multiple functions (with parameters) to be queued and executed in order at the next frame.
public class DelayedFunctionQueue
{
protected var queue:Array;
protected var dispatcher:Sprite;
public function DelayedFunctionQueue()
{
queue = new Array();
dispatcher = new Sprite();
}
public function add( func:Function, ... args ):void
{
var delegateFn:Function = function():void
{
func.apply( null, args );
}
queue.push( delegateFn );
if ( queue.length == 1 )
{
dispatcher.addEventListener( Event.ENTER_FRAME, onEF, false, 0, true );
}
}
protected function onEF( event:Event ):void
{
dispatcher.removeEventListener( Event.ENTER_FRAME, onEF, false );
queue = queue.reverse();
while ( queue.length > 0 )
{
var delegateFn:Function = queue.pop();
delegateFn();
}
}
}
Might be useful to someone.
One way would be to see how many frames per second your project is set for and let the setTimeout function delay for 1 frame time within that setting.
So if your project is set at 24 frames per second, you delay for 42 millisec in setTimeout.
var timerSprite:Sprite = new Sprite();
timerSprite.addEventListener(Event.ENTER_FRAME, oneFrameHandeler);
function oneFrameHandeler(e:Event):void
{
timerSprite.removeEventListener(Event.ENTER_FRAME, oneFrameHandeler);
timerSprite = null;
trace("one frame later!")
}
ENTER_FRAME is not overkill - something like this is short and easy
addEventListener(Event.ENTER_FRAME, function(e:Event):void
{
removeEventListener(Event.ENTER_FRAME, arguments["callee"]);
onceOffFunction();
}

Resources