Tips & Tweaks when programming Math !

In this post,I am going to tell you some tips and tricks which you should know & you can implement in your codes if required.You dont need to require long codes for short tasks.

To check if a number is power of 2,just calculate log2(n) and if it is an integer,it is a power of 2 else it is not.

Number of digits in a number is ceil[log(n)]. This formula is used to calculate the number of digits in n!.

nCr denotes the number of ways of choosing ‘r’ objects from ‘n’ objects.
nCr=(n-1)C(r) + (n-1)C(r-1)

To find the gcd/hcf of two numbers,you should use Euclid’s algorithm.
Program in C —

gcd(int a,int b)
{
if(b==0) return a;
else gcd(b,a%b);
}

LCM of two numbers= (a*b)/gcd(a,b)

To find the number which occurs odd number of times in a list given that all other numbers appear even number of times-
XOR all the numbers and the result gives you the element which occurs odd number of times.

To check if the nth bit of a number is on/off.AND the number with 2 to the power i.If the result is 0,then it is OFF.

To find the nth Fibonacci number-

fib(n)
{
if(n==0) return 0;
if(n==1) return 1;
return f(n-1)+f(n-2);
}

Given a list of numbers from 1 to n and a number is missing,you have to find the missing number.
Method 1-
Find the sum of all given numbers and subtract it from n*(n+1)/2,you get the unknown number.
Method 2-
XOR all the numbers from 1 to n.Let the result be A1.
XOR all the given numbers.Let the result be A2.
XOR A1 and A2.The result gives the unknown number.

Android development primer: Getting to know Android a little better

Once you have set up the Android SDK and AVD in your system, I would like to take some time and provide you with a little description of the Android Platform so that a read-through of it may give you a basic idea of it’s features and fundamentals.

ANDROID ARCHITECTURE

  •  Android runs on Linux i.e. it is based on Linux Operating System, more specifically Linux 2.6
  • It makes use of a virtual machine named Dalvik Virtual Machine, which in particular is optimized for mobile devices. It is analogous to the Java Virtual Machine with which most Java programmers must already be familiar.
  • It makes use of embedded version of OpenGL named OpenGL ES for graphical purposes.
  • It uses SQLite for storage of data in databases. Web Developers can find analogy in the fact that PHP uses MySQL and ASP.NET uses Microsoft SQL Server.
  • For browsing purposes it uses the open-source WebKit Engine.

ABOUT ANDROID APPLICATIONS

  • As most of you may already know Android applications are written in Java programming language.
  • The Android API helps separate layout from functionalities. The layout is usually written in XML, however many programmers also write it in Java.
  • Each application runs in it’s own Linux process just like different processes run in a computer’s Operating System.
  • All applications must possess components, a manifest file and resources.
  • There are four major components of an Android Application namely Activities, Services, Content Providers, Broadcast Receivers.
  • A manifest file named “AndroidManifest.xml” exactly, is required for each application. This serves the purpose of giving a clear picture to the Android system what your application is all about, what permissions it requires and other related details. I will cover the Android Manifest file and it’s importance in detail in a later post.
  • Resources may consist of xml scripts, colors, shapes, pictures and any other things that your application makes use of.

ACTIVITIES

Any single screen with a user interface is an activity i.e. every screen a user sees is a separate activity. For instance, when you check your text/multimedia messages, the screen that lists the sms/mms conversations, is an activity. When you click on one and enter the conversation screen, that is another activity. Practically, every single application that you come across will have more than one activity. The user can navigate from one activity to another while using the application.

The question now arises, how does the flow of control work in a multi-activity application? Well, it is the responsibility of the Application Programmer to decide how and when will a user be taken from one particular activity to another. Remember that when switching activities, the current activity is paused and the next activity is brought to the front.

Also if you have used an Android device before, you must know that on pressing the “back” key on the device, the user is brought to the screen/activity he/she was on immediately before coming to the current activity. Quite intuitively, it is done using a stack data structure. This stack is known as Back Stack in Android.

SERVICES

Services are programs that perform long-running operations in the background. Since they run in the background, they obviously do not contain a user interface. The most striking feature of a service is that it runs independently of the activity that created it. In simple terms it means that on closing the activity that created a particular service, the service keeps running and does not close with the activity. Another very useful feature of services is that, if allowed, any application can bind to a service and manipulate it.

Now, if you have used an Android device before, you can definitely think of a few services that you have come across. One of them is playing music. When you go to the music player, queue your favorite tracks and then close the music player the music continues to play. This is a very simple day-to-day example of a service.

CONTENT PROVIDERS

Have you ever thought how data can be shared between applications in an Android device? Since each Android Application runs in it’s own process, any and every data to be shared need to be centrally located, so that each application may have access to it. That is exactly what is achieved using Content Providers. Android already contains a number of providers like Contacts, Calls, Media etc. that applications can get access to. An application can also create a provider so that other applications can share it’s data and perform whatever tasks they need to.

Data is stored as a simple table in a Database Model. Data from a Content Provider is accessed with the help of a public URI (Uniform Resource Identifier). A URI uniquely identifies a particular data set.

BROADCAST RECEIVERS

Broadcast Receiver is a component that receives broadcasts from the Android System. A broadcast can be considered to be a system wide announcement of the occurrence of an event. Any and every applications programmed to receive to a particular type of  broadcast, will trigger off as soon as a broadcast occurs.

Applications can also create their own broadcasts such that other applications might receive it and execute a specific set of instructions. Just like services, Broadcast Receivers do not have a user interface. You must have seen that a dialog appears on your device whenever the battery is low. That is a classic example of a broadcast receiver. When the battery is below a certain level, a broadcast is initiated by the Android system. The inbuilt applications receive this broadcast and show a dialog box informing you of the same.

With this, we come to the end of a thorough introduction and we are now ready to plunge ourselves into some real-time Android Application Programming. In my next post I will brief you about the Eclipse IDE and show you how to create your first Android Application

Android development primer: Kicking-Off Android Application Programming.

This is the first post on Android Application Programming and is hence aimed at walking you through setting up the Android Software Development Kit (sdk) and Eclipse IDE (Integrated Development Environment) in your computer.

Contrary to what you might think or how difficult it might seem at the beginning, setting up Android in your system is very easy. You can also find brief descriptions of the steps to setup Android on http://developer.android.com/index.html. So why do you need this post? Because this post compiles all the instructions so it is easier to choose from available options unlike the android developer official website which provides instructions across a number of webpages based on the type of installation you choose to have and might seem a little confusing to absolute beginners.

Visit http://developer.android.com/sdk/index.html.

Now you can do one of the two things below:-

  • If you do not have an IDE already installed in you system or you do but would rather not use it for development purposes, you can download the ADT (Android Developer Tools) Bundle. There are links to download ADT Bundle for various platforms i.e. Windows, Mac OS X and Linux. Choose the one that you require.
  • If you choose to use an already installed IDE for development purposes, you can download SDK tools only. These are again present for different platforms.

To save yourself from any complications and unnecessary hard work, I would suggest the first option. The simple reason behind this is that the downloaded IDE  is already configured with the ADT Plugin and the SDK is ready. Also it is always advisable to use Eclipse IDE for development purposes which you may not have.

SETTING UP ANDROID DEVELOPMENT TOOLS (ADT) BUNDLE :

If you have downloaded the ADT Bundle you need to do a couple of things.

  • Unzip the downloaded file using any compression/decompression software like winzip/winrar to a comfortable location.
  • The extracted folder will contain two sub folders namely eclipse and sdk. Get into the eclipse folder and launch Eclipse.

Remember that you should not try and relocate any files or folders because the path of the sdk is already setup in the Eclipse preferences and moving it will cause unwanted behavior.

SETTING UP ANDROID SDK TOOLS TO WORK WITH AN EXISTING IDE :

If you choose to use an existing IDE and download Android SDK Tools instead of the ADT Bundle, you need to work a little more.

  • Install the SDK Tools. Remember that this is not the entire SDK environment but a tool that is used to download SDK packages for different versions of android. Since you will be required to refer to the SDK directory from within Eclipse in later steps it is advisable you choose a comfortable location and remember it.
  • Do not start Android SDK Manager if you intend to use Eclipse IDE. We have to install the ADT plugin first.
  • Launch Eclipse. Navigate to Help -> Install New Software
  • Click Add on the top right corner. This opens up a dialog box that requires a “Name” and “Location” for the software to be installed. The location can be the absolute address of an archive in your system, but for the time being we will concentrate on how to download this from the Internet.
  • Type ADT Plugin for the name and enter the following URL for the location :- https://dl-ssl.google.com/android/eclipse
  • You can use http instead of https if you have trouble acquiring the plugin.
  • The next dialog shows you the available softwares that you need to download. Check the Developer Tools. Hit Next.
  • All you need to do in further windows is hit Next/OK/Finish. Don’t worry about any warnings saying that the authenticity of the software cannot be established. Anything from Google is bound to be authentic.
  • Restart Eclipse IDE once the installation is done.
  • When Eclipse IDE restarts you will see a “Welcome to Android Development” window. Select Use Existing SDKs. Browse and select the location of the SDK directory which you installed. Hit Next.
  • If for some reason you are facing problem doing this or the the “Welcome to Android Development” window does not pop up you can always set up the path for Android SDK after Eclipse IDE has started up, by navigating to Window -> Preferences -> Android.
  • Now you need to download the platform tools and one of the android platforms. Why? Because each android platform has a different set of SDK and hence you need to have the one for which you will be developing applications.
  • Launch the SDK Manager from the installed directory or from Eclipse by clicking Window -> Android SDK Manager. It shows all the SDK packages available for you to download.
  • As a minimum configuration it is advisable to download the latest tools packages (by checking the Tools folder), the latest version of Android (by checking the first Android folder) and the Android Support Library (by checking Extras -> Android Support Library)
  • The Android version in the above step can practically be any Android version but it is always recommended to download the latest.
  • If you have the time and resources I would advise you to download the API (Application Programming Interface) for all versions of Android.

All Done!! You are ready to create your first Android Application.

Note :- When Eclipse is launched for the first time it asks for a Workspace directory. A workspace is a directory where all your applications and support files will be stored. Browse and choose a comfortable location for your workspace and check/uncheck Use this as the default and do not ask again according to your needs. I would advise checking it so you do not have to browse through at every launch.

Android development primer: Android Virtual Devices

In my last post, I showed you how to set up Android SDK using either ADT Bundle or SDK Tools in your system. So technically you have all the pieces of the puzzle you require, in order to start off creating Android Applications. But, before you get into any real time application programming you need to familiarize yourself with AVDs or Android Virtual Devices.

WHAT ARE ANDROID VIRTUAL DEVICES?

Android Virtual Devices or Emulators as you will come to call them, are virtual devices that install in your system and emulate an Android device. An AVD can emulate most, but not all functionalities of an actual Android device. It is more than sufficient for our development needs.

WHY DO WE NEED ANDROID VIRTUAL DEVICES?

Any sort of development process is a continuous sequence of coding and debugging. If you have any prior knowledge of programming of any kind, you know that when a program executes it goes through an Input-Output sequence. However, here we will not be requiring the traditional form of outputs that usually appear on the terminal window of an IDE. Since we are creating applications for real world devices, we need to know exactly what our code creates and how it behaves on an Android device. Not every developer out there possesses an Android device and even for those who do, it is not practically possible to install the application every time a minor/major change has been made to it. It is during this time that AVDs come to the rescue. With every change you make in your application you can execute it on the emulator to see how it will be reflected in a real-time Android device.

Remember that nothing comes even close to testing your application on a real device because emulators are rather slow. But for relatively unimportant changes emulators do a pretty good job. I recommend trying the application on a real device at regular intervals or when major changes/updates/functionality additions are done.

SETTING UP AN ANDROID VIRTUAL DEVICE

Depending on the version of the SDK/AVD Manager you are using, certain options may or may not be available. Setting up an Android Virtual Device is fairly straight-forward. Follow the steps below:

  • Launch the AVD Manager by clicking on the AVD Manager.exe file in the sdk folder. You can also launch it from within Eclipse, by clicking Window -> Android Virtual Device Manager
  • Click the New button on the top right.
  • Provide an AVD Name of your choice.
  • From the Device drop down menu choose a suitable device.
  • Target is the version of Android you want this device to have. Remember that the drop down menu will display only those versions whose APIs you have installed.
  • CPU/ABI is automatically selected for you.
  • Set up your specifications for Front Camera/Back Camera/RAM/Internal Storage/SD Card. As I said earlier, an AVD can emulate most features of an actual Android device. It includes Internal Storage and External SD Card.
  • You will find a Snapshot check box. With snapshot enabled, whenever an AVD is launched it launches from a snapshot of it’s previous run. Although this will take a relatively longer time while closing, it’s startup time decreases incredibly. I would recommend enabling snapshot.
  • The Skin option helps with creating emulators with various resolutions and screen sizes. You’re gonna want to come here and create a bunch of AVDs when you are testing your application against devices with different screen resolutions.
  • You can check/uncheck Use Host GPU option according to your needs.
  • If all the data that you entered is acceptable, you can now go ahead and create the AVD.

Once created, the AVD should be displayed in the AVD Manager with little icon to the left of it’s name that shows it’s status. The bottom of the AVD Manager shows what these mean. If you face problems with you AVD, you can always delete the AVD and create a new one.

LAUNCHING AN ANDROID VIRTUAL DEVICE

Select the emulator you just created and click “Start”. The start dialog has a few options, all of which are explained below:

  • Skin – This shows the screen resolution of the chosen AVD.
  • Density – This shows the density of the pixels of the AVD screen.
  • Scale display to real size – This option is enabled if the resolution of the AVD is bigger than your screen. You can scale it down and enter the AVD screen size and the Scale below changes automatically.
  • Wipe user data – It emulates the “Reset Factory Settings” function of an Android device. It is generally enabled when after installing a bunch of applications and changing settings to fit your needs, you need to reset them and uninstall all the applications.
  • Launch from snapshot – This option can be enabled only if “snapshot” was enabled during the creation of the AVD. It launches the AVD from a snapshot of it’s previous run.
  • Save to snapshot – This option can be enabled only if “snapshot” was enabled during the creation of the AVD. It saves a snapshot of the current run of the AVD so that it can be launched from the exact same place next time.
  • Click Launch.

Now, it will take some time for the first launch. Subsequent launches will be faster if “snapshot” was enabled.

Note :- If you possess an Android device, it is apparent that the AVD launch is different from your device’s start up. This is because the factory settings of actual Android devices include extra layers of UI (User Interface) giving them fancy start-up animations and sounds. These differ across devices from different companies even if the Android version is same. The AVD however does not possesses any such layers and shows the primitive form of the selected Android version.

Insertion sort in Java

Here is a sample code for inserstion sort.

The basic approach is to keep a pivot up to which the list is sorted.

Insert the value (initially at the pivot) at the right place in the already sorted array to the left of the pivot.

import java.util.*;

public class InsertionSort {

     public static void main(String []args){
         int a[] = {123, 112, 134, 97, 34};
         sort(a);
        System.out.println("sorted :" + Arrays.toString(a));
     }
     
     public static void sort(int[] a) {
         if (a.length <= 1) {
             return;
         }
         int pivotValue;
         int j;
         for (int i = 1; i < a.length; i++) {
             pivotValue = a[i];
             for (j = i-1; j >= 0; j--) {
                 if (a[j] > pivotValue) {
                     a[j + 1] = a[j];
                 } else {
                     break;
                 }
             }
             a[j+1] = pivotValue;
             System.out.println("pivot :" + i + " : " + Arrays.toString(a));
         }
     }
}

A Random Representation Democracy using UID

Now that the corruption in the largest democracy of the world – India has reached to more than a THOUSAND BILLION US DOLLARS (reference here), its time we rethought about the effectiveness of general elections, in selecting the right people to rule us.  An alternative will be a “Random Representation” democracy, which in simple terms will work like this –

  1. Citizens educated to a certain level may voluntarily take up a diploma course in Public Policy making, standardized and made available (in distance mode) by the Union government.
  2. Those who successfully complete the course, can register themselves as willing to dedicate 3 years, as people’s representative, in a Government web-portal – prior to the elections.
  3. A central computer then selects in a random fashion, the required number of representatives to Parliament/Assemblies from among these volunteers.
  4. The selected representatives choose the PM and cabinet from among themselves by volunteering/voting.
  5. The knowledge about new/ongoing policies/laws are quickly disseminated to the new representatives using well maintained documentation portals.
  6. New representatives are chosen every three years, after which older ones return back to their previous professions. A previous PM may be retained if the new representatives decide so.
  7. This new system doesn’t have the concept of political parties (which depend heavily on private funding for survival); and thus has much lesser tendency to contract corruption.

Solar Hydel Hybrid Power Stations

We hear a lot of fuzz about solar-wind hybrid power plants. Its surprising why there’s no major projects which utilize solar energy to multiply the output from an existing hydro electric power station.

A solar-hydel hybrid plant would work, in a very basic sense, as below –

  1. Photo voltaic panels are deployed in arrays supported on floating barges in the reservoir. (OR on barren land if available in proximity)
  2. Additional penstock-turbine-generator circuits are built for the EXTRA power to be generated.
  3. A sump collects the water used by the NEW water circuits described in step 2.
  4. Solar energy created by the PV arrays are used by several DC motors to pump the water from sump back to the reservoir.

(Detailed design will involve output power, back-up duration, fluid flow losses etc as design parameters.)

This method has these advantages –

  1. Removes the need of batteries which are expensive to procure and maintain too. Instead here solar energy is stored as potential energy of water.
  2. Removes the  need for expensive power electronics for DC to AC conversion.
  3. Reduces evaporation losses of water from reservoir considerably.
  4. Reduces the need for new Dams for increasing power generation.

 

BoshServlet Updated

BoshServlet is updated at Google code (http://code.google.com/p/bosh-servlet/) with the following changes –

  1. Intermittent race condition and lock ups while serving requests fixed.
  2. Changed session initialization flow to fix an error while using STARTTLS.
  3. Automated response for server pings.
  4. Added an example HTML page on using the servlet.

Thank you for your patience with BoshServlet so far. Please use the latest version and let me know of any fix/feature you find as needed.

– Kj

Remove virus “myFolder.exe”

I could fix the usb-disks infected with the virus which replaces your folders with a file folderName.exe, by following these steps (on Windows) –

  1. Run the command attrib e:\*.* /d /s -h -r -s in the command prompt – this will display all the hidden files and folders.
  2. Delete the dll file that appears in the disk after the above command is run, and also the folders converted to .exe.

The disk should now be usable again.

javax.net.ssl.SSLHandshakeException: unable to find valid certification path to requested target

Error: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Cause: The certificate not in trusted list of JVM.

Solution: Add the certificate to trusted list by compiling and running the following Java class from the download link below (modified from the one posted at http://code.naishe.in/2011/07/looks-like-article-no-more-unable-to.html). Note: The certificate file(path) may have to be edited and set to the file used by your JVM to look up certificates.

Download InstallCert.java