Convert a Transparent Image to Grayscale in iOS

Converting an image to grayscale can be thought of redrawing the image in a color space where the only colors available are only shades of gray, varying from black at the weakest intensity to white at the strongest [wikipedia]. The manual process involves converting the individual RGB values for each pixel of the image to a corresponding greyscale intensity value according to some formula. The formula described in this wikipedia article can be used for such conversion. However, for images with transparency, ie. with an alpha channel, the process is not that straightforward.

If you are programming in iOS, the SDK is going to save you some considerable effort. The process of converting a UIImage to grayscale is itself an interesting one, in addition to being very easy. Just follow the three steps described below for converting a transparent colored image to grayscale in iOS.

Step 1. Create a opaque, grayscale image from the original image

Step 2. Create a image (mask) taking only the alpha channel from the original image

Step 3. Create a new image from the opaque image by masking it against the image formed in Step 2

Validating XML Against RELAX NG Schema

Xml is considered to be the most popular format for configuration files or web service documents. Whatever the purpose, the xml files must conform to a schema previously agreed upon by the developers. Having a schema ensures that the xml configuration is structurally correct, which is the first step in validating the file. RELAX NG fits right into this picture as a schema language for xml. It provides a set of grammatical rules that our xmls must follow in order to be a valid one. The grammar is itself stated in the form of a xml document. In this post, we will see a small example of its usage.

1. Writing the Schema

In this example, we will define the structure for the a team entity. Let’s save it in teams.xml file.

The RELAX NG schema for the xml above would be

Thats all for the sample xml we have written above. Now lets explain a bit about what happened here. The first element in the RELAX NG schema is an element with name team. That denotes that we are looking for the first element with tag team in the teams.xml file. Inside an element tag, we have to specify the type of content the tag will contain. A team tag contains a name, manager and a players entity. Therefore, we find three elements inside the team tag with names name, manager and players. Note the <text /> tag withing the name or manager entity. It states that the name and manager tags will accept any textual value. The players entity is a composite object, which will contain more than one player names. As such, inside this tag, we have a oneOrMore entity defined within which we specify an element for a single player. Note that for players, we need the names to be an attribute of the player tag, not as a child element. Therefore, we define an attribute tag under the player tag. We have not defined the type of value that attribute can hold as we did for the name and manager entity. This is not necessary as an attribute tag is considered to accept text by default. Once we are done up to this, we are ready with our schema for validating the sample team.xml file. Lets save our schema in rng_schema.xml file.

2. Validation

Now we need a tool to validate team.xml against our schema file rng_schema.xml. We will use xmllint as our validation tool. It really doesn’t matter which we use. In case you are interested in something different, you may try one from the list here. If you do not have xmllint installed, try the following command in Ubuntu.

In case you need a different version number, a little google search on xmllint will reveal itself in appropriate version for you. Now, time the real action! Execute the following in Terminal.

The following output should follow.

That was a very tiny introduction to the more powerful RELAX NG schema validation. There are many more tags that we can use according to the structural requirements for our xml, and more constraints that can be imposed. For a complete tutorial, please follow the official tutorial for RELAX NG.

Thread Synchronization in Python using Lock

Python provides a synchronization mechanism through Lock objects in its threading package. To learn more about locks or thread synchronization in general, have a look at here. In this post, I will demonstrate how we can make synchronize access to a shared piece of data such as a list in Python. Let’s start with the code first.

This demonstrates a very simplified implementation of how we can establish synchronized access to a shared resource which, in this case, is the list. Note that each of the function wraps any read or write access within the pair of acquire() and release() methods of the lock. In a multi-threaded environment, these functions must be made global so that all the threads can access the contents of the list in a synchronized manner with these functions only. The list is still global, so accessing its elements bypassing these functions is definitely possible. But we want everything to be synchronized right? So we should avoid doing that. Another way to keep global access available is to have all these wrapped in class with static members functions for synchronized access to the list.

Display Html in TextView in Android

TextViews in Android are much powerful than they initially seem to be. The best part with this UI element is that it can render basic html tags such as links and even styling attributes, which is similar to what a WebView is usually capable of. Here’s an example.

In one of my apps, I needed to display two lines of text with three words of different colors. The line should re-size and wrap itself automatically, so it was not possible to have separate TextViews with different colors and juxtaposing them side by side. Why? Because android does not provide anything such as a FlowLayout (BlackBerry has it), hence if I had used separate TextViews in the same line, no matter how much they needed to expand, they would always stay in the same line (expanding horizontally) whereas I wanted them to occupy an extra line if necessary.

On the other hand, if had already aligned the text views such that they occupy two rows no matter what, the view won’t stay the same on different sized screens. Thus, no wrapping of text will be visible, but rather a haphazard and ugly flow of text will result. The easiest solution then was to use plain html and harness TextView’s html rendering capability. The whole text would lie in only one TextView element.

Use the following imports in your Activity class.

The function below sets a sample html text on a TextView element.

 

Extract Email Addresses Using Regular Expression in Python

In an earlier post, I have demonstrated how we can extract links or anchor tags from html documents in python. The intent here is similar, but this time, we are going to pull out email addresses (an definitely not send them spam emails, please don’t). Python is awesome with regular expressions, and it is one of the prime reasons why python is so popular for crawling or scrapping jobs.

Regular expression for emails

This is definitely not the definitive version for emails, and there could be some cases that this does not cover. However, this has served me humbly quite a few times to my needs. I am yet to discover an email address that makes this invalid. In case you find one, I would be glad to learn it.

Here’s the full working code for extracting email addresses from an html document.

 

Extract Href Links (Urls) From HTML Using Regular Expression in Python

Regular expressions with python is one of the nicest things you would find in python. In this post, I will demonstrate how we can extract links or anchor elements from a html document. This is particularly useful if you need to pull out the links from a web page.

Here’s the regular expression for extracting whatever is there in an anchor element. As you would probably know, having the whole expression inside parentheses will return whatever matches the expression inside. If confused, experiment with the expression below by removing starting and ending parentheses for a pair.

Regular expression for href links

Here’s the complete code.

Restore Windows Vista or 7 from .wim file

This technique has been applied to restore Windows 7 to the factory settings found in the Recovery partition in a dell inspiron laptop. The partition is usually hidden. To make it visible, right click on My Computer and choose Manage. From the list of drives that appears, right click on the drive labeled Recovery and choose Mount. Note the drive letter assigned to the partition. Also collect a Windows 7 DVD because the recovery process needs to be carried out from the software in the DVD, not from hard-disk.

So, we are wiping away whatever junk is there in C:. Lets say the drive letter assigned to our recovery partition is E. The recovery partition contains some useful tools, one of which is imagex. This is what we will use to extract our .wmi image file to C:. Follow the steps below to restore your windows.

Step 1: Boot from the DVD. In case it does not do that automatically, you may need to change boot device priority settings from BIOS

Step 2: From the setup screen that appears, click on Repair

Step 3: From a list of repair options, choose the line that talks about Command Line

Step 4: A black screen with a blinking cursor appears.You have to change to the recovery drive, then to the tools folder and finally run imagex to restore the image.To achieve this, enter these commands:

Give yourself some time, as this takes about half an hour to complete. When done, restart your computer, and this time, boot from your hard-disk. Enjoy :) !

Inflating and Encapsulating Layout XML into View Object in Android

There are two different ways that layout files in xml can be inflated into the Activity class. The most straightforward method, usually seen in introductory materials demonstrating android Activity, is to use the the xml in setContentView function for the activity. For example, here’s how the HomeActivity will inflate home.xml into itself using setContentView.

Well, now that the xml has been inflated, what’s next? The view elements such as TextView, ImageView, etc. will now need to be queried from the inflated content, and stored in member variables. Consider the following xml for home.

After inflated, these two view elements must be stored as member variables of the Activity class by the findViewById function. Till now, this is trivial.

Consider the case where we may need the Activity to inflate one of many layouts dynamically, or that we need the same view in more than one Activity. Read More

Android Device Detection Error ‘???????????? no permissions’

I have suffered quite a few times in this pain. And then I found these three commands that saved my world! First, connect your device with the USB, and give the following commands.

(In Ubuntu)

Parsing JSON in Android

Web-services and APIs, for instance the Graph API of Facebook, depend heavily on JSON and XML to expose their functionalities. In this post, I will demonstrate how we can parse JSON data from a web-service (simply said, a url) into a  Java object. Android already provides necessary classes to work with JSON, and its as simple as it can be. See the sample usage below.

First, import the following library classes.

Here’s a sample JSON we will parse.

And here’s the code for parsing this JSON.

To work with arrays, you may use the JSONArray class. To retrieve an array into a JSONArray object, use the getJSONArray method on an instance of JSONObject.