A Usable Mac: Yosemite + Reduced Transparency + Lucida Grande

I updated to OS X 10.10 after a day it was released – only to be stunned by the really, really ugly looking UI. @francispereira dubs this new update as “Polio infected”. There’s transparency where it should never have been in the first place, and the font smoothing engine is gone haywire with the new system default font, Helvetica.

Let’s fix it:

Drop the transparency

Open System Preferences(type sys in Spotlight). Open the Accessibility settings(second last row, extreme right). Check the checkbox that says “Reduce transparency”.

Revert the system default font to Lucida Grande(the font used in OS X 10.9 and earlier)

Download this app which I found here. Uncompress the downloaded file, then right click on the extracted app, and click on Open. Then click on the Patch and Install button in the dialog box that appears. It will then prompt you for your system password, as it copies Lucida Grande from /System/Library/Fonts to /Library/Fonts, and then patches it to be the system default font.

Next, log out and log back in to see a more usable Mac.

Seriously Tim, you ought to check yourself before you wreck yourself.

Download your Coursera lectures using JS, bash and wget

So, in light of recent events, I was unable to follow up on my Coursera Algorithms course.

Trying to find a way to download all the lectures at once, I couldn’t find a way that worked for me – I found two, but they simply didn’t work. With the help of some JavaScript that I got from one of these sources, I cooked up the following steps to easily download all the lectures at once:

Step 1: Extract the lecture names, and their IDs from the Coursera page
Navigate to your lecture page(for me, it was https://class.coursera.org/algs4partII-003/lecture).
Execute the following JavaScript in the Console(in Chrome, use the Inspect Element option):

function findLectures () {
  var link_elems = document.querySelectorAll('.lecture-link');
  var lectures = "";
  Array.prototype.slice.call(link_elems).forEach(function (elem, i) {
    var lecture = i + "|" + elem.getAttribute('data-lecture-id') + "|" + elem.innerText.trim();
    lectures += lecture + "\n";
  });
  return lectures;
}

Then call the method findLectures(). This will print each lecture in the following format: Lecture position in page|Lecture ID|Lecture name.
Example output:

0|43|Course Introduction (9:22)
1|1|Introduction to Graphs (9:32)
2|2|Graph API (14:47)

Save this to a file named lectures.txt(exclude any quotes that get pasted)

Step 2: Export Coursera’s cookies
Use the Chrome plugin cookie.txt export to export all the cookies that Coursera has saved. Save the result to a file named cookies.txt

Step 3: Download them!
Run the following in the terminal:

export COUNT=1; while read line; do lecture_name=`echo $line | awk -F '|' {'print $3'}` lecture_id=`echo $line | awk -F '|' {'print $2'}`; echo "Downloading lecture $COUNT; ID=$lecture_id; Name=$lecture_name..."; ((COUNT++)); wget --load-cookies cookies.txt https://class.coursera.org/algs4partII-003/lecture/download.mp4?lecture_id=$lecture_id -O "$COUNT - $lecture_name"; done < lectures.txt

Make sure you replace the link to where your lectures are listed. The above link has “https://class.coursera.org/algs4partII-003/lecture/” in it.

This will download all the lectures in the current working directory. It does not maintain any relationship with the week that the lecture was released in. It downloads them in the order that they are listed on the Coursera lecture page.

“The Library” is here

“The Library” is a collection of several popular encyclopedias. It is your one stop for popular game guides and TV show trivia. You can search, and bookmark articles from various encyclopedias.
What’s more? Each time the app is launched, it displays a random featured article from the encyclopedia you last viewed! Explore more about your favourite game/TV show each day.

Popular encyclopedias include:
– Doctor Who
– Assassin’s Creed
– Lord of the Rings
– Mass Effect
– and 42 more!

With this app, you can:
– Read more about your favourite character
– Read about movie plots, and further details
– Game level guides and walk-throughs
– and much more!

Get it on Google Play

CardBox – Personalize a card for every occasion

We[the CardBox developers], have recently launched a brand new app, CardBox, which allows you to create and instantly share greeting cards for almost any occasion!
CardBox allows you to create cards for the following occasions currently:

  • Birthdays
  • Anniversaries
  • Christmas
  • New Year’s day
  • Valentine’s day
  • Women’s day
  • Mother’s day
  • Father’s day
  • Parents’ day
  • Grandparents’ day
  • Halloween
  • Children’s day
  • Thanksgiving

Here’s a review from one of our fans:

Creating personalized cards has never been this easy! Be it Christmas or New Year's or birthdays and anniversary wishes, CardBox allows you to custom make your own cute little e-card to send to the world. The app contains a bunch of ready-made cards to use for popular events. You can personalize these by adding in your own text and images. If you are more inclined towards the do-it-yourself cards, you can make your own from scratch as well, with the option to use your own photos, and the tons of font and color options available. One of the features that I appreciate most about CardBox is that it auto-syncs with your Facebook friends' information and sends you reminders of their life events such as birthdays and anniversaries. On the whole, this is a great little app to have just to wish someone on their special day in a very different way.

– Rashmi Anand

Like CardBox on Facebook

Get it on Google Play
Coming soon to iOS.

How to get a File object of an Android raw resource using reflection

Context:

You have a URI to a resource which is placed in the raw directory inside the Android resources directory, res. Say you want to take that raw resource(let’s say it’s an image) and add it to an attachment using FIleBody to a MultiPartEntity. Both these classes are available in the Apache HTTP Components library. FileBody will only allow you to give it a File object in it’s constructor. Certainly, you are stuck as you have the URI to an Android raw resource, and CANNOT create a File object out of it.

 

So what’s the solution? Reflection.

    private File getFileFromRawResource(Uri rUri) {
        String uri = rUri.toString();
        String fn;
        // I've only tested this with raw resources
        if (uri.contains("/raw/")) {
            // Try to get the resource name
            String[] parts = uri.split("/");
            fn = parts[parts.length - 1];
        } else {
            return null;
        }
        // Notice that I've hard-coded the file extension to .jpg
        // I was working with getting a File object of a JPEG image from my raw resources
        String dest = Environment.getExternalStorageDirectory() + "/image.jpg";
        try {
            // Use reflection to get resource ID of the raw resource
            // as we need to get an InputStream to it
            // getResources(),openRawResource() takes only a resource ID
            R.raw r = new R.raw();
            Field frame = R.raw.class.getDeclaredField(fn);
            frame.setAccessible(true);
            int id = (Integer) frame.get(r);
            // Get the InputStream
            InputStream inputStream = getResources().openRawResource(id);
            FileOutputStream fileOutputStream = new FileOutputStream(dest);
            // IOUtils is a class from Apache Commons IO
            // It writes an InputStream to an OutputStream
            IOUtils.copy(inputStream, fileOutputStream);
            fileOutputStream.close();
            return new File(dest);
        } catch (NoSuchFieldException e) {
            Log.e("MyApp", "NoSuchFieldException in getFileFromRawResource()");
        } catch (IllegalAccessException e) {
            Log.e("MyApp", "IllegalAccessException in getFileFromRawResource()");
        } catch (FileNotFoundException e) {
            Log.e("MyApp", "FileNotFoundException in getFileFromRawResource()");
        } catch (IOException e) {
            Log.e("MyApp", "IOException in getFileFromRawResource()");
        }
        return null;
    }    

The code is pretty much self-explanatory. Drop a comment if you have any questions/doubts.

Calculate the REAL scale factor and the angle of rotation from an Android Matrix

After performing transformations such as rotation of a bitmap about an arbitrary point, the scale is lost. Of course, this makes sense because the bitmap is rotated inside the same bounds.

To get the real scale now, along with the most reliable degree of rotation, I had to follow this method. Hope it saves the rest of you a night or two.

float[] v = new float[9];
matrix.getValues(v);
// translation is simple
float tx = v[Matrix.MTRANS_X];
float ty = v[Matrix.MTRANS_Y];

// calculate real scale
float scalex = values[Matrix.MSCALE_X];
float skewy = values[Matrix.MSKEW_Y];
float rScale = (float) Math.sqrt(scalex * scalex + skewy * skewy);

// calculate the degree of rotation
float rAngle = Math.round(Math.atan2(v[Matrix.MSKEW_X], v[Matrix.MSCALE_X]) * (180 / Math.PI));

Multi Touch in Android – Translate, Scale, and Rotate

Here’s a quick and easy implementation of Android’s multi touch feature – one finger to move, two to zoom, and three to rotate the image.

Assuming you have a basic understanding of 2D matrix transformations, the Matrix class in Android uses a 3×3 matrix to achieve all of the 2D transformations.

The source code and pre -built APK is available. See the end of this post.

Main activity – MultiTouch.java

package com.multitouch.example;

import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class MultiTouch extends Activity implements OnTouchListener {

    // these matrices will be used to move and zoom image
    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();
    // we can be in one of these 3 states
    private static final int NONE = 0;
    private static final int DRAG = 1;
    private static final int ZOOM = 2;
    private int mode = NONE;
    // remember some things for zooming
    private PointF start = new PointF();
    private PointF mid = new PointF();
    private float oldDist = 1f;
    private float d = 0f;
    private float newRot = 0f;
    private float[] lastEvent = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView view = (ImageView) findViewById(R.id.imageView);
        view.setOnTouchListener(this);
    }

    public boolean onTouch(View v, MotionEvent event) {
        // handle touch events here
        ImageView view = (ImageView) v;
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                start.set(event.getX(), event.getY());
                mode = DRAG;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                lastEvent = new float[4];
                lastEvent[0] = event.getX(0);
                lastEvent[1] = event.getX(1);
                lastEvent[2] = event.getY(0);
                lastEvent[3] = event.getY(1);
                d = rotation(event);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);
                    float dx = event.getX() - start.x;
                    float dy = event.getY() - start.y;
                    matrix.postTranslate(dx, dy);
                } else if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        matrix.set(savedMatrix);
                        float scale = (newDist / oldDist);
                        matrix.postScale(scale, scale, mid.x, mid.y);
                    }
                    if (lastEvent != null && event.getPointerCount() == 3) {
                        newRot = rotation(event);
                        float r = newRot - d;
                        float[] values = new float[9];
                        matrix.getValues(values);
                        float tx = values[2];
                        float ty = values[5];
                        float sx = values[0];
                        float xc = (view.getWidth() / 2) * sx;
                        float yc = (view.getHeight() / 2) * sx;
                        matrix.postRotate(r, tx + xc, ty + yc);
                    }
                }
                break;
        }

        view.setImageMatrix(matrix);
        return true;
    }

    /**
     * Determine the space between the first two fingers
     */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }

    /**
     * Calculate the mid point of the first two fingers
     */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    /**
     * Calculate the degree to be rotated by.
     *
     * @param event
     * @return Degrees
     */
    private float rotation(MotionEvent event) {
        double delta_x = (event.getX(0) - event.getX(1));
        double delta_y = (event.getY(0) - event.getY(1));
        double radians = Math.atan2(delta_y, delta_x);
        return (float) Math.toDegrees(radians);
    }
}

An important function that is always used is postXx(). This function concats a new matrix of the type Xx to the existing matrix object. Using setXx() will reset the matrix’s Xx property.
Main layout – main.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ImageView android:id="@+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/butterfly"
android:scaleType="matrix" />

</FrameLayout>

Browse and download the source code on GitHub.

Rooted? Get the most of your Android phone | A power saving strategy

The smart-phones these days are power hungry devices, and often drain the battery within six to eight hours, or even less. However, if it’s running Android, there’s a good chance that that can change. The key is to find the right set of tools, and optimize your phone to be right on the edge, there when you need it, and highly responsive. What it takes is a power saving strategy, offered by Set CPU for root users android application. This nifty little tool, worth it’s price, is by far the most essential application among several others(probably thousands). It allows you to set profiles, and depending on how well you set it up, you can extend your battery life by a couple of hours(~four).
So how do you balance phone responsiveness while saving power at the same time?
Take a look at the following two screenshots, it’s what I’ve got setup:

The settings indicated above, automatically scale the CPU frequency. The highest CPU frequency supported by your processor will take the most power, so if you’d want to scale it down, especially during low levels of battery, this application can help you do so automatically.
Read about the profile priority when setting up newer profiles for this application.

You can read about which CPU frequency governor is right for you here

The Unofficial Gentoo Linux x86 uClibC stage3s’

Update:
The catalyst spec files are available here:
https://github.com/judepereira/gentoo-development/tree/master/x86/uclibc/catalyst

Following this Gentoo bug:
https://bugs.gentoo.org/show_bug.cgi?id=441976
We have official experimental uClibC for x86 and amd64 stages.
I will not be maintaining these unofficial ones any longer.

The link to the official archives is:
http://mirrors.rit.edu/gentoo/experimental/x86/uclibc/
and
http://mirrors.rit.edu/gentoo/experimental/amd64/uclibc/

The uclibc experimental stages on the gentoo mirrors are all outdated(they go back to years), so here are my stage3s’, which have been updated. They’re very similar to, and in fact can be considered to be the same stages that the Gentoo Community provides, only updated.

As of 27th August 2011, they are now built by catalyst.

The stages are built by catalyst now, and I’m looking for the possibility of hosting them on the Gentoo mirrors.

Follow my tutorial here, to get a basic ideology on working with it

stage3-uclibc-x86-26062012 is affected by bug #423491 sys-apps/findutils-4.4.2-r1 and sys-apps/coreutils-8.14 with sys-libs/uclibc – rpmatch.c:58:1: error: redefinition of ‘rpmatch’ /// /usr/include/stdlib.h:810:28: note: previous definition of ‘rpmatch’ was here

The workaround for it right now is to comment the entire function in stdlib.h and those packages will compile well. Also comment the _wur definition, just above the function rpmatch. This is a crude workaround, and it’ll be fixed when upstream decides what’s the solution.

Files:
26th June, 2012
stage3-uclibc-x86-26062012.tar.bz2
stage3-uclibc-x86-26062012.tar.bz2.md5sum

The above stage was not build by catalyst, as it could not deal with the rpmatch bug. This stage was created manually from the last release.

5th August, 2011
stage3-uclibc-x86-02082011.tar.bz2
stage3-uclibc-x86-02082011.tar.bz2.md5sum

7th July, 2011
stage3-uclibc-x86-07072011.tar.bz2
stage3-uclibc-x86-07072011.tar.bz2.md5

1st June, 2011
stage3-uclibc-x86-01062011.tar.bz2
stage3-uclibc-x86-01062011.tar.bz2.MD5

25th April, 2011
stage3-uclibc-x86-25042011.tar.bz2
stage3-uclibc-x86-25042011.tar.bz2.md5sum

For historic releases, post a comment, as to which one you require and why a specific version.
If you want the stage1 or stage2, drop a comment and I shall have them uploaded.

For those of you who would like to build these stages themselves, here are the spec files for catalyst:
stage1.spec
stage2.spec
stage3.spec

Update:
The catalyst spec files are available here:
https://github.com/judepereira/gentoo-development/tree/master/x86/uclibc/catalyst

In addition, I’ve taken down all the stage files that I used to host here, in favour of the official stages now available from the Gentoo mirrors:

Use Ruby to Generate your Shadow Password

I was initially stumbled on creating the shadow compatible SHA-512 hash.
After a little research, the answer was obvious:

require 'digest/sha2'

password = "pass@123"
salt = rand(36**8).to_s(36)
shadow_hash = password.crypt("$6$" + salt)

And you now have a password hash which you can directly use in /etc/shadow