Tuesday, January 8, 2019

Google Colab setup for fast.ai Deep learning course

For past few days I have been trying to setup Google Colab to run fast.ai lesson files.
Found multiple post on the same but  I was getting some or other error.

So here is the code which worked for me, I know there is latest version of fast.ai, but I wasn't able to make it work with that. 
Here the code is based on fastai version 0.7.


I am unable to mention the author of the original post, as I was trying multiple combination at the time. If you are able to find, please comment, I will update my post with proper citation.


PS: sometimes Google colab throws random error, so I will suggest to reset all runtime and then run again

Thursday, February 15, 2018

Rename Domain Computer using Powershell Script

As name suggests, powershell is very powerful way to automate pretty much all the things in windows.

If you want to rename your computer using power shell script where your computer is part of domain. Here is the the simple set of commands to do it :

1. $user = 'DOMAIN-NAME\USER-NAME'
2. $password = 'PASSWORD'|ConvertTo-SecureString -AsPlainText -force
3. $cred = New-Object System.Management.Automation.PSCredential $user,$password
4. Rename-Computer -ComputerName CURRENT-COMPUTER-NAME -NewName NEW_COMPUTER-NAME -domaincredential $cred

After that you need to restart the computer for changes to take effect.

Hope it helps !!

Saturday, February 6, 2016

C++ Graph class Implementation : Without any STL package

Hi All,

Please find the implementation for Graph class in C++ without using any STL reference.
Let me know if you find any issues with it.

Header file.


Cpp file:



Happy Coding !!

Wednesday, November 18, 2015

Parse.com Android : Common Issues faced

If you have just started in the world of BASS service, you might have chosen Parse.com.
Although it has good tutorial for explaining things, still I think community support is not very good.
I also had hard time to try basic things. So let me share a complete tutorial for extracting some data from Parse.com. It will be more towards covering the known issues.

Step 1: Uploading Data
In Tutorial provided by Parse, they talked how you can create a ParseObject, and upload the data by putting.You can follow the Guide provided by Parse to do that. I instead use Import Data option in Data Browser. So create a Json file and upload it there. If you are facing any issue with uploading, like it should be in that particular format, I will suggest to download any existing Table such as User, and open the JSON file. Similar way you can do it. Remember the first name should be "results" only, otherwise it wont let you upload.

Step 2: Creating a subclass of ParseObject
Although you can use normal ParseObject class do that, I will suggest you to use your own customized subclass of ParseObject.
a) Use @ParseClassName("YOUR_CLASS_NAME")  annotation.
b) Keep the file name, class name and Table Name same.
c) There should be default constructor of your customized sub-class.
d) Create set/get method for your fields in the table.

Step3: Registering the subclass
In your Application class's onCreate() method: add this line before calling Parse.initialize() :
ParseObject.registerSubclass(YOUR_CLASS_NAME.class);

Step4: Query using the subclass
 ParseQuery query = Alert.getQuery();
query.findInBackground(); //see the last link to get the full code.

Step5: Manifest changes
a) Please make sure you have defined the name field in tag in AndroidManifest.xml. Better use the complete path.
b) Add android.permission.INTERNET and android.permission.ACCESS_NETWORK_STATE permission.

I think this covers pretty much all the points.  Let me know if you face any issues with it. Sorry for lousy writing.
Here is link for all code.



Wednesday, November 4, 2015

Unable to add Google Play Service or Appcompat library project

It has been very long since I wrote any post about Android. So I will try now to continue the writing.

If you have left Android for some time and now starting over again. You might observe that Google is no longer providing ADT (Android Development Tool) bundle. Now the new tool is Android Studio. Although it has all the related tools at one place, but it is slow and little bit hard to start with.

So here is the guide for using old ADT.
Download the last ADT bundle. I am using adt-bundle-windows-x86_64-20140702.
You will find that it doesnt have Google Play Services project. To install it:
1. Go to Sdk Manager. Its there in the same zip file of adt bundle.
2. Refresh the list, in last checkbox named Extras: you can see one sub-item Google Play Services.
3. Check it and install it.
4. You can see that now a folder has been created in the \sdk\extras\google\google_play_services.
5. Now go to eclipse, Import Android project and give the location to this google_play_services folder. Don't forget to Check the Copy Projects into workspace option.
6. That's it.

Now if you want to include this project in your App's Project. Just go to project settings. In Android Option, there is a option to Add, Click on it, it will be showing your play-service/appcompat project.
choose whichever is relevant to you.

The same process could be followed for Appcompat Project.

If you face any other issue, comment here or mail me @ rahul.lnmiit@gmail.com

Friday, September 26, 2014

Device Tree in Linux

In the series of short notes on kernel concepts. Here is my new post on Device Tree. Device Tree has become a important part of linux kernel now. So lets start with it in my usual way of writing :

What is Device Tree?
- Device Tree is a tree like structure, which is used to store hardware information.
- It is a description of machine's hardware that is readable by the OS, so that kernel code could separated from machine specific information.
- So using Device tree, you can get any information from it at any point of time by parsing it.

What is the benefit of Device Tree?
- It ensures a single board file for a chipset, rest of the device specific information can be moved to device tree.
- Platform devices are created at run-time by the kernel by parsing the device tree nodes.
- we can add the devices which are not present right now, but in future they will, so no need to write the code again at later stage.
- So overall it steps toward the single kernel binary for all variation of chipset, which can be clubbed with specific device tree blob to  create different binaries for different variation. This will reduce the time to support new platform for the chipset.

How to enable DT support ?
- First thing is create an entry in board file, between DT_MACHINE_START & DT_MACHINE_END. you need to look into a board file to understand it better. Remember you must have dt_compat  field with the appropriate dt_mach structure, which will be containing the chipset details.
- Add your device tree source(dts) file. It have the compatible , model and id field, so it should be filled with appropriate variable. [ check /arch/arm/boot/dts/  folder for .dts file]
- To enable building this tree, there are 2 ways :
a) Enable through menuconfig -> boot options -> flattened device tree
or
b) define 'select USE_OF ' in Kconfig entry in arch/arm/Kconfig

Structure of Device Tree:
 Device tree describes a machine's hardware with a combination of

1) Nodes: It represents the device or bus. Contains properties and child nodes. It is defined as node_name@unit_address.

2) Properties: provides information about a device. It consists of a name and a value. Properties can further be categorized as Standard or Non-Standard.

Standard Properties:
a) compatible : it is used to distinguish between different nodes. Recommended format for compatible property is "manufacturer, model". OS can use it for machine/device driver selection.

b) phandle : specifies an unique numerical identifier for a node with the device tree. Used by other nodes that need to refer to the node associated with the property.

c) status : Indicate the operational status of a device. Values for this could be "okay", "disabled", "fail".

d) #address-cells,#size-cells : May be used in any device node that has children in the device tree hierarchy. Describes how the child nodes should be addressed. #address-cells tells no of cells to encode the address field in child's reg property. #size-cells tells no of cells to encode the size field in child's reg property.

e)reg : Arbitrary number of pairs of address and size. It describes the address and the size od the device's resources. It tells no of cells to specify address and size are specified by the #address-cells and #size-cells properties in the parent of the device node.


These are the main things. If you want more details, I will suggest you to refer Documentation/devicetree in linux kernel.

Thursday, September 25, 2014

Short Notes on System Call

This post covers pretty much all main points which you need to know about System Call in Linux. These points are my notes which I covered through many blogs/sites for my study. So lets start it :

What is System Call ?
- As Linux doesn't allow user process to directly modify anything in kernel space. It has provided a way to achieve it, which is known as System Call. So basically system call provide a layer between the kernel and user space process. Using this, kernel performs user space process's task inside the kernel space. This way kernel have control on, what a user process can do.

Why you need a System Call ?
- As system call is the only legal entry point to kernel, sometimes you may need some information, which can only be provided with kernel space credentials, so Kernel developers give you some system call. Although user space doesn't use it directly(in general), they uses some API for the same. 
So the flow will go like 

read() ----> read() wrapper ------> system_call() ------> sys_read()

Here first two thing is in user space and last two is in kernel space.

How do they work ?
- Application program calls the API.
- A system library routine is called first.
- It transforms the call to the system standard and traps to the kernel.
- Control is taken by the kernel running in the system mode.
- According to the code, the call dispatcher invokes the responsible handler.
- Interrupt is disable during this handler.
- After call is finished, mode is changed from system mode to user mode and calling process execution resumes.

How it works at low level ?
-  So whenever you call any system call, it is translated to SWI .
- Whenever processor sees SWI, it interrupts whatever is running currently( except IRQ/FIQ), changes the mode to supervisor mode(SVC).
- Whatever parameters were there in the system call, are passed using registers. 
- Also PC is stored in LR of svc mode and CPSR is saved in SPSR_svc, so that we can recover the previous state while returning from SWI.
- On execution of SWI, processor looks for SWI_handler address, which was already defined in the vector table. 
- From this SWI handler, processor jumps to the specific system call handler. Here we use the system call number to get the corresponding handler.
- Once the system call handler finishes its execution. Processor change the mode to user, and recover PC from LR.

Type of System Call :
- Process control and IPC : fork(), exec(), pipe()
- Memory Management : malloc(), free()
- File and File System management : open(), read(), write()
- Device Management : ioctl()
- Others : kill(), signal()

Implementation of System Call :
For this you can refer my previous blog on creating system call.

Friday, September 19, 2014

Add a Custom System Call in Linux Kernel

Here I will be covering a small tutorial on creating new system call in Linux Kernel. I am using Latest Kernel version 3.16 ( It is latest at the time of blog written).
I added my call for 32 bit system only. 

So the whole process is divided in 5 step.

Step 1:  Open arch/x86/syscalls/syscall_32.tbl . Here go to the last line in the file. It will be containing a number in first column, this number tells that it is the last number used by system for system call. So lets say the number is 356, so your new system call will have number 357. Now just duplicate the last line, and change the number and name of the sys call. Let say it is "hello". So the whole line will look like :

357    i386    hello   sys_hello

Step 2: Add the syntax of syscall in  include/linux/syscalls.h. Suppose this sys call takes 2 int parameters. So for syscall "hello", your new line should be like this :

asmlinkage long sys_hello(int a, int b);

Step 3:  Now add the entry in /kernel/sys_ni.c. So entry will be like :

cond_syscall(sys_hello);

Step 4: Add the function definition for sys call. Open kernel/sys.c. you can add it at different place too.  Now as our sys call is having two parameters, so the function will look like this :

SYSCALL_DEFINE2(hello /*name of syscall */, int /*type of first parameter */,  a /*name of first parameter*/, int /*type of second parameter */,  a /*name of second parameter*/)
{
int error = -EINVAL;
// code for whatever you want to do in syscall 

return 0;
}

That's it, your system call is created, but to reflect it in your kernel, you have to build it. you can refer my blog 


Step 5:  Test the system call. create a userspace program. Don't forget to add sys/syscall.h header. 

Now to call our hello syscall. 

int call = syscall(357, 1,2); // here 357 is our system call number, 1 is val for a and 2 for b.


That will be all from my side. I hope it help you to understand syscall. 

Wednesday, July 30, 2014

Insertion Sort : In non increasing format

Here is the pseudo code for arranging number in non increasing format using Insertion sort. This is one of the exercise of Book Introduction to Algorithms by CLRS.

//N is array's length
for j = N-1 to 1
   key = A[j];
   i = j + 1;
 
   while i<=N && A[i] > key
            A[i-1] = A[i];
            i = i +1;
   A[i-1] = key;

Input : 5 4 3 2 6
Output : 5 4 3 6 2
              5 4 6 3 2
              5 6 4 3 2
              6 5 4 3 2 [Final]

Thursday, July 24, 2014

Short Notes on Memory in Linux

Most of part of this blog will be containing notes from Robert Love's Linux Kernel Development. But I will try to add the general questions also in this blog.


The most basic unit of memory is page. Kernel use page structure to keep track of all the pages in the system. Through this kernel can be informed that whether page is used or free, if used then who is using it etc.

Zone : Because of hardware limitation the kernel can't treat all pages identical. So it is divided in 3 parts mostly : ZONE_DMA(upto 16 MB), ZONE_NORMAL(16 to 896 MB) and ZONE_HIGHMEM(896 & above).

Main limitation to divide pages in Zone are:
1. Some hardware devices can perform DMA to only certain memory address.
2. Some memory can't be permanently mapped into kernel address space.(eg: HIGMEM)

Page allocation interface :

1. struct page * alloc_pages(gfp_t gfp_mask, unsigned int order) : This returns 2 to the power order pages contiguous physical page. As this function returns a page pointer, to get the logical address of it, we use page_address(struct page * page) method.
2. unsigned long  __get_free_pages(gft_t gfp_mask, unsigned int order) : it returns the logical address.
3. unsigned long get_zeroed_pages(gfp_mask) : it is useful for page allocated for user space, as it zeroes the content of allocated page, so that sensitive data doesn't pass to user space.
4. void * kmalloc(size_t size, gfp_t flags): this function returns a pointer to a region of memory that is atleast size bytes in length. This memory is physically contiguous.
5. vamlloc() : it allocates virtually contiguous memory. It does this by allocating potentially non contiguous chunks of physical memory and fixing the page table to map the memory into a contiguous chunk of virtual memory.

Deallocation interface :

1. __free_pages(struct page *page, unsigned int order) : Always ensure you are deallocating only those page which you allocate.
2. kfree(const void *ptr)
3. vfree(const void *ptr)

Introduction to Slab Layer:
Allocation and deallocation memory is the most common operation in Kernel. Because of it, there is good chance of de-fragmentation. Which is complete waste of resources, as you are having the free memory but you cant use it as it is not contiguous.
To resolve this issue, Linux kernel came up with the slab layer concept. So most frequently used data structure is allocated through cache. At the start-up we create the caches for all major data structure. Cache is further divided in slab. And slab contains a page. Apart from that Cache also maintain 3 list, empty list, full list and partial list.
So whenever allocation request comes, Cache check whether any empty page is there on any of the list. It allocates there and then return the page. Once that structure is released, the corresponding page is also released and return back to the free list.

This was the basics, now lets try with questions which I faced, these questions may not in order of relevance:

1. What is the return address of kmalloc() ? Physical or Virtual?
Ans : it always return the virtual address, and the allocated memory region will be physically as well as virtually contiguous.

2. How memory is allocated for program ?
Ans : When ever program compilation is done. At the time of loading, First program is loaded in memory, then mapped it to the Virtual memory. So it will be having page table with no association with physical memory. At the time of use, means when you want some memory for operation, it goes to page table, there MMU find that no physical memory is allocated, so it do the page_fault(). Then the physical memory is allocated and corresponding entry is created in the page table.

3. logical address and virtual address ?
Ans : Most important thing is logical address comes in picture if you have segmentation unit in your system. If it is not there then there is no logical address. So the address translation happens like this :
           logical address => [segmentation unit] => virtual address => [paging unit] => physical address

4. Why physically contiguous memory region is more efficient than virtually contiguous memory?
Ans : As memory allocated is physically contiguous can use a concept called huge pages. With this higher page size can be used, so correspondingly there will be lesser page entries in the table.Huge pages can improve performance through reduced page faults (a single fault brings in a large chunk of memory at once) and by reducing the cost of virtual to physical address translation (fewer levels of page tables must be traversed to get to the physical address). 

5. How Shared memory is used?
Ans : For shared memory we use IPC like shmem. So whenever two process wants to share some memory. They use shmem IPC to get an id for the associated memory, further this shared memory is mapped to both processes's address space. So for those process it looks like local memory. Internally the vm_area_struct (virtual memory area) uses VM_SHARED flag to show this memory area as shared memory.
           Also when we create a child process with CLONE_VM flag, at the time of creation it skips the allocate_mm() call (which is actually responsible for memory allocation) and assign it's mm structure to its parent's mm structure. 

6. Where does the memory is allocated for kernel stack ?
Ans : Kernel stack is allocated in the kernel space, remember not is user space memory. But it is mapped to that Process's address space, not only that but to all other process's address space. As apart from kernel no body will be using this, so it no process is able to recognize it and they don't have permission to access it.

7. Can a process use whole 4 GB address ?
Ans : No, it can't. Remember, memory is divided in memory area. So a process can only access only those memory areas for which it has permission. Even to add or remove memory area, it has to request kernel.




Sunday, June 29, 2014

How to Submit android app to Amazon app store

If you are new to android development and specifically planning to launch your app to Amazon app store. Then you must be feeling a little bit left behind, because there you won't find much over net apart from Amazon's own material. 

Although it is mentioned on their site clearly, I thought of repeating it, because it will just some one else to find the right thing :

So if you want to add the ad api so here is the way : 

1.  Download sdk from here.
2.  Now add the Jar in Eclipse using Install New Software. After that add this link as name Amazon.
3.  Now Import your android project, remove all the google play service api from it, and add Amazon api. To do that right click on your project, and click on Properties. And then in that click on Amazon Mobile app SDK. 
4. There you can select whatever you want to use, Mobile Ads, ADM, In-App purchasing etc.
5. Now it comes to the coding part. Wherever you want to use it, include the following code :

AdRegistration.setAppKey("37de83fd21234ed4811e241507876542F"); // put your Application id
    
   this.adView = (AdLayout) findViewById(R.id.adview);
   
   AdTargetingOptions adOptions = new AdTargetingOptions().enableGeoLocation(true);
   // Optional: Set ad targeting options here.
   this.adView.loadAd(adOptions); // Retrieves an ad on background thread

And you have to create corresponding entry in xml :

 
    android:id="@+id/adview"
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"/>

6. And you are good to go. 
7. Use Test your app option on Amazon before uploading your apk to Amazon app store.

I hope this blog help you to publish your first App on Amazon app store.

Thursday, June 26, 2014

Android : How to Check whether device is rooted or not ?

Many time user go for rooting their phone to break the constraints put by operator and OEMs. 
So Rooting your phone opens a door of new features which could be really useful. 

To root your phone, I will suggest you to go to Xda developers. They have wide range of tutorial specifically for each devices. So once you have followed their steps, and just wanted to confirm whether your device has been rooted, Here is a simple app called Root Verifier Pro Launched by Bitdroid Devz

I will suggest you to try it, it worked fine for me. 

Thursday, June 19, 2014

HWComposer : Android Surface Composition Logic Module

After my last post of SurfaceFlinger few people asked me to write on HWcomposer, which is tightly associated with SurfaceFlinger. 
I here would like to mention that Google's Graphics Architecture link helped me a lot.  So I will be mentioning many of those points here again.
So here we go 

HWComposer(HWC)'s primary purpose is to determing the most efficient way to composite buffers with the available hardware.
You can easily recognize the value of HWC, when you consider "overlay planes". The purpose of overlay planes is to composite the multiple buffers together, but in the display hardware(MDP in case of QCom) rather than the GPU. You can refer this link for diagram.

The mentioned link describes it very well, it goes like :
In General you have three buffers for Android screen at a time, one for Status bar, second for Navigation bar and third for Application. So instead of compositing all three buffers, SurfaceFlinger pass these buffers to Display Hardware to process. So HWC works like this :

  • SurfaceFlinger provides the HWC with a full list of layers, and asks, "how do you want to handle this?"
  • The HWC responds by marking each layer as "overlay" or "GLES composition."
  • SurfaceFlinger takes care of any GLES composition, passing the output buffer to HWC, and lets HWC handle the rest.

  • Now as mentioned in 3rd point, Surfaceflinger passes the output buffer to HWC. This is quite useful when there is no update in the screen. In this scenario, HWC can choose GLES composition for those buffer. Because of this, When Surfaceflinger comes up with the same set of buffers(as no screen is changed), HWC can just continue to show the previously composite buffer.

    Code Flow:

    Linking of hwc module :

    SurfaceFlinger::init() -> HWComposer() -> loadHWCModule() -> hwc_open_1 -> (module->methods-->open) ->open() [defined in hwc.cpp]

     Now whenever Surfaceflinger have new buffers to update, it calls setupHWComposer(). This function is used to get all layers, using 
    currentLayers = hw->getVisibleLayersSortedByZ();

    after setting the data, it calls prepare()  which in turns call prepare()[hwc.cpp][I will definde the details of this function later].

    After all processing and composition is done, we call postFrameBuffer(), it calls commit() and finally hwc::set(). Which goes like this :

    hwc::set() -> hwc_set_primary() -> (mFbUpdate->draw())* -> ov.queueBuffer() -> GenericPipe::queueBuffer() -> Data:queueBuffer()(OverlayCtrlData.h) -> MdpData:play()(overlaymdp.h) -> play()(MdpWrapper.h) ->ioctl(fd,MSMFB_OVERLAY_PLAY,offset)

    this fd and offset it is getting from 
    fbLayer = &list->hwLayers[last];
    hnd = (private_handle_t *) fbLayer->handle;


    after (mFbUpdate->draw()) calls finishes, flow goes like 
    (Overlay->displayCommit()) -> displayCommit()(Overlay.cpp) -> displayCommit()(MdpWrapper.h) -> ioctl(fd, MSMFB_OVERLAY_COMMIT, info)

    After this lcd driver starts doing the final task.

    Now lets understand what prepare() function do. 

    prepare is called for each frame before composition and is used by SurfaceFlinger to determine what composition steps the HWC can handle. 
    The HWC responds by setting the compositionType field in each layer to either HWC_FRAMEBUFFER or HWC_OVERLAY.
    In case of HWC_FRAMEBUFFER, composition is handled by SurfaceFlinger using OpenGL ES, in later case HWC will have to handle the layer's composition.

    Now other important function in hwc.cpp is set(). When this call returns the caller assumes that the display will be updated in the near future with the content of their work list.



    Wednesday, June 11, 2014

    difference between Kernel Thread and User thread

    1. Kernel threads run only in Kernel Mode, while regular processes run alternatively in Kernel Mode and in User Mode.

    2. Because kernel threads run only in Kernel Mode, they use only linear addresses greater than PAGE_OFFSET. Regular processes, on the other hand, use all four gigabytes of linear addresses, in either User Mode or Kernel Mode.

    Process 0 :
    This is the ancestor of all processes, also known as the idle process. it is a kernel thread created from scratch during the intialization phase of linux. This ancestor proces uses the following statically allocated data structures.

    1. A process descriptor stored in the init_task variable, initialized by the INIT_TASK macro.
    2. A thread_info descriptor and a Kernel Mode stack stored in the init_thread_union variable and initialized by the INIT_THREAD_INFO macro.
    3. The following tables, which is the process descriptor points to:

    - init_mm ( initialized by INIT_MM)
    - init_fs (initlialized by INIT_FS)
    - init_files (initlialized by INIT_FILES)
    - init_signals(initialized by INIT_SIGNALS)
    - init_sighand(initialized by INIT_SIGHAND)

    4. The master kernel Page Global Directory stored in swapper_pg_dir.

    The start_kernel() function intializes all the data structures needed by the kernel enables interrupts, and creates another kernel thread, named process 1 (known as init process).

    After creating init process, Process 0 is selected by scheduler only when there are no other processes in the TASK_RUNNING state.

    For multiprocessor system, there is a process 0 for each CPU.

    Monday, June 2, 2014

    Check if a character link list is palindrome or not.

    Hi Folks,

    Here is my implementation for checking whether link list is palindrome or not.

    #include <iostream>
    #include <stack>
    #include <cstdlib>

    struct node
    {
    int data;
    struct node *next;
    };

    using namespace std;

    struct node *head;

    void addNode(int data)
    {
    struct node *temp;
    temp = (struct node *) malloc(sizeof(struct node));
    temp -> next = NULL;
    temp->data = data;

    if(head == NULL)
    head = temp;
    else
    {
    struct node *head1;
    head1 = head;
    while(head1 ->next != NULL)
    {
    head1 = head1->next;
    }
    head1->next = temp;
    }
    }


    int main()
    {
    int N;
    cin >> N;

    for(int i=0;i<N;i++)
    {
    int temp;
    cin >> temp;
    addNode(temp);
    }

    struct node *slow, *fast;
    stack<int> stk;

    slow = head;
    fast = head;

    while(fast->next != NULL)
    {
    stk.push(slow->data);
    slow = slow->next;
    fast = fast->next;
    if(fast->next != NULL)
    fast = fast->next;
    }

    if(N %2 != 0)
    slow = slow->next;
    while(!stk.empty())
    {

    // cout << (stk.top()) <<" " << (slow->data) <<endl;
    if(stk.top() == slow->data)
    {
    slow = slow->next;
    stk.pop();
    }
    else
    {
    cout <<"No Pallindrome" <<endl;
    return false;
    }
    }

    cout <<"Pallindrome" <<endl;//return true;
    }

    Sunday, June 1, 2014

    Generate all combination of elements of an array : Power Set Algorithm

    #include
    #include
    #define MAX 100010
    using namespace std;

    int arr[MAX];

    void powerset(int arr[], vector v, int start, int end)
    {
    if(start > end)
    return;
    v.push_back(arr[start]);
    vector::iterator i;
    for(i = v.begin(); i
    {
    cout << *i;
    }
    cout << "\n";

    powerset(arr,v,start+1,end);
    v.pop_back();
    powerset(arr,v,start+1,end);

    }

    int main()
    {
    int T,N;
    cin >> T;
    while(T-- > 0)
    {
    cin >> N;

    for(int i=0;i
    cin >> arr[i];
    vector v;
    powerset(arr,v,0,N-1);
    }
    return 0;
    }

    Wednesday, May 28, 2014

    Notes on Insertion Sort

    Insertion Sort is a way of sorting elements. While using insertion sort, we traverse from right to left element.

    Steps :

    1. Assume 0th element is already sorted.
    2. Starting i from first element till last :
                  -  In a loop(j ), check if the previous element is greater than the comparing element( for example for first time, we will be comparing 1st element to 0th element.)
                  - If previous element is greater than comparing element, we will replace the j+1th element with j.[Remember before doing this keep array[i] stored in some variable, as it will be compared to all elements].
                  - when loops finished, just replace the last index element with array[i] stored value.


    Code :

    for(i =1; i{
            int val = arr[i];
            int j = i-1;

            while( j >=0 && A[j] > val)
             {
                  A[j+1] = A[j];
                  j--;
             }
         
             A[j] = val;
    }

    Wednesday, April 23, 2014

    kmalloc() V/S other page allocation methods

    If you are developing anthing in Kernel, I hope you have used kmalloc() many times till now. But if you see there are other function also to allocate physical memory. Those are :

    __get_free_page(unsigned int gfp_mask)
    __get_free_pages(unsinged int gfp_mask, int order)
    get_zeroed_page(unsigned int gfp_mask)

    So when we use kmalloc() and when we use the above functions ?
    Answer lies in your requirement, if you need very small memory to allocate, go for kmalloc, because there you define the minimum no of bytes(let say n) you need to allocate. But remember it just ensure that atleast n bytes will be allocated, but in reality, it allocates more than it, sometimes even double of the size. So in short there is no fine granuality with kmalloc().

    while get_free_page family is used when you want to allocate memory in terms of pages, as for kernel, page is the smallest memory unit. So you will pass the order x, and it will return you 2 power x pages. So here Kernel ensures that only requested no of pages will be allocated. So there will not be any memory waste.

    And if you want to allocate memory from high memory, then there is a seperate function : [Although these function can be used for normal zones too]

    alloc_pages(unsinged int gfp_mask, unsigned int order)
    alloc_pages(unsinged int gfp_mask)


    Sunday, April 20, 2014

    Short Note on Android App Signing

    I know you will find many articles for mentioned title. But I thought of summarizing it , So Here are the steps :

    1. You need Keytool and Jarsigner. If you have java installed in your system, then you have these utilities.

    2. Now generate a private key for your app, So here is the command :
     keytool -genkey -v -keystore my-release-key.keystore -alias ANY_NAME -keyalg RSA -keysize 2048 -validity 10000

    This will ask you few basic question, answer those. finally it will ask the password, give it, this will encrypt your keystore file.

    3. I hope as you are an android developer, you must be having Eclipse with you. So Go to File -> export -> Android -> Export Android Application.

    4. Select the project from which you want to export the application.

    5.  Select keystore, remember in step 2 you created my-release-key.keystore, give path to this file. And entered the password you have entered at the time of creation.

    6. Next it will ask key alias selection, So whatever ANY_NAME you given in step2, choose that and again give the password.

    7. Finally it will ask you the location, where the signed application will be exported. So just give the path and click finish.

    And you are done.

    Monday, April 14, 2014

    Create a structure which can contain any type of data

    Generally whenever we create a structure, we define that what kind of data it will be storing. But think it this way, what if you don't know what kind of data structure it can use in future, to avoid that situation. Here is the way :

    #include
    #include
    struct node
    {
    void *ptr;
    struct node *link;
    };
    int main(void) {
    // your code goes here
    struct node *head,*temp;
    float var = 10.5f;
    head = (struct node *)malloc(sizeof(struct node));
    *(int *)(head->ptr) =10;
    head->link = NULL;

    temp = (struct node *)malloc(sizeof(struct node));
    *(float *)(temp->ptr) = var;
    temp->link = NULL;

    head->link = temp;

    printf("Value = %d",*(int *)(head->ptr));
    printf("Value = %f",*(float *)(temp->ptr));
    return 0;
    }

    Hope it helps you in your next interview :)