Do you use callbacks only, or .. Promises too?😉

Amr Abdulrahman

Should I read this?

If you’re a JavaScript developer who still uses callbacks (on either the client side or server side) then this post is for you. If you don’t know what Promises are, then you probably will find it useful.

Back in time, JavaScript was initially built to add interactivity to web pages and to be used on the client side. It has been designed to handle user interactions using events and event handlers. Also to make communications with the server. All of these stuff are Asynchronous operations. we can say:

JavaScript is an event-driven programming language.

which means, the flow of the program is determined by events such as user actions (mouse clicks, key presses) or messages from other programs/threads.


So, JavaScript is designed over and encourages the usage of callbacks.

Here’s a simple illustration of how a callback way works. #Main script wants to execute #Function_B after

View original post 323 more words

Android: Should you sign different Apps with the same Key or not?

Releasing your first App is a great milestone, but with releasing the second one, here comes the question: Should I use the same key to sign my new app, or should I generate a new key for it?!!

Well, it totally depends on your needs, so let’s see different needs:

Why using same key for different apps?

  • When you want to use App modularity features (as recommended by the official documentation):

    Android allows apps signed by the same certificate to run in the same process, if the applications so requests, so that the system treats them as a single application. In this way you can deploy your app in modules, and users can update each of the modules independently.

  • When you want to share Code/Data securely between your apps through permissions (also as recommended by the official documentation):

    Android provides signature-based permissions enforcement, so that an app can expose functionality to another app that is signed with a specified certificate. By signing multiple apps with the same certificate and using signature-based permissions checks, your apps can share code and data in a secure manner.

  • If you want to avoid the hassle of managing different keys for different apps.

Why using different keys for different apps?

  • If you are somehow paranoid about security (and you should), not to put all the eggs in one basket, which is highly recommended in this article.

  • When the apps are completely different & won’t ever use the app-modularity or Code/Data sharing described above.

  • When there is a chance (even a small one) that you will sell one of the apps separately in the future, then that app must have its own key from the beginning.

Some useful numbers:
As per this article, they made a study on August 2014, they found that Google Play has about 246,000 Android apps but only 11,681 certificates were found!
The distribution of the number of apps sharing the same key is shown below. The X-axis is the number of apps sharing the same certificate. The Y-axis is the number of certificates.
The distribution of the number of apps sharing the same key. The X-axis is the number of apps sharing the same certificate. The Y-axis is the number of certificates.

Be aware that once you signed your app and uploaded it to Google Play, you can’t undo this step, you can’t sign it with a different certificate key. so make your decision wisely!

I hope you find here the answer you were searching for, & hope you share your case with us in the comments .. Good Luck🙂

Querying MongoDB ObjectId by Date range

I had a situation where I wanted to query a collection in the production environment for a specific day, but the surprise for me was that the collection has no CreatedAt field in it in the first place🙂, so I had to rely on the ObjectId of the document. Searching around for a while I found this answer by kate, so I wanted to share it with all of you, & even shared it as an answer on another StackOverflow question.

And here it goes, let’s assume we want to query for April 4th 2015, we can do it in the terminal like this:

> var objIdMin = ObjectId(Math.floor((new Date('2015/4/4'))/1000).toString(16) + "0000000000000000")
> var objIdMax = ObjectId(Math.floor((new Date('2015/4/5'))/1000).toString(16) + "0000000000000000")
> db.collection.find({_id:{$gt: objIdMin, $lt: objIdMax}}).pretty()

Android: Loading images Super-Fast like WhatsApp – Part 2

We discussed earlier in Part 1 of this tutorial how Zingoo team wants to deliver the best UX possible to the users, & because WhatsApp is doing a great job with images, so we watched what they are doing, like:

  • Photos are cached, so no need to load them every time you open the app.
  • They first show a very small thumbnail (about 10KB or less) until the real image is loaded, & this is the real pro-tip for their better UX.
  • Photos sizes range around 100KB, which loads the images pretty fast on most common mobile-network speeds.

First 2 points are already discussed in part 1, so question here in part 2 is how could we compress images to be about 100KB to be sent easily over common mobile-networks.

How is it done?
After taking the picture and saving it to a file with path imagePath, we start compressing it to be ready for sending over network:

ImageCompressionAsyncTask imageCompression = new ImageCompressionAsyncTask() {
    protected void onPostExecute(byte[] imageBytes) {
        // image here is compressed & ready to be sent to the server
imageCompression.execute(imagePath);// imagePath as a string

& here is what we do in ImageCompressionAsyncTask:

public abstract class ImageCompressionAsyncTask extends AsyncTask<String, Void, byte[]> {

    protected byte[] doInBackground(String... strings) {
        if(strings.length == 0 || strings[0] == null)
            return null;
        return ImageUtils.compressImage(strings[0]);

    protected abstract void onPostExecute(byte[] imageBytes) ;

It is clear that the real juice exists in ImageUtils.compressImage(). Thanks to Ambalika Saha & her brilliant post that enabled me from using this solution in Zingoo, and even writing this post right here🙂 . And here is my version of doing it:

public class ImageUtils {
    private static final float maxHeight = 1280.0f;
    private static final float maxWidth = 1280.0f;

    public static byte[] compressImage(String imagePath) {
        Bitmap scaledBitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;
        float imgRatio = (float) actualWidth / (float) actualHeight;
        float maxRatio = maxWidth / maxHeight;

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;


        options.inSampleSize = ImageUtils.calculateInSampleSize(options, actualWidth, actualHeight);
        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
            bmp = BitmapFactory.decodeFile(imagePath, options);
        } catch (OutOfMemoryError exception) {

        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

        ExifInterface exif;
        try {
            exif = new ExifInterface(imagePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
            } else if (orientation == 3) {
            } else if (orientation == 8) {
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
        } catch (IOException e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
        return out.toByteArray();

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        final float totalPixels = width * height;
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {

        return inSampleSize;

I hope you like it.

Android: Loading images Super-Fast like WhatsApp – Part 1

Zingoo is a new promising app that will rock your weekends, outings and any happening that you want to easily enjoy watching its moments over & over again (we are now doing the Android version, then the iOS one). Because we want Zingoo to be born strong, it has to deliver the best possible [UX] to all awesome-moments lovers around the world, which means we have to do our best in loading the images.

Because we (at Begether) do listen to our users, we heard a lot of comments on how WhatsApp is loading images super-fast, so we dug deeper to know what we can do about it, & here is what we find,

What does WhatsApp do?
WhatsApp is doing the following (numbers are approximate):

  • Photos sizes range around 100KB, which loads the images pretty fast on most common mobile-network speeds. (part 2 explains how to achieve this)
  • Photos are cached, so no need to load them every time you open the app (almost no need to mention this🙂 ).
  • They first show a very small thumbnail (about 10KB or less) until the real image is loaded, & this is the real pro-tip for their better UX.

The last tip has a different variance by calculating the image dimensions & the approximate color of the image that will be shown & applying it to its placeholder, like the coming 3 minutes in this video:

but still, the thumbnail is away more cooler, right?😉

How is it done?
To achieve the caching there are some good Android libraries out there that are doing a good job, but one of them is doing a way better than the others, which is Picasso. Both caching on disk & on memory are built under the hood, with a very developer-friendly API, I just love what Jake Wharton & his mates did for all of us, thanks guys.
Using Picasso is pretty easy, just like this example one-liner:


you just need first to add Picasso to your gradle files with the urlConnection library (according to this issue), like this:

compile 'com.squareup.picasso:picasso:2.4.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'

After solving the caching issue, we need to apply the thumbnail great tip, we need to use Picasso 2 times, one for loading the thumbnail and the other for loading the real image like the comment I made on this issue. Also to avoid the thumbnail’s pixlation effect (due to its small size), it would be better to make a blurring effect on it,
WhatsApp's Thumbnail Loading Effect

and here is how it is done:

Transformation blurTransformation = new Transformation() {
    public Bitmap transform(Bitmap source) {
        Bitmap blurred = Blur.fastblur(LiveImageView.this.context, source, 10);
        return blurred;

    public String key() {
        return "blur()";

    .load(thumbUrl) // thumbnail url goes here
    .resize(imageViewWidth, imageViewHeight)
    .into(imageView, new Callback() {
        public void onSuccess() {
                    .load(url) // image url goes here
                    .resize(imageViewWidth, imageViewHeight)

        public void onError() {

We used the Callback() functionality to start loading the full image after the thumbnail is completely loaded, with using the blurred thumbnail’s drawable as the new placeholder for the real image, & this is how the magic is being done right here🙂.
Also the blurring made here is Blur.fastblur(), thanks to Michael Evans & his EtsyBlurExample example, you can find this class here.

The only remaining part is how to compress the large images (which could be 2 to 4 MB) to be only about 100 KB, which is discussed in Part 2.


All Node.js frameworks in one page

Do you wanna use Node.js but don’t know which framework that suits your needs ?

well, this page has all available frameworks known today categorized by:

So, this is all you need to start choosing the framework that suits your needs, good luck.

Tip: look for how many github stars the framework has got, it shows you how much it is trusted by people like you😉 , which brings us to the incredible record by Meteor which is 22,337 stars till now!!

Solved: Restarting node server may stop recurring Agenda jobs

Node is the future, it is that simple. With that being said, one of the important things one will look for is how to start cron-jobs, is it by just using cron-tab to start a stand-alone script, or could it be a plugin inside the code base itself, like what is available in Node with its great npm set of packages that you can choose from,
one of the very good packages for managing the cron-jobs is Agenda which comes with a great feature for visualizing your jobs by using Agenda-UI which looks like this:
enter image description here

After starting using Agenda (0.6.27), I faced a serious issue when restarting my node server, because the recurring jobs (i.e agenda.every '30 minutes') may stop working for no reason, my code was like this:

agenda.define 'my job', my_job_function
agenda.every '30 minutes', 'my job'

for a while, I thought in leaving Agenda for good, & using the widely known Cron instead, which is a really great alternative by the way, it is almost an imitation of the linux’s cron-tab interface, with an incredible number of downloads (95,483 downloads in the last month),
The only thing kept me trying to find a solution is Agenda’s superior advantage by monitoring the jobs easily using its Agenda-UI interface, so I opened an issue on Agenda’s github page & digged in a little more until I found the solution.

Solution 1
Since redefining our jobs on server start didn’t solve it, so I managed to remove the old broken recurring jobs when shutting down the server like this (you can add the following to your startup scripts like putting it in app.js):

graceful = ()->
    agenda.cancel repeatInterval: { $exists: true, $ne: null }, (err, numRemoved)->
        agenda.stop ()->
            process.exit 0

and with server start, the jobs will be redefined again & voila,
I’m using this workaround now, & it is working like a charm.

Solution 2
While observing the broken jobs & what causes them to stop working, I found that they are locked, because restarting the server while they are still running prevented them from releasing the lock, so droppedoncaprica has proposed the following solution to release all locks when starting the server:

agenda._db.update {lockedAt: {$exists: true } }, { $set : { lockedAt : null } }, (e, numUnlocked)->
    if e
        console.log e
    console.log "Unlocked #{numUnlocked} jobs."
    # redefine your jobs here

Once Agenda solves this issue, I’ll update the post with the version containing the fix isA.