Categories
discuss

Fade background image in and out with jQuery?

So far, I’ve tried a bunch of things to the effect of the following, without success:

<script type="text/javascript">
var x = 0;

while (true) {
    /* change background-image of #slide using some variation
    of animate or fadeIn/fadeOut with or without setTimeout */
    x++;
}
</script>

Any ideas?

Answer

You can fade background colors but not background images. The way to work around this is to have your images as <img> tags and hide them by default display:none;. Give your images position:absolute and z-index:-1 so they act like backgrounds and are behind everything else.

Here’s a quick example of images fading one after the other.

HTML

<img src=".." />
<img src=".." />

CSS

img{
 position:absolute;
 z-index:-1;
 display:none;
}

jQuery

function test() {
    $("img").each(function(index) {
        $(this).hide();
        $(this).delay(3000* index).fadeIn(3000).fadeOut();
    });
}
test();

Check working example at http://jsfiddle.net/RyGKV/

Categories
discuss

TimePicker in PreferenceScreen

I’d like to create a preference field called Interval and I want to be able to popup a TimePicker and set a mm:ss formated value with minimal value 00:30 and step 30 seconds.

Is it possible to use TimePicker in PreferenceScreen ?

Answer

There is no TimePreference built into Android. However, creating your own is fairly easy. Here’s one I did:

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;

public class TimePreference extends DialogPreference {
    private int lastHour=0;
    private int lastMinute=0;
    private TimePicker picker=null;

    public static int getHour(String time) {
        String[] pieces=time.split(":");

        return(Integer.parseInt(pieces[0]));
    }

    public static int getMinute(String time) {
        String[] pieces=time.split(":");

        return(Integer.parseInt(pieces[1]));
    }

    public TimePreference(Context ctxt, AttributeSet attrs) {
        super(ctxt, attrs);

        setPositiveButtonText("Set");
        setNegativeButtonText("Cancel");
    }

    @Override
    protected View onCreateDialogView() {
        picker=new TimePicker(getContext());

        return(picker);
    }

    @Override
    protected void onBindDialogView(View v) {
        super.onBindDialogView(v);

        picker.setCurrentHour(lastHour);
        picker.setCurrentMinute(lastMinute);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);

        if (positiveResult) {
            lastHour=picker.getCurrentHour();
            lastMinute=picker.getCurrentMinute();

            String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);

            if (callChangeListener(time)) {
                persistString(time);
            }
        }
    }

    @Override
    protected Object onGetDefaultValue(TypedArray a, int index) {
        return(a.getString(index));
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        String time=null;

        if (restoreValue) {
            if (defaultValue==null) {
                time=getPersistedString("00:00");
            }
            else {
                time=getPersistedString(defaultValue.toString());
            }
        }
        else {
            time=defaultValue.toString();
        }

        lastHour=getHour(time);
        lastMinute=getMinute(time);
    }
}
Categories
discuss

how to detect document size change in jquery

so suppose that clicking something would lead to a new content being loaded to the screen hence the height of document changes and whereas previously there are no scroll bars, now there actually are scrollbars…

how do I detect something like that happening using jquery

binding resize event onto window only detects window resize whereas binding it into document doesn’t work

Answer

Update:
Please don’t use the DOMSubtreeModified event. It is old, deprecated and not well-supported by browsers. In 99,9 % of the cases, there is a different event you can listen on. Most likely you are one of those people using jQuery and doing some AJAX stuff, so please take a look at their AJAX docs.


These are all available events. You would have to detect $(document).bind('DOMSubtreeModified', function() { ... }); and check for a dimension change to the previous firing.

var height = $(this).height(),
    width  = $(this).width();
$(document).bind('DOMSubtreeModified', function() {
    if($(this).height() != height || $(this).width() != width) {
        recalibrate();
    }
});

This event is firing every time anything is done to the DOM. Therefore it will slowdown your browser.

We should get a better alternative. Could you please give us more information to your scenario?

Categories
discuss

How to jUnit test the result of code in another thread

I have a process that runs in a thread (used as a realtime signal analysis process). I want to feed that thread process a known input, and then test — in jUnit — that the output is correct. I have a callback listener that can notify me when the thread finishes processing the data and I can run assertions on the result successfully by registering the test case itself as a listener.
When those assertions fail, they do throw an exception. But that exception is not registered as a failure by jUnit, presumably because they are happening outside of a test method.

How do I structure my jUnit test so that the test fails correctly after the listener returns? Here’s a simplified version of the code.

 public class PitchDetectionTest extends TestCase 
    implements EngineRunCompleteListener() {
  AudioData            fixtureData;
  PitchDetectionEngine pitchEngine;

  public void setUp() {
    fixtureData = <stuff to load audio data>;
  }

  public void testCorrectPitch() {
    pitchEngine = new PitchEngine(fixtureData);
    pitchEngine.setCompletionListener(this);
    pitchEngine.start();   
    // delay termination long enough for the engine to complete
    try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
  }

  // gets called by the PitchEngine when it has finished processing all data in the
  // fixtureData.   This is the only method defined by interface    
  // EngineRunCompleteListener.
  public void notifyEngineRunComplete() {

    // The real code asserts things about the PitchEngine's results.   When they fail, 
    // an exception is thrown that I can see in the console, but this unit test still  
    // shows as 'success' in the jUnit interface.   What I want is to see 
    // testCorrectPitch() fail.
    assertTrue(false);  

  }

}

public class PitchEngine () {
  EngineRunCompleteListener completionListener();
  Thread myThread;

  public void start() {
    // other stuff
    myThread = new Thread(this);
    myThread.start();    
  }

  public void run() {
    while (some condition) {
      // do stuff with the data
    }
    if (engineRunCompleteListener != null) {
      engineRunCompleteListener.notifyEngineRunComplete();
    }
  }

}

Answer

You already have two threads running. Your junit thread, and the process thread (started by myThread.start().
Off the top of my head, I can think of at least two options that you have, all of them involving moving the assertion away from notifyEngineRunComplete. For example:

  • You can use join to wait for the process thread to finish, and then do your assertions (Javadoc here).
  • You can put your junit thread to sleep by waiting on a monitor object, and then in your callback function notify this monitor. This way you’ll know that the process has finished.
  • You can use an Executor and a Future object. I think this would be the coolest solution if it works with your classes (Javadoc here).
Categories
discuss

How to hash some string with sha256 in Java?

How can I hash some string with sha256 in Java?

Answer

SHA-256 isn’t an “encoding” – it’s a one-way hash.

You’d basically convert the string into bytes (e.g. using text.getBytes(StandardCharsets.UTF_8)) and then hash the bytes. Note that the result of the hash would also be arbitrary binary data, and if you want to represent that in a string, you should use base64 or hex… don’t try to use the String(byte[], String) constructor.

e.g.

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..