Timers in NS2

If you are learning ns2, timers are often an obstacle. They concern with the ability of calling classes methods in consequence of an event schedule. The difficult raises when trying to find out in which order methods are called. If timers are involved, you can’t expect to find nested calls of methods until the one you are interested in. In this section it is explained how to understand this behavior.

A TimeHandler, as name suggests, is an object created to manage time, and is defined in the common/timer-handler(.cc,.h) files of your ns2 distribution. This handler is in charge to schedule the execution of events during the simulation. The time the handler refers to is the simulation time, not depending on the time your machine uses to process the code.
A timer is like a state machine and is charachterized by three states. The first is TIMER_IDLE which means that timer can manage an event. The next state is TIMER_PENDING, describing a status in which the timer is waiting to manage an event, and so it can’t accept new events. This means that the timer has accepted to manage an event to be scheduled in the future and it is busy, waiting for this event. The last state is TIMER_HANDLING in which the event is processed, calling the expire() function. After processing the event, timer returns in idle state.
In cbr/cbr-module(.cc,.h) of the MIRACLE distribution you can find a simple timer example, exploited to manage CBR packets transmission.
In the header file we define a new TimerHandler object. It is NOT possible to use TimerHandler class as is, because each timer has to handle its events in a particular fashion, which depends on the content of expire() function.

/**
 * Timer used by CbrModule to schedule packet transmission
 */
class SendTimer : public TimerHandler
{
public:
  SendTimer(CbrModule *m) : TimerHandler() { module = m; }

protected:
virtual void expire(Event *e);
CbrModule* module;
};

We defined the constructor, the expire() function and a reference to the module the timer refers to.
On the other side, when defining CbrModule, we have to add SendTimer_ as a friend class, in order to make it able to properly manage events. In this case expire() function has to call a CbrModule private method to activate packet sending processes.

  friend class SendTimer;

It is also necessary to define (in CbrModule) the timer itself, to have a reference to the object to whom submit events.

  SendTimer sendTmr_;  /*timer which schedules packet transmissions*/

In CbrModule.cc file, when you define the module constructor you have also to activate Timer constructor. This one has a reference to this to definitively associate SendTimer to this CbrModule. If you look at the definition of timer constructor, you’ll see that it only associates a CbrModule to the object (the one which submits events) to be managed by the timer.

CbrModule::CbrModule() 
  : sendTmr_(this),

At the top of the same file there is the definition of expire() function. When timer switchs to the TIMER_HANDLING state, it refers to this particular set of actions. When a CbrModule event expires, the function transmit() is called. Note that this function is defined in CbrModule, so Timer class has to be declaredas a friend of Module one. The module attribute refers to CbrModule, as explained before (see the constructor).

void SendTimer::expire(Event *e)
{
  module->transmit();
}

Now we are ready to schedule an event. TimerHandler class offers two methods to do this. They work in a similar fashion: both of them schedule an event but, while one is made to be called occasionally (i.e., when the timer is not busy, TIMER_IDLE), the second is created to work in an always pending status, in order to consecutively recall expire() function. If timer is always in TIMER_PENDING status, no other (sporadic) events can be managed by the timer. The former is called sched() and the latter is called resched(). The sched() function works only if timer is TIMER_IDLE while resched() can potentially cancel a previously scheduled TIMER_PENDING event and to schedule its new event. In this way the timer is maintaned always busy for those methods which don’t call resched() function. If your method instead, has the privileged resched() call you can access and modify the events.
In CbrModule we want to periodically transmit a packet. To achieve this result we use resched() function.

void CbrModule::start()
{
  ...
  sendTmr_.resched(period_);
}

At the end of transmit() method we reschedule again an event in order to create a “self-updating” loop. In this case, at the end of expire function, we schedule the timer for next period_ instants, maintaining the loop.

Thanx to ns-miracles for this post

Hi Guys

Hi Guys , December was the holiday time , in this  winter i decided to studied Python ,that is very Good Scripting LAnguage , this helps us in very different ways … i will put some lecture videos and some assignments this will help you guys .

 

All the BesT !! 🙂

How Many Ip Address !!!

Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given “25525511135”,
return [“255.255.11.135”, “255.255.111.35”]{hint:recursion,backtrack}

Here is the Solution ……
it was taken me about 5 hours to solve see !!!

//cc Arun Kumar Gupta

import java.util.*;
public class AllIpAddress
{
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
String input = sc.next();
int[] intArray = new int[input.length()];
int length = input.length();

for (int i = 0; i < input.length(); i++) {
intArray[i] = Character.digit(input.charAt(i), 10);
//System.out.println(intArray[i]);
}
int i = 0 , j = 1 , k = 2;
AllIpAddress ip = new AllIpAddress();
ip.Ipaddress(intArray , i , j , k , length-1);

}
void Ipaddress(int [] intArray , int i , int j , int k , int length)
{
try{
int where = 0 ,change = 0;
int p1 =createIP( intArray , -1 , i);
int p2 =createIP( intArray , i ,  j );
int p3 =createIP( intArray ,  j , k );
int p4 =createIP( intArray ,  k ,  length );
//System.out.println(“**********Garbage”+p1+”.”+p2+”.”+p3+”.”+p4);
//System.out.println(“i = “+i+”j = “+j+”k = “+k);
if((p1<=255)&&(p2<=255)&&(p3<=255)&&(p4<=255)&&(p4>0))
{
System.out.println(p1+”.”+p2+”.”+p3+”.”+p4);
}
if(p4 >255)
{
//if(k != j)
//++k;
where =4;
//System.out.println(“Problem at P4”);
}
else if(p3>255)
{
//if(j != i)
//++j;
//–k;
where = 3;
//System.out.println(“Problem at P3”);
}
else if(p2>255)
{
//++i;
where = 2;
//System.out.println(“Problem at P2”);
}
else if(p1>255)
{

//System.out.println(“Problem at P1”);
System.exit(0);
}

if((k == length) && (j+1 == k))
{
//System.out.println(“if((k == length) && (j+1 == k))”);
//System.out.println(i+”_”+j+”_”+k);
++i;
j = i+1;
k = j+1;
change = 1;
//System.out.println(i+”_”+j+”_”+k);

}
if((k == length) &&(change == 0) )
{
//System.out.println(“if((k == length) &&(change == 0) )”);
++j;
k = j+1;
change = 0;
}
else if(change == 0)
{
if( (k) < length )
++k;
}
/*if(where ==4)
{
++k;
}
if(where ==3)
{
++j;
–k;
}
if(where ==2)
{
++i;
–j;
}
/*if(k==length)
{
–k;
–j;
}*/
Ipaddress(intArray , i , j , k , length);
}
catch(ArrayIndexOutOfBoundsException e){
//System.out.println(“Exception thrown  :” + e);
}
}
static int createIP(int [] intArray , int start , int end)
{
//System.out.println(“I am at createIP()start = “+start+”\tend = “+end);
int val = 1 , fina = 0;
for(int e =end ; e>start ; –e)
{
fina = intArray[e]*val + fina;
val = val*10;
}
return fina;
}
}

Constant In C

A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.
  • Octal constants are written with a leading zero – 015.
  • Hexadecimal constants are written with a leading 0x – 0x1ae.
  • Long constants are written with a trailing L – 890L.

Character constants are usually just the character enclosed in single quotes; ‘a’, ‘b’, ‘c’. Some characters can’t be represented in this way, so we use a 2 character sequence as follows.

'\n' newline
'\t' tab
'\\' backslash
'\'' single quote
'\0' null ( Usedautomatically to terminate character string )
In addition, a required bit pattern can be specified using its octal equivalent.
‘\044’ produces bit pattern 00100100.
Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg “Brian and Dennis”. The string is actually stored as an array of characters. The null character ‘\0’ is automatically placed at the end of such a string to act as a string terminator.
A character is a different type to a single character string. This is important poing to note.

Defining Constants

ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed.
The const keyword is to declare a constant, as shown below:
int const a = 1;
const int a =2;
Note:
  • You can declare the const before or after the type. Choose one an stick to it.
  • It is usual to initialise a const with a value as it cannot get a value any other way.
The preprocessor #define is another more flexible (see Preprocessor Chapters) method to define constants in a program.
#define TRUE  1
#define FALSE 0
#define NAME_SIZE 20
Here TRUE, FALSE and NAME_SIZE are constant
You frequently see const declaration in function parameters. This says simply that the function is not going to change the value of the parameter.
The following function definition used concepts we have not met (see chapters on functions, strings, pointers, and standard libraries) but for completenes of this section it is is included here:
void strcpy(char *buffer, char const *string)

The enum Data type

enum is the abbreviation for ENUMERATE, and we can use this keyword to declare and initialize a sequence of integer constants. Here’s an example:
enum colors {RED, YELLOW, GREEN, BLUE};
I’ve made the constant names uppercase, but you can name them which ever way you want.
Here, colors is the name given to the set of constants – the name is optional. Now, if you don’t assign a value to a constant, the default value for the first one in the list – RED in our case, has the value of 0. The rest of the undefined constants have a value 1 more than the one before, so in our case, YELLOW is 1GREEN is 2 and BLUE is 3.
But you can assign values if you wanted to:
enum colors {RED=1, YELLOW, GREEN=6, BLUE };
Now RED=1, YELLOW=2, GREEN=6 and BLUE=7.
The main advantage of enum is that if you don’t initialize your constants, each one would have a unique value. The first would be zero and the rest would then count upwards.
You can name your constants in a weird order if you really wanted…
#include 

int main() {
enum {RED=5, YELLOW, GREEN=4, BLUE};

printf("RED = %d\n", RED);
printf("YELLOW = %d\n", YELLOW);
printf("GREEN = %d\n", GREEN);
printf("BLUE = %d\n", BLUE);
return 0;
}

This will produce following results

RED = 5
YELLOW = 6
GREEN = 4
BLUE = 5

Copied From Tutorial C

Prime Generator

Sorry for late post i was too busy ….
this is a new problem 
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

Input

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

Output

For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

Example

Input:
2
1 10
3 5

Output:
2
3
5
7

3
5




Solution :


CC Arun Kumar Gupta

import java.util.*;
public class FastestPrime
{
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
int test_cases = sc.nextInt();
if((test_cases <=10) && (test_cases > 0))
{
for(int i = 0 ; i {
int m = sc.nextInt();
int n = sc.nextInt();
if((m<= 1000000000) &&(n<=1000000000)&&(n>0)&&(m>0))
{
if((n-m) <= 100000)
{
if((m % 2) == 0)
++m;
for(int j = m ; j<= n ; ++j)
{
NextNum(j);
j = j+ 1;

}
}
}
System.out.println();
}
}


}
static void NextNum(int m)
{
int div = 3;
int array [] = new int[1000];
int rem = 1 ;
while((rem != 0) && (div <= (m/2)))
{
rem = m%div;
div = div+2;
}
if(rem != 0)
{
System.out.println(m);
}

}
}



Webcam is not Working in Ubuntu 11.10

Hi Guys back with some new stuffs of Linux ..
this happens frequently in Ubuntu, after some of using the Ubuntu webcam does not works.
so i have solution here .
it was taken long time to me found out the solution .
this solution worked in my laptop .

sudo apt-get install v4l2ucp
sudo v4l2ucp 

then run
cheese 

it will work   

Sync Subtitles With The Video In VLC

I can’t stress the usefulness of subtitles enough, especially when you’re watching a movie in a foreign language. I was watching Heavenly Forest, a Japanese romantic drama, a few days back. The movie was wonderful, but I wouldn’t have understood anything had it not been for those English subtitles. I even tend to use English subtitles while watchingEnglish movies, because you guys talk so fast (Americans) or so weird (British) that it’s hard for me to grasp!
Handy as they are, subtitles can turn extremely irritating if they’re out of sync with the video. They distract you, and you end up understanding even less than what you’d have without the subs. Thankfully, if you’re using VLC player to watch the videos, you can make use of a nifty feature in the program to sync the subtitle with the video! Do note that it’ll only temporarily sync the subtitles with the video, and the sync will be gone the next time you watch the video.
Anyway, lets get started with how to implement it. I’m assuming that you’ve already loaded the video and subtitle files into VLC (you can just drag them both into its interface). Now, carefully take a look at the video and the subs, and see whether the subs are lagging behind or running ahead of the video. If you’re watching a foreign movie, it may seem like a very difficult job, but just try a little hard and you should be able to make this out. For example, if you see a girl screaming and running around wildly, and the subs show “Help me! Help me!” 3 seconds after that scene, this means that the titles are 3 seconds behind the movie.
Once you’ve figured out the lag / lead of the subtitle, it’s time to sync it with the video. In VLC, navigate to Tools > Track Synchronization, where you’ll find the Subtitles/Video section. Now comes the important part – syncing the subtitle. If the subtitle is lagging behind the video, you’ve to provide a negative value to ‘Advance of subtitles over video’. Say the subs display 3 seconds after the video, the value you got to enter is –3.000 s. Note that you can adjust the sync time to upto a thousandth of a second, although adjusting to the tenths does the job in all cases. Similarly if the subtitle is ahead of the video, enter the required positive number of seconds. Hit the Refresh button at the top right corner of the window, and you should see the change immediately.

Max gain from given stock values



Given ticker value for a stock, for next n days, given what is the max profit that you can make ?
Eg – the max profit you can make is buy at time t1 @ 5 and sell @ t2 when stock was 12, to get max Profit of 7 dollars.

time – Stock Price

t0 – 10
t1 – 5
t2 – 12
t3 – 7
t4 – 12

Also – you can only trade once i.e you can buy and sell only 1 time.

so here is the solution of that problem .that problem is nothing just think like that if we have only one day stock values so we can buy or sell on that day only , so for general we can find the for up to kth day and we can find out for the k+1’th day ..

so algo is that maintain the 3 things first two pointer of buy and sell and one pointer of minimum values .we can make it in O(n) only



Just make a new array which contains the “lookahead” view, where we can see, which potential highest value we can gaini in future.

Another array just contains the lowest value so far. When the difference between the two arrays is max, there is the buying point. Selling point is, when the falling edge of the max array is reached.


public void highestGain(int[] prices) {
        int[] maxPrices = new int[prices.length];
        int[] minPrices = new int[prices.length];
        maxPrices[maxPrices.length-1] = prices[prices.length-1];
        minPrices[0] = prices[0];
        for(int i = 1; i <prices.length; i++) {
            int right = prices.length-i-1;
            minPrices[i] = Math.min(minPrices[i-1], prices[i]);
            maxPrices[right] = Math.max(maxPrices[right+1], prices[right]);
        }
        System.out.println("MaxPrices: " + Arrays.toString(maxPrices));
        System.out.println("MinPrices: " + Arrays.toString(minPrices));

// find when to buy (when the difference of min/max is highest)

        int maxDifference = maxPrices[0] - minPrices[0];
        int maxDifferencePos = 0;
        for(int i=0; i<minPrices.length; i++) {
            int difference = maxPrices[i] - minPrices[i];
            if(maxDifference < difference) {
                maxDifference = difference;
                maxDifferencePos = i;
            }
        }
        // Now find the falling edge of max prices - there was the last peak
        int sellPos = maxDifferencePos+1;
        int lastPrice = maxPrices[maxDifferencePos];
        for(; sellPos < maxPrices.length; sellPos++) {
            if(lastPrice > maxPrices[sellPos]) {
                sellPos --;
                break;
            }
        }

System.out.println("Ideal to buy/sell: " + maxDifferencePos + ":" + sellPos);

    }



Alien Chef


A new programming Problem…..

//http://www.codechef.com/problems/DOWNLOAD
/*


The aliens living in outer space are very advanced in technology, intelligence and everything, except one, and that is Cooking. Each year they spend millions of dollars in research, to crack famous recipes prepared by humans.

Recently they came to know about Khana-Academy, a non-profit organization streaming free cooking lesson videos on earth. There are N recipes, numbered 1 to N, and the video of the ith recipe is live in the time interval [Si, Ei]. An alien can visit earth but can not survive for more than just a small moment (earth is so advanced in pollution). An alien visits the earth at an integer time t and instantly downloads the complete video of all the lessons that are live at that moment of time t and leaves earth immediately. You are given the visiting times of a small group of K aliens. Find the number of different recipes aliens can learn by watching the downloaded videos. Not just one group of aliens, there are Q such groups, so you have to find the answer for each of these Q groups.
Input

The first line has an integer N. Each of the following N lines has two integers Si Ei. The next line has an integer Q, the number of groups. Each of the following Q lines has information of a group of aliens. The first integer is K, the number of aliens in that group, followed by K integers in the same line, the integer visiting times t of the aliens.


1 ≤ N ≤ 100000 (105)

1 ≤ Q ≤ 5000 (5 103)
1 ≤ K ≤ 20
1 ≤ Si, Ei, t ≤ 1000000000 (109)
Si < Ei

Output


For each of the Q groups, output the number of different recipes that group of aliens can learn by watching the downloaded videos.

Example

Input:

4
1 4
3 10
2 6
5 8
3
1 5
2 2 6
3 1 10 9

Output:

3
4
2

Explanation:

Given videos of 4 recipes in the following closed intervals.
1. [ 1 , 4 ]
2. [ 3 , 10 ]
3. [ 2 , 6 ]
4. [ 5 , 8 ]

In the first query, only one alien arrives at t = 5 and can download 3 recipes 2, 3, 4.


In the second query, two aliens arrive at t = 2 and 6. They can learn all the 4 recipes.


In the third query, three aliens arrive at t = 1, 10 and 9. They can learn only two recipes, 1 and 2.


*/




import java.util.*;
import java.lang.*;
/*public class Array
{
int num[]  = new int[20];



}

*/
public class AlienChefs
{
static int aaa[] = new int[100000];
static int end ;
//leng = 1;
static int start ;
public static void main(String [] args)
{

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if((0
{
int a[] = new int[2*n];
int add = 10;
for(int i = 0 ; i<(2*n) ; ++i)
{
//System.out.println(“Inside”);

a[i] = sc.nextInt();
if( (0
{
if((i%2) == 1   )
{
//System.out.println(“Inside”);
if((a[i-1] > a[i]))
System.exit(0);
}

}
else 
System.exit(0);
}
int groups = sc.nextInt();
//System.out.println(“********************”);
//int address[] = new int[groups];
for(int i = 0 ; i< groups; ++i)
{
int count = 0 ;
int alen = 0 ;
int times = sc.nextInt();
for(int j =0 ;j
{

alen = sc.nextInt();
if((0
{
//System.out.println(alen);
count = count+ cc(a , alen);

}


}
start = end – start;
start = start +end + add ;
end = start;
aaa[start] = 1000;
System.out.println(count);

}
}

}
static int cc(int a [] , int val)
{
int count = 0 ;

for(int i = 0 ; i< a.length; i++)
{ //static int a;
int abc =0;


if((a[i] <= val)&& (val <= a[i+1] ))
{
//System.out.println(“***************************************”);
abc = check(aaa , i);
if( abc == 0)
{
++count;
}

}
++i;

}
//System.out.println(“Count Returned :”+count);

return count;
}
static int check(int qw [], int i)
{
//System.out.println(“Check Function is called “);
//System.out.println(start+”:”+end);
//System.out.println(“i = “+i);
for(int j = start ; j<=end ; j++)
{
if(qw[j] == i)
return 1;
}
qw[end] = i;
//System.out.println(qw[end]+”   :::::::Value Added”);
++end;
return 0;

}
}


How Many Ip Address !!!

Hi Friends new problemGiven a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given “25525511135”,

return [“255.255.11.135”, “255.255.111.35”]{hint:recursion,backtrack}


Here is the Solution …… 
it was taken me about 5 hours to solve see !!!

//cc Arun Kumar Gupta

import java.util.*;
public class AllIpAddress
{
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
String input = sc.next();
int[] intArray = new int[input.length()];
int length = input.length();

for (int i = 0; i < input.length(); i++) {
intArray[i] = Character.digit(input.charAt(i), 10);
//System.out.println(intArray[i]);
}
int i = 0 , j = 1 , k = 2;
AllIpAddress ip = new AllIpAddress();
ip.Ipaddress(intArray , i , j , k , length-1);

}
void Ipaddress(int [] intArray , int i , int j , int k , int length)
{
try{
int where = 0 ,change = 0;
int p1 =createIP( intArray , -1 , i);
int p2 =createIP( intArray , i ,  j );
int p3 =createIP( intArray ,  j , k );
int p4 =createIP( intArray ,  k ,  length );
//System.out.println("**********Garbage"+p1+"."+p2+"."+p3+"."+p4);
//System.out.println("i = "+i+"j = "+j+"k = "+k);
if((p1<=255)&&(p2<=255)&&(p3<=255)&&(p4<=255)&&(p4>0))
{
System.out.println(p1+"."+p2+"."+p3+"."+p4);
}
if(p4 >255)
{
//if(k != j)
//++k;
where =4;
//System.out.println("Problem at P4");
}
else if(p3>255)
{
//if(j != i)
//++j;
//--k;
where = 3;
//System.out.println("Problem at P3");
}
else if(p2>255)
{
//++i;
where = 2;
//System.out.println("Problem at P2");
}
else if(p1>255)
{

//System.out.println("Problem at P1");
System.exit(0);
}

if((k == length) && (j+1 == k))
{
//System.out.println("if((k == length) && (j+1 == k))");
//System.out.println(i+"_"+j+"_"+k);
++i;
j = i+1;
k = j+1;
change = 1;
//System.out.println(i+"_"+j+"_"+k);

}
if((k == length) &&(change == 0) )
{
//System.out.println("if((k == length) &&(change == 0) )");
++j;
k = j+1;
change = 0;
}
else if(change == 0)
{
if( (k) < length )
++k;
}
/*if(where ==4)
{
++k;
}
if(where ==3)
{
++j;
--k;
}
if(where ==2)
{
++i;
--j;
}
/*if(k==length)
{
--k;
--j;
}*/
Ipaddress(intArray , i , j , k , length);
}
catch(ArrayIndexOutOfBoundsException e){
//System.out.println("Exception thrown  :" + e);
}
}
static int createIP(int [] intArray , int start , int end)
{
//System.out.println("I am at createIP()start = "+start+"\tend = "+end);
int val = 1 , fina = 0;
for(int e =end ; e>start ; --e)
{
fina = intArray[e]*val + fina;
val = val*10;
}
return fina;
}
}