Friday, July 17, 2009

virtual destructor

Ask any programmer, he'll immediately reply saying "A destructor is a member function of a class, which gets called when the object goes out of scope". This means all clean ups and final steps of class destruction are to be done in destructor. A virtual function is something which helps a derived class in overriding the implementation of a functionality of a base class.
The order of execution of destructor in an inherited class during a clean up is like this.
1. Derived class destructor
2. Base class destructor

A difference between a destructor (of course also the constructor) and other member functions is that, if a regular member function has a body at the derived class, only the version at Derived class gets executed. Whereas in case of destructors, both derived as well as base class versions get executed.

Now turning our attention to why a destructor has to be virtual, the reason is that we, programmers are very smart. We'll do days and nights of work to inherit and extend the functionality of an existing class which is being used, and say that we don't want to change the implementation/interface just for the sake of a new entrant. Let me explain this with an example.


--------------------------------------------------------------------------------
#include
class Base
{
public:
Base(){ cout<<"Constructor: Base"< ~Base(){ cout<<"Destructor : Base"<};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"< ~Derived(){ cout<<"Destructor : Derived"<> };
void main()
{
Base *Var = new Derived();
delete Var;
}

Try executing this code, you'll see the difference. To our observation, the constructors are getting called in the proper order. But to the dread of a programmer of a large project, the destructor of the derived class was not called at all.

This is where the virtual mechanism comes into our rescue. By making the Base class Destructor virtual, both the destructors will be called in order. The following is the corrected sample.

#include
class Base
{
public:
Base(){ cout<<"Constructor: Base"< virtual ~Base(){ cout<<"Destructor : Base"<};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"< ~Derived(){ cout<<"Destructor : Derived"<};
void main()
{
Base *Var = new Derived();
delete Var;
}


Note:
There is one more point to be noted regarding virtual destructor. We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body (at least) for the destructor.

Sunday, July 12, 2009

Intel interview question II

1. Write a function that will return the bit mirror image of inputData. (i.e. 11110010b => 01001111b)
unsigned short mirror (unsigned short inputData)
{

int numberByte = sizeof(unsigned short);//decide how many bytes in this processor.
int *temp_buffer,j,temp;
unsigned short mirrorOutput=0;
int numberBits = numberByte * 8; // how many bits for inputData
// allocate the memory
temp_buffer = (int*)malloc(sizeof(int)*numberBits);

// read bits information into temp_buffer.
for (j =0;j temp_buffer[j]= (inputData & (1<
// output the bits informaiton for inputData.
printf("output the bits informaiton for inputData\n");
for (j =0;j printf("%d ",temp_buffer[j]);


// inverse the buffer.
for (j=0;j temp = temp_buffer[j];
temp_buffer[j]= temp_buffer[numberBits-1-j];
temp_buffer[numberBits-1-j] = temp;
}
// output the mirror bits information for outputData
printf("\n\n output the bits informaiton for outputData\n");
for (j =0;j printf("%d ",temp_buffer[j]);

// output the integral number
for (j=0;j mirrorOutput = mirrorOutput + temp_buffer[j]*(1<
return mirrorOutput;
}




2. What is the output from the following code? (Assume 32-bit integers)

int x[] = {1,2,3,4,5};
int *p = x;
char *pc = (char *) p;
*(p++) = 6 ;
*(int *)(pc+4) = 7;
printf(”%d %d %d %d %d\n”, x[0], x[1], x[2], x[3], x[4]);


6,7,3,4,5.





3. What is the value of a 32-bit integer with bits 13:9 (9 through 13) set to 0x1A?
4. Given an array that contains N numbers, write a routine to determine if there are two numbers in the array whose sum equals the number K. For example, given the array {8, 4, 1, 6}, and K=10, then return true since 4+6=10. Describe a solution that would take O(N log N) time.
5. Answer the following questions relating to the code below:
class Buffer {
static int dataBuffer[100];
static int head = 0;
static int tail = 0;

public:
static void Produce(int data) {
dataBuffer[head++] = data;
if (head == 100) head = 0;
}
static bool CanConsume() {
if (head != tail) return true;
return false;
}
static int Consume() {
int pos = tail++;
if (tail == 100) tail = 0;
return dataBuffer[pos];
}
}
void Producer() {
while(1) {
… some stuff …
Buffer.Produce(x);
… some stuff …
}
}
void Consumer() {
while(1) {
… some stuff …
if(Buffer.CanConsume() ) {
int x = Buffer.Consume();
… do something with x …
}
… some stuff …
}
}

a. If we have a multithreaded system with one thread executing ‘Producer’ and one thread executing ‘Consumer’ is there anything wrong with the code above? Give details.
The major bug in this implementation is buffer is not protected. Two problems will occur: the producer may write into the buffer and index is not updated yet, consumer will get the wrong result. We can use the semaphore that limits access to that section of code to only one thread at a time.

b. If we have two threads running ‘Producer’ and one thread running ‘Consumer’ is there anything wrong with the code above? Give details.
If two threads running ‘producer’ and one thread running ‘consumer’, the buffer will be overflow because of the fast speed of producing data. We need another semaphore indicating the buffer is not full in order to produce the data into buffer.


c. If we have one thread Running ‘Producer’ and two threads running ‘Consumer’ is there anything wrong with the code above? Give details.
If we have one thread Running ‘Producer’ and two threads running ‘Consumer’, the buffer will be empty. The thread consumer will wake up, grab the lock and see that the buffer is empty or not, and then go back to sleep. We need set another semaphore indicating the buffer is not empty.



6. Write a function to return a nearest integer value given a float input.

int round (float f)
{
return nearIntegel = f>=0?(int)(x+0.5):(int)(x-0.5);
}



Intel graphic team

Intel Graphyics Team
One of the things with the questions below is that some of the
questions are not as straightforward as they look since they
may not work on all system architectures or maybe performance
sensitive. For additional brownie points, you are encouraged
to make additional comments about the questions/answers.
1. Consider the following structure definitions:
typedef struct {
int a;
int b;
int c;
} ABC;

typedef struct {
int d;
int e;
int f;
ABC *abc;
} DEF;

Write code for the following two functions:

// The create function uses a SINGLE MALLLOC to allocate for structure
// DEF and its child structure (i.e. at the end of the allocation,
// these two lines of code will be valid:
//
// DEF *pdef = CreateDEF ();
// pdef->abc->a = 10;
DEF *CreateDEF (void)
{


}

// Note: To the free function, we are passing a pointer to ABC.

void FreeDEF (ABC *pabc)
{

}

solution:
#include "stdafx.h"
typedef struct {
int a;
int b;
int c;
} ABC;

typedef struct {
int d;
int e;
int f;
ABC *abc;
} DEF;

DEF *CreateDEF (void)
{
// dynamicallly allocate the memory
DEF *temp_DEF = (DEF*)malloc(sizeof(DEF));
if(!temp_DEF){
printf("\n error allocating the memory for DEF\n");
return NULL ;
}
else
{
//allocate the memory for its child structure
temp_DEF->abc = (ABC*)malloc(sizeof(ABC));
if(!temp_DEF->abc){
printf("\n error allocating the memory for its child ABC\n");
return NULL ;
}
// return the valid memory allocation
return temp_DEF;
}
}
void FreeDEF (ABC *pabc)
{
//if memory is not empty
if(pabc!=NULL) free(pabc);

}

int _tmain(int argc, _TCHAR* argv[])
{
DEF *pdef = CreateDEF ();

//problem 2.
int value;

// get the address of pdef
value = (int) pdef;
// address + 8, moved to pdef->f
value += 8;

// then pass 10 to pdef->f.
*(int *) value = 10;

//now you can pass value to pdef.
pdef->abc->a = 10;
// print out the value on console.
printf("%d\n", pdef->abc->a);
printf("%d\n", pdef->abc-f);

//deallocate the memory
FreeDEF(pdef->abc);
if(pdef!=NULL) free(pdef);

return 0;
}


2. Is the following code OK? What does it do?

DEF *pdef = CreateDEF();
int value;

value = (int) pdef;
value += 8;

*(int *) value = 10;

solution:
it fristly get the address of pdef and add by 8 bypte, which
point to the f of DEF. therefore, the value 10 should pass to
pdef->f.
pdef->f =10




3. Consider 4 components of a color where:

unsigned char red = 0x10;
unsigned char green = 0xFF;
unsigned char blue = 0x0F;
unsigned char alpha = 0x44;

Generate a packed color ARGB which is a 32 bit integer such that A is in the
MSB of ARGB followed by red, green, blue

-----------------
A R G B
-----------------

unsigned int PackBytes (unsigned char red, .. green, ... blue, .. alpha)
{


}

solution:
#include "stdafx.h"
unsigned int PackBytes (unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha)
{

unsigned int result;
// package the four elements using left shift and or.
result = (alpha<<24)(red<<16)(green<<8)(blue);
return result;
}
void UnPackByptes(unsigned int result)
{
unsigned char alpha,red,green, blue;
alpha = (result&0xFF000000)>>24;
red = (result&0x00FF0000)>>16;
green = (result&0x0000FF00)>>8;
blue = (result&0x000000FF);
printf("%d,%d,%d,%d\n",alpha,red,green,blue);
}
int _tmain(int argc, _TCHAR* argv[])
{
unsigned char red = 0x10;
unsigned char green = 0xFF;
unsigned char blue = 0x0F;
unsigned char alpha = 0x44;
unsigned int result;
//package these four components
result = PackBytes(red,green,blue,alpha);
printf("the packaged result is %d\n",result);
//unpack the result into four components for verification.
UnPackByptes(result);
return 0;
}


4. What is wrong with the following code?

a. How would you fix it by changing the code?
b. How would you fix it by changing the macro? (Not allowed to
collapse the three printf's into a single printf).


#define PRINT_THREE_TIMES \
printf ("one: %d\n", 1); \
printf ("two: %d\n", 2); \
printf ("three: %d\n", 3); \



if (i == 1)
....;
else if (i == 2)
....;
else if (i == 3)
PRINT_THREE_TIMES
else if (i == 4)
....;

Solution:
(a). adding bracket
if (i == 1)
....;
else if (i == 2)
....;
else if (i == 3)
{PRINT_THREE_TIMES}
else if (i == 4)
....;
(b).#define PRINT_THREE_TIMES_modify { printf ("one: %d\n", 1); printf ("two: %d\n", 2); printf ("three: %d\n", 3);}
5. Consider the following code:
int CheckForZero (int a[], int n)
{
int i;

for (i = 0; i < n; i++) {
if (a[i] == 0) {
return (TRUE);
}
}
return (FALSE);
}
This code works - but it does a check for every element in 'a' - i.e.
it does "n" compares and bails early if it finds even one zero element.
Our array 'a' generally does not have a zero. Optimize this code to
do only one compare. Feel free to instead use some mathematical
operations such as ADD, SUB etc.

Solution:
#include "stdafx.h"
int CheckForZero_Opt(int a[],int n)
{
int i,result=1;
//multiply all elements for once comparison, in fact, doing such way is not efficient, because each time
// multiplication is very expensive. however,in order to provide once comparison, this is one method.
for (i=0;i result*=a[i];
//if result is zero, it means that there is at least one zero element in the array.
if(result==0)
return 1;
else
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[4]={1,0,-2,4};
int flag;
flag = CheckForZero_Opt(a,4);
if(flag==1) printf("there is at least one zero element in the array\n");
else printf("there is no zero in the array\n");

return 0;
}
6. Consider the following function:
int SpecialFunction (int a)
{

if (a <= 1) {
return (1);
} else {
return (a * SpecialFunction (a - 2));
}
}

What is the value of x where "x = SpecialFunction (11)"


11*9*7*5*3*1=10395





7. Write code to see if a number is a power of 2

int Is2Power (unsigned int a)
{


}
solution:
#include "stdafx.h"
int Is2Power (unsigned int a)
{
int numOnes=0;
//calculate the total numbers of 1 in the integer number.
while(a)
{ a = a&(a-1);
numOnes++;
}
// if only oneOnes,then it is power of 2.
if(numOnes==1)
return 1;
else
return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
int a,flag;
printf("please input one integer number here:\n");
scanf("%d",&a);
flag = Is2Power(a);
if(flag==1) printf("this is a power of 2\n");
else printf("this is not a power of 2\n");
return 0;
}


8. What is the value of x where "x = sizeof (struct A)" on a 32 bit machine?
Show your calculations.

struct A {
char a;
char b;
int c;
short d;
int *p;
};

solution:
#include "stdafx.h"
struct A {
char a;//1 byte
char b;//1 byte
int c;//4 byte
short d;//4 byte
int *p; //4 byte.

};
/*according to the above label,the length of struct should 14.in fact the actual length should be 16, not 14, because of word alignment. The reason for this is that most compilers, by default, align complex data-structures to a word alignment boundary. In addition, the individual members are also aligned to their respective alignment boundaries. By this logic, the structure student gets aligned on a word boundary and the variable age within the structure is aligned with the next word address. This is accomplished by way of the compiler inserting "padding" space between two members or to the end of the structure to satisfy alignment requirements.This padding is inserted to align age with a word boundary. */
int _tmain(int argc, _TCHAR* argv[])
{
int length;
length = sizeof(struct A);
printf("%d\n",length);
return 0;
}


9. The operating system typically allocates memory in pages such that
the base address of the pages are 0, 4K, 8K, .... Given two
addresses, write a program to find if two pointers are on the
same page.

int AreOnSamePage (int *a, int *b)
{


}

solution:
#include "stdafx.h"
int AreOnSamePage (int *a, int *b)
{

int aAddress = int(a);
int bAddress = int(b);
int page_size = 4096;
int aPageNum, bPageNum;

//define the page number in the memory space
aPageNum = aAddress/page_size;
bPageNum = bAddress/page_size;

//if they are the same papge, return 1.
if(aPageNum==bPageNum&&abs(bAddress-aAddress) return 1;
else
return 0;

}
int _tmain(int argc, _TCHAR* argv[])
{
int *a,*b;
int c;
//dynamically allocat memory for a and b
a = (int*)malloc(sizeof(int));
b = (int*)malloc(sizeof(int));
// decide whether they are on the same page.
c = AreOnSamePage(a,b);
//print out result
if(c==1) printf("they are in the same page\n");
else printf("they are not in the same page\n");
//deallocate memory
free(a);
free(b);
return 0;
}

10. Write a function to generate a nearest integer value.

int round (float f)
{
}
solution:
#include "stdafx.h"
int round (float f)
{
return int(f+0.5);
}
int _tmain(int argc, _TCHAR* argv[])
{
float f;
int c;
printf("please input on float number here:\n");
scanf ("%f",&f);
c = round(f);
printf("round number is %d\n",c);
return 0;
}

Qualcomm Internship Interview questions

2) Tell me about the most enjoyable project you have completed while at work/school, and why
· I developed one robust face detection/tracking algorithm on TI OMAP3430 platform, and also based on face detection I can overlay 2D/3D graphics object on the Phone via OpenGL.
· I improved H.264 video encoding with my developed two algorithms.
· Recently I also developed one robust head pose estimation running on TI OMAP3430.
· TI has already shown my developed demos to their customers.


3) What are some questions you would ask yourself before deciding to use a LUT to complete some task?
· (1). Firstly we should think lookup table can be generalized to other conditions. For example, we have developed one lookup table for color-based on tracking. In order to robustly tracking the faces, I have developed two lookup tables for fluorescent and incandescent conditions. For other conditions between fluorescent and incandescent condition, you need to consider whether your developed lookup table still works.
· (2). How big is your lookup table, especially for mobile device.


4) What data structure would you use if you were developing a spell checker for a language that contained 10 words, 100 words, 50000 words?
For 50000 words,
Binary Tree for larger dictionary should be used, because it gives O(log2(n)).
For small dictionary, array should be used.


4) What is one way you could dramatically hurt the performance of an image rotation function?
The pixel at non-integer position, additonal interpolation filter should be used.


6) What was this programmer most likely trying to do, and fix his code:
int f(char * p)
{
int n = 0;
while(*p != 0) n = 10 *n + *++p - 0;
return &n;
}
Convert one string to integer number.
int f(char * p)
{
int n = 0;
while(*p != 0)
n = 10 *n + *p++ - 0; // should post pointer plus plus
return n; //return one value not address.
}

Thursday, July 9, 2009

List all file names in one folder using C.

FILE *fid;
char fileName[256];
//positive samples(fist)
system("dir /s/b C:\\jianfeng\\debug_pics\\*.* > fist_list.txt");
fid = fopen("fist_list.txt","r");
if ( fid != NULL )
{
while ( fgets (fileName, sizeof(fileName), fid ) != NULL ) /* read a line */
{
fputs ( fileName, stdout ); /* write the line */
}
fclose ( fid );
}
else
{
perror ( "error" ); /* why didn't the file open? */
}

Wednesday, July 8, 2009

Machine Learning: Expectation Maximization via OpenCV

#include
#include
int main( int argc, char** argv )
{
const int N = 4;
const int N1 = (int)sqrt((double)N);
const CvScalar colors[] = {{{0,0,255}},{{0,255,0}},{{0,255,255}},{{255,255,0}}};
int i, j;
int nsamples = 100;
CvRNG rng_state = cvRNG(-1);
CvMat* samples = cvCreateMat( nsamples, 2, CV_32FC1 );
CvMat* labels = cvCreateMat( nsamples, 1, CV_32SC1 );
IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
float _sample[2];
CvMat sample = cvMat( 1, 2, CV_32FC1, _sample );
CvEM em_model;
CvEMParams params;
CvMat samples_part;
cvReshape( samples, samples, 2, 0 );
for( i = 0; i < N; i++ )
{
CvScalar mean, sigma;
// form the training samples
cvGetRows( samples, &samples_part, i*nsamples/N, (i+1)*nsamples/N );
mean = cvScalar(((i%N1)+1.)*img->width/(N1+1), ((i/N1)+1.)*img->height/(N1+1));
sigma = cvScalar(30,30);
cvRandArr(&rng_state, &samples_part, CV_RAND_NORMAL, mean, sigma );
}
cvReshape( samples, samples, 1, 0 );
// initialize model's parameters
params.covs = NULL;
params.means = NULL;
params.weights = NULL;
params.probs = NULL;
params.nclusters = N;
params.cov_mat_type = CvEM::COV_MAT_SPHERICAL;
params.start_step = CvEM::START_AUTO_STEP;
params.term_crit.max_iter = 10;
params.term_crit.epsilon = 0.1;
params.term_crit.type = CV_TERMCRIT_ITERCV_TERMCRIT_EPS;
// cluster the data
em_model.train( samples, 0, params, labels );
// classify every image pixel
cvZero( img );
for( i = 0; i <>height; i++ )
{
for( j = 0; j <>width; j++ )
{
CvPoint pt = cvPoint(j, i);
sample.data.fl[0] = (float)j;
sample.data.fl[1] = (float)i;
int response = cvRound(em_model.predict( &sample, NULL ));
CvScalar c = colors[response];
cvCircle( img, pt, 1, cvScalar(c.val[0]*0.75,c.val[1]*0.75,c.val[2]*0.75), CV_FILLED );
}
}
//draw the clustered samples
for( i = 0; i < nsamples; i++ )
{
CvPoint pt;
pt.x = cvRound(samples->data.fl[i*2]);
pt.y = cvRound(samples->data.fl[i*2+1]);
cvCircle( img, pt, 1, colors[labels->data.i[i]], CV_FILLED );
}
cvNamedWindow( "EM-clustering result", 1 );
cvShowImage( "EM-clustering result", img );
cvWaitKey(0);
cvReleaseMat( &samples );
cvReleaseMat( &labels );
return 0;
}