Search This Blog

Saturday, December 31, 2011

How To: Disable Firewall on RHEL / CentOS / RedHat Linux

don't want firewall because I only run one http (port 80) public service. How do I turn off or disable firewall permanently under RHEL / Fedora Linux / Red Hat Enterprise Linux and CentOS Linux?

iptables is administration tool / command for IPv4 packet filtering and NAT. You need to use the following tools:
[a] service is a command to run a System V init script. It is use to save / stop / start firewall service.
[b] chkconfig command is used to update and queries runlevel information for system service. It is a system tool for maintaining the /etc/rc*.d hierarchy. Use this tool to disable firewall service at boot time.

How Do I Disable Firewall?

First login as the root user.
Next enter the following three commands to disable firewall.
# service iptables save
# service iptables stop
# chkconfig iptables off

If you are using IPv6 firewall, enter:
# service ip6tables save
# service ip6tables stop
# chkconfig ip6tables off

Linux Disable / Remove The Iptables Firewall

Iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel.
If you are using RHEL (Redhat), Fedora core or Cent os Linux just type following commands to disable the iptables firewall:
# service iptables save
# service iptables stop
# chkconfig iptables off

If you are using any other Linux distribution type the following command to clear up firewall rules:
# iptables -F
# iptables -X
# iptables -t nat -F
# iptables -t nat -X
# iptables -t mangle -F
# iptables -t mangle -X
# iptables -P INPUT ACCEPT
# iptables -P OUTPUT ACCEPT

You may need to put above rules in a shell script and execute the same. Also remove your iptables startup script from your network configuration file such as /etc/network/interfaces. Look for post-up directive.

Howto disable the iptables firewall in Linux

A Linux firewall is software based firewall that provides protection between your server (workstation) and damaging content on the Internet or network.
It will try to guard your computer against both malicious users and software such as viruses/worms.

Task: Disable / Turn off Linux Firewall (Red hat/CentOS/Fedora Core)

Type the following two commands (you must login as the root user):
# /etc/init.d/iptables save
# /etc/init.d/iptables stop

Task: Enable / Turn on Linux Firewall (Red hat/CentOS/Fedora Core)

Type the following command to turn on iptables firewall:
# /etc/init.d/iptables start

Other Linux distribution

If you are using other Linux distribution such as Debian / Ubuntu / Suse Linux etc, try following generic procedure.
Save firewall rules
# iptables-save > /root/firewall.rules
OR
$ sudo iptables-save > /root/firewall.rules
Now type the following commands (login as root):
# iptables -X
# iptables -t nat -F
# iptables -t nat -X
# iptables -t mangle -F
# iptables -t mangle -X
# iptables -P INPUT ACCEPT
# iptables -P FORWARD ACCEPT
# iptables -P OUTPUT ACCEPT

To restore or turn on firewall type the following command:
# iptables-restore < /root/firewall.rules

GUI tools

If you are using GUI desktop firewall tools such as 'firestarter', use the same tool to stop firewall.
System > Administration > firestarter > Click on Stop Firewall button:
Howto disable the iptables firewall in Debian  / Ubuntu Linux

rand() examples in c++

C++ Syntax (Toggle Plain Text)
  1. #include
  2. #include
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int random_integer = rand();
  9. cout << random_integer << endl;
  10. }
     
     
    C++ Syntax (Toggle Plain Text)
    1. #include
    2. #include
    3.  
    4. using namespace std;
    5.  
    6. int main()
    7. {
    8. cout << "The value of RAND_MAX is " << RAND_MAX << endl;
    9. }
       
       
       
      C++ Syntax (Toggle Plain Text)
      1. #include
      2. #include
      3. #include
      4.  
      5. using namespace std;
      6.  
      7. int main()
      8. {
      9. srand((unsigned)time(0));
      10. int random_integer = rand();
      11. cout << random_integer << endl;
      12. }
         
         
         
         
        C++ Syntax (Toggle Plain Text)
        1. #include
        2. #include
        3. #include
        4.  
        5. using namespace std;
        6.  
        7. int main()
        8. {
        9. srand((unsigned)time(0));
        10. int random_integer;
        11. for(int index=0; index<20; index++){
        12. random_integer = (rand()%10)+1;
        13. cout << random_integer << endl;
        14. }
        15. }
           
           
           
          C++ Syntax (Toggle Plain Text)
          1. #include
          2. #include
          3. #include
          4.  
          5. using namespace std;
          6.  
          7. int main()
          8. {
          9. srand((unsigned)time(0));
          10. int random_integer;
          11. int lowest=1, highest=10;
          12. int range=(highest-lowest)+1;
          13. for(int index=0; index<20; index++){
          14. random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
          15. cout << random_integer << endl;
          16. }
          17. }
             
             
             
             
             
           
         
       
     

rand() in c++

rand

function
int rand ( void );
Generate random number
Returns a pseudo-random integral number in the range 0 to RAND_MAX.

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using srand.

RAND_MAX is a constant defined in . Its default value may vary between implementations but it is granted to be at least 32767.

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014

Notice though that this modulo operation does not generate a truly uniformly distributed random number in the span (since in most cases lower numbers are slightly more likely), but it is generally a good approximation for short spans.

Parameters

(none)

Return Value

An integer value between 0 and RAND_MAX.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* rand example: guess the number */
#include 
#include 
#include 

int main ()
{
  int iSecret, iGuess;

  /* initialize random seed: */
  srand ( time(NULL) );

  /* generate secret number: */
  iSecret = rand() % 10 + 1;

  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret"The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);

  puts ("Congratulations!");
  return 0;
}


Output:

Guess the number (1 to 10): 5
The secret number is higher
Guess the number (1 to 10): 8
The secret number is lower
Guess the number (1 to 10): 7
Congratulations!

In this example, the random seed is initialized to a value representing the second in which the program is executed (time is defined in the header ). This way to initialize the seed is generally a good enough option for most randoming needs.

Getting Random Values in C and C++ with Rand

At some point in any programmer's life, he or she must learn how to get a random value, or values, in their program. To some this seems involved, difficult, or even beyond their personal ability. This, however, is simply not the case.
Randomizing of values is, at its most basic form, one of the easier things a programmer can do with the C++ language.

I will first start with an introduction to the idea of randomizing values, followed by a simple example program that will output three random values. Once a secure understanding of these concepts is in place (hopefully it will be), I will include a short program that uses a range of values from which the random values can be taken.
Ok, now that you know why this tutorial was written, and what it includes, you are ready to learn how to randomize values! So without further ado, let's get started, shall we?
Many programs that you will write require the use of random numbers. For example, a game such as backgammon requires a roll of two dice on each move. Since there are 6 numbers on each die, you could calculate each roll by finding a random number from 1 to 6 for each die.
To make this task a little easier, C++ provides us with a library function, called rand that returns an integer between 0 and RAND_MAX. Let's take a break to explain what RAND_MAX is. RAND_MAX is a compiler-dependent constant, and it is inclusive. Inclusive means that the value of RAND_MAX is included in the range of values. The function, rand, and the constant, RAND_MAX, are included in the library header file stdlib.h.
The number returned by function rand is dependent on the initial value, called a seed that remains the same for each run of a program. This means that the sequence of random numbers that is generated by the program will be exactly the same on each run of the program.
How do you solve this problem you ask? Well I'll tell you! To help us combat this problem we will use another function, srand(seed), which is also declared in the stdlib.h header file. This function allows an application to specify the initial value used by rand at program startup.
Using this method of randomization, the program will use a different seed value on every run, causing a different set of random values every run, which is what we want in this case. The problem posed to us now, of course, is how to get an arbitrary seed value. Forcing the user or programmer to enter this value every time the program was run wouldn't be very efficient at all, so we need another way to do it.
So we turn to the perfect source for our always-changing value, the system clock. The C++ data type time_t and the function time, both declared in time.h, can be used to easily retrieve the time on the computers clock.
When converted to an unsigned integer, a positive whole number, the program time (at execution of program) can make a very nice seed value. This works nicely because no two program executions will occur at the same instant of the computers clock.
As promised, here is a very basic example program. The following code was written in Visual C++ 6.0, but should compile fine on most computers (given u have a compiler, which if your reading this I assume you do). The program outputs three random values.
/*Steven Billington
January 17, 2003
Ranexample.cpp
Program displays three random integers.
*/
/*
Header: iostream
Reason: Input/Output stream
Header: cstdlib
Reason: For functions rand and srand
Header: time.h
Reason: For function time, and for data type time_t
*/
#include 
#include 
#include 

using namespace std;

int main()
{
/*
Declare variable to hold seconds on clock.
*/
time_t seconds;
/*
Get value from system clock and
place in seconds variable.
*/
time(&seconds);
/*
Convert seconds to a unsigned
integer.
*/
srand((unsigned int) seconds);
/*
Output random values.
*/
cout<< rand() << endl;
cout<< rand() << endl;
cout<< rand() << endl;
return 0;
}
Users of a random number generator might wish to have a narrower or a wider range of numbers than provided by the rand function. Ideally, to solve this problem a user would specify the range with integer values representing the lower and the upper bounds. To understand how we might accomplish this with the rand function, consider how to generate a number between 0 and an arbitrary upper bound, referred to as high, inclusive.
For any two integers, say a and b, a % b is between 0 and b - 1, inclusive. With this in mind, the expression rand() % high + 1 would generate a number between 1 and high, inclusive, where high is less than or equal to RAND_MAX, a constant defined by the compiler. To place a lower bound in replacement of 1 on that result, we can have the program generate a random number between 0 and (high - low + 1) + low.

/*
Steven Billington
January 17, 2003
exDice.cpp
Program rolls two dice with random
results.
*/
/*
Header: iostream
Reason: Input/Output stream
Header: stdlib
Reason: For functions rand and srand
Header: time.h
Reason: For function time, and for data type time_t
*/
#include 
#include 
#include 
/*
These constants define our upper
and our lower bounds. The random numbers
will always be between 1 and 6, inclusive.
*/
const int LOW = 1;
const int HIGH = 6;

using namespace std;

int main()
{
/*
Variables to hold random values
for the first and the second die on
each roll.
*/
int first_die, sec_die;
/*
Declare variable to hold seconds on clock.
*/
time_t seconds;
/*
Get value from system clock and
place in seconds variable.
*/
time(&seconds);
/*
Convert seconds to a unsigned
integer.
*/
srand((unsigned int) seconds);
/*
Get first and second random numbers.
*/
first_die = rand() % (HIGH - LOW + 1) + LOW;
sec_die = rand() % (HIGH - LOW + 1) + LOW;
/*
Output first roll results.
*/
cout<< "Your roll is (" << first_die << ", "
<< sec_die << "}" << endl << endl;
/*
Get two new random values.
*/
first_die = rand() % (HIGH - LOW + 1) + LOW;
sec_die = rand() % (HIGH - LOW + 1) + LOW;
/*
Output second roll results.
*/
cout<< "My roll is (" << first_die << ", "
<< sec_die << "}" << endl << endl;
return 0;
}

Generating Random Numbers

Generating Random Numbers
The key function in generating random numbers is;

 int random (int n);
which generates a random number in the range of 0 to n-1. For example;

 y = random(100);
y will be in the range of 0 though 99.
Note that if you run the following program, again and again, the same three random numbers will be generated. That is, TurboC always seeds the random number generator with the same starting number.
This feature is great for debugging. However, it would terrible if you were designing software for the gaming industry as everyone would know what numbers were going to come up.
Therefore, the function "randomize()" may be used to seed the random number generator with a number which is developed from the system clock, which of course, is always changing.

/*
** Program RANDOM1.C
**
** Generates three random numbers in range of 0 to 99 and
** reports as to which is the largest and which is the smallest.
**
** Intended to show the use of functions randomize(), random() anf the
** use of functions.
**
** Peter H. Anderson, MSU, Feb 6, '97
*/

#include 
#include  /* required for randomize() and random() */
#include   /* required for clrscr() */

int gen_rand(void);   /* note these are declarations of functions */
int find_max(int x, int y, int z);
int find_min(int x, int y, int z);

FILE *f1;

void main(void)
{
   int num1, num2, num3, max, min;

   clrscr();  /* clear the screen */

   f1=fopen("a:\\output.dta", "wt"); /* open a file for output */

   /* randomize(); */  /* uncomment this if you want a random start */

   num1=gen_rand();
   num2=gen_rand();
   num3=gen_rand();

   max=find_max(num1, num2, num3);
   min=find_min(num1, num2, num3);

   printf("Random numbers are %d, %d, and %d\n", num1, num2, num3);
   fprintf(f1, "Random numbers are %d, %d, and %d\n", num1, num2, num3);

   printf("Largest is %d.  Smallest is %d.\n", max, min);
   fprintf(f1, "Largest is %d.  Smallest is %d.\n", max, min);

   fclose(f1);
}

int gen_rand(void)
/* returns random number in range of 0 to 99 */
{
   int n;
   n=random(100);  /* n is random number in range of 0 - 99 */
   return(n);
}

int find_max( int x, int y, int z)
/* returns largest number */
{
   int max;
   if ((x>=y) && (x>=z))
   {
  max = x;
   }
   else if ((y>=x) && (y>=z))
   {
  max = y;
   }
   else
   {
  max = z;
   }
   return(max);
}

int find_min( int x, int y, int z)
/* returns smallest number */
{
   int min;
   if ((x<=y) && (x<=z))
   {
  min = x;
   }
   else if ((y<=x) && (y<=z))
   {
  min = y;
   }
   else
   {
  min = y;
   }
   return(min);
}

How to generate a random number in C?

#include 
#include 

srand(time(NULL));
int r = rand();
 
 
/* random int between 0 and 19 */
int r = rand() % 20;
 

Friday, December 30, 2011

How to use getline() and switch() together in c++

Add the line cin.ignore(); before the getline.
Main problem is that the stream operator >> leaves the newline in the stream so when you try to use getline it reads an empty line. ignore() will chew up the newline and let you read the string you expect.

Here is example:::

#include
#include
#include
using namespace std;
const int size=100;
const int length=50;
class list
{
   
    char name[size][length];
    //string name[size];
    int number[size];
    int count;
    char newName[length];
    //string newName;
   
    public:
    void CNT(void)
    {
        count =0; //initializes count to zero
    }

    void initialize(void);
    void check_list(void);
    void add_name(void);   
};

void list::initialize(void)
{
    int i;
    for(i=0;i    {
        number[i]=0;
        strcpy(name[i],"default");
       
    }
}

void list::add_name(void)
{   
    cin.ignore();
    cout<<"\n"<<"Enter your FULL NAME to add in list : ";
    //cin>>name[count];
    cin.getline(name[count],length);
    //cin.getline(name[count],length);
    cout<<"\n"<<"Enetr your name's associated number : ";
    cin>>number[count];
    count++;
    //cout<<"\n"<    cout<<"\n"<<"========================================================================";
}

void list::check_list(void)
{
    int i;
    int logic=0;
    cin.ignore();
    cout<<"\n"<<"Enter your FULL NAME to check the associated number with it : ";
    //cin>>newName;
    cin.getline(newName,length);
    //cin.getline(newName,length);
    for(i=0;i    {
        if(strcmp(name[i],newName)==0)
        {
            cout<<"\n"<<"Number associated with your name is : "<            logic=1;
        }
        else
        {
            if(i==size-1 && logic==0)
            {
                cout<<"\n"<<"Ack!! Your name is not in the list. Enter option number 2 to add your name in list "<<"\n";
               
            }
        }
    }
   
    //cout<<"\n"<<"name is = "<
    cout<<"\n"<<"========================================================================";
}

int main()
{
    list user;
   
    user.CNT();
    user.initialize();
    //user.check_list();
    //user.add_name();
       
    int x;
    do
    {
        cout<<"\n"<<"You can do the following : "<<" Enter approperiate number  ";
        cout<<"\n"<<" 1 : to check your name and associated number in list ";
        cout<<"\n"<<" 2 : to add your name in list ";
        cout<<"\n"<<" 3 : to Quit ";
        cout<<"\n"<<" Please select your option ";
        cin>>x;
        switch(x)
        {
            case 1: user.check_list();
            break;
            case 2: user.add_name();
            case 3: break;
            default : cout<<"\n"<<"Error in input : Please select your correct option ";
        }   
    }while(x!=3);
   
   
    cout<<"\n";
    return 0;
   
}

Use get() to read a string that contains spaces

Use get() to read a string that contains spaces

#include  
#include  
using namespace std; 
 
int main() 

  char str[80]
 
  cout << "Enter your name: "
  cin.get(str, 79)
 
  cout << str << '\n'
 
  return 0
}
Enter your name: Joe
Joe

Use of Get() function in c

/* gets example */
#include 

int main()
{
  char string [256];
  printf ("Insert your full address: ");
  gets (string);
  printf ("Your address is: %s\n",string);
  return 0;
}

get() and put() function use

#include
main( )
{
char name[30] ;
printf ( "Enter your name\n" ) ;
gets ( name ) ;

puts ( "Welcome to codesnipr.....");
puts ( name ) ;
getch();
}

Use of Getline() in C++

Example

1
2
3
4
5
6
7
8
9
10
11
// getline with strings
#include 
#include 
using namespace std;

int main () {
  string str;
  cout << "Please enter full name: ";
  getline (cin,str);
  cout << "Thank you, " << str << ".\n";
}

C Array of String

A String is an array of char objects. An array of string can be declared and handled like a 2d(two dimensional) arrays.

C Array of String

     
In this section you will learn how to create an array of string in C.
A String is an array of char objects. An array of string can be declared and handled like a 2d(two dimensional) arrays. You can see in the given example that we have declare a 2 dimensional character array consisting of three 'rows' and twelve 'columns'. The array is initialized with three character strings. In C, a format specifier %s is used with the printf to print the string.
Here is the code:

ARRAYSTR.C





#include 
#include 
void main() {
  clrscr();
  char arr[3][12]"Rose""India""technologies" };
  printf("Array of String is = %s,%s,%s\n", arr[0], arr[1], arr[2]);
  getch();
}

C String

Strings are arrays of chars. String literals are words surrounded by double quotation marks.
 
"This is a static string"
To declare a string of 49 letters, you would want to say:
 
char string[50];
This would declare a string with a length of 50 characters. Do not forget that arrays begin at zero, not 1 for the index number. In addition, a string ends with a null character, literally a '\0' character. However, just remember that there will be an extra character on the end on a string. It is like a period at the end of a sentence, it is not counted as a letter, but it still takes up a space. Technically, in a fifty char array you could only hold 49 letters and one null character at the end to terminate the string.

TAKE NOTE: char *arry; Can also be used as a string. If you have read the tutorial on pointers, you can do something such as:
 
arry = new char[256];
which allows you to access arry just as if it were an array. Keep in mind that to use delete you must put [] between delete and arry to tell it to free all 256 bytes of memory allocated.

For example:
 
delete [] arry.
Strings are useful for holding all types of long input. If you want the user to input his or her name, you must use a string. Using cin>> to input a string works, but it will terminate the string after it reads the first space. The best way to handle this situation is to use the function cin.getline. Technically cin is a class (a beast similar to a structure), and you are calling one of its member functions. The most important thing is to understand how to use the function however.

The prototype for that function is:
 
istream& getline(char *buffer, int length, char terminal_char);
The char *buffer is a pointer to the first element of the character array, so that it can actually be used to access the array. The int length is simply how long the string to be input can be at its maximum (how big the array is). The char terminal_char means that the string will terminate if the user inputs whatever that character is. Keep in mind that it will discard whatever the terminal character is.

It is possible to make a function call of cin.getline(arry, 50); without the terminal character. Note that '\n' is the way of actually telling the compiler you mean a new line, i.e. someone hitting the enter key.

For a example:
 
#include 

using namespace std;

int main()
{
  char string[256];                               // A nice long string

  cout<<"Please enter a long string: ";
  cin.getline ( string, 256, '\n' );              // Input goes into string
  cout<<"Your long string was: "<< string < 
Remember that you are actually passing the address of the array when you
 pass string because arrays do not require an address operator (&) 
to be used to pass their address. Other than that, you could make '\n' 
any character you want (make sure to enclose it with single quotes to 
inform the compiler of its character status) to have the getline 
terminate on that character.


 
cstring is a header file that contains many functions for manipulating strings. One of these is the string comparison function.
 
int strcmp ( const char *s1, const char *s2 );
strcmp will accept two strings. It will return an integer. This integer will either be:
 
Negative if s1 is less than s2.
Zero if s1 and s2 are equal.
Positive if s1 is greater than s2.
Strcmp is case sensitive. Strcmp also passes the address of the character array to the function to allow it to be accessed.
 
char *strcat ( char *dest, const char *src );
strcat is short for string concatenate, which means to add to the end, or append. It adds the second string to the first string. It returns a pointer to the concatenated string. Beware this function, it assumes that dest is large enough to hold the entire contents of src as well as its own contents.
 
char *strcpy ( char *dest, const char *src );
strcpy is short for string copy, which means it copies the entire contents of src into dest. The contents of dest after strcpy will be exactly the same as src such that strcmp ( dest, src ) will return 0.
 
size_t strlen ( const char *s );
strlen will return the length of a string, minus the terminating character ('\0'). The size_t is nothing to worry about. Just treat it as an integer that cannot be negative, which it is. Here is a small program using many of the previously described functions:
 
#include  //For cout
#include   //For the string functions

using namespace std;

int main()
{
  char name[50];
  char lastname[50];
  char fullname[100]; // Big enough to hold both name and lastname
  
  cout<<"Please enter your name: ";
  cin.getline ( name, 50 );
  if ( strcmp ( name, "Julienne" ) == 0 ) // Equal strings
    cout<<"That's my name too.\n";
  else                                    // Not equal
    cout<<"That's not my name.\n";
  // Find the length of your name
  cout<<"Your name is "<< strlen ( name ) <<" letters long\n";
  cout<<"Enter your last name: ";
  cin.getline ( lastname, 50 );
  fullname[0] = '\0';            // strcat searches for '\0' to cat after
  strcat ( fullname, name );     // Copy name into full name
  strcat ( fullname, " " );      // We want to separate the names by a space
  strcat ( fullname, lastname ); // Copy lastname onto the end of fullname
  cout<<"Your full name is "<< fullname <<"\n";
  cin.get();
}

Safe Programming

The above string functions all rely on the existence of a null terminator at the end of a string. This isn't always a safe bet. Moreover, some of them, noticeably strcat, rely on the fact that the destination string can hold the entire string being appended onto the end. Although it might seem like you'll never make that sort of mistake, historically, problems based on accidentally writing off the end of an array in a function like strcat, have been a major problem. Fortunately, in their infinite wisdom, the designers of C have included functions designed to help you avoid these issues. Similar to the way that fgets takes the maximum number of characters that fit into the buffer, there are string functions that take an additional argument to indicate the length of the destination buffer. For instance, the strcpy function has an analogous strncpy function
 
char *strncpy ( char *dest, const char *src, size_t len );
which will only copy len bytes from src to dest (len should be less than the size of dest or the write could still go beyond the bounds of the array). Unfortunately, strncpy can lead to one niggling issue: it doesn't guarantee that dest will have a null terminator attached to it (this might happen if the string src is longer than dest). You can avoid this problem by using strlen to get the length of src and make sure it will fit in dest. Of course, if you were going to do that, then you probably don't need strncpy in the first place, right? Wrong. Now it forces you to pay attention to this issue, which is a big part of the battle.

Compare strings: strcmp

Compare strings: strcmp



#include 
#include 

int main()
{
  char word1[20];
  char word2[20];

  printf("\n first word:\n1: ");
  scanf("%s", word1);                                 /* Read the first word    */

  printf(" second word:\n 2: ");
  scanf("%s", word2);                                 /* Read the second word   */

  /* Compare the two words */
  if(strcmp(word1,word2== 0)
    printf("identical words");
  else
    printf("%s comes before %s"(strcmp(word1, word20? word2 : word1, (strcmp(word1, word20? word2 : word1);
}

Wednesday, December 21, 2011

void() type: where and where not it shoul be used

The void type is an incomplete type that cannot be completed.
The void type has three important uses:
  • To signify that a function returns no value
  • To indicate a generic pointer (one that can point to any type object)
  • To specify a function prototype with no arguments
The following example shows how void is used to define a function, with no parameters, that does not return a value:
void message(void)
{
  printf ("Stop making sense!");
}
The next example shows a function prototype for a function that accepts a pointer to any object as its first and second argument:
void memcopy (void *dest, void *source, int length);
A pointer to the void type has the same representation and alignment requirements as a pointer to a character type. The void * type is a derived type based on void .
The void type can also be used in a cast expression to explicitly discard or ignore a value. For example:
int tree(void);

void main()
{
  int i;

  for (; ; (void)tree()){...}  /* void cast is valid                  */

  for (; (void)tree(); ;){...} /* void cast is NOT valid, because the */
                               /* value of the second expression in a */
                               /* for statement is used               */

  for ((void)tree(); ;) {...}  /* void cast is valid                  */

}
A void expression has no value, and cannot be used in any context where a value is required.

===================================================

The void data type always represents an empty set of values. The only object that can be declared with the type specifier void is a pointer.
When a function does not return a value, you should use void as the type specifier in the function definition and declaration. An argument list for a function taking no arguments is void.
You cannot declare a variable of type void, but you can explicitly convert any expression to type void. The resulting expression can only be used as one of the following:
  • An expression statement
  • The left operand of a comma expression
  • The second or third operand in a conditional expression.
Example of void Type
In the following example, the function find_max is declared as having type void.
Note:
C The use of the sizeof operator in the line find_max(numbers, (sizeof(numbers) / sizeof(numbers[0]))); is a standard method of determining the number of elements in an array.
   /**
   ** Example of void type
   **/
   #include 
 
   /* declaration of function find_max */
   extern void find_max(int x[ ], int j);
 
   int main(void)
   {
      static int numbers[ ] = { 99, 54, -102, 89};
 
      find_max(numbers, (sizeof(numbers) / sizeof(numbers[0])));
 
      return(0);
   }
 
   void find_max(int x[ ], int j)
   { /* begin definition of function find_max */
      int i, temp = x[0];
 
      for (i = 1; i < j; i++)
      {
          if (x[i] > temp)
             temp = x[i];
      }
      printf("max number = %d\n", temp);
   } /* end definition of function find_max  */

Sunday, December 18, 2011

What is Stream Processing ???

Stream processing is a computer programming paradigm, related to SIMD (single instruction, multiple data), that allows some applications to more easily exploit a limited form of parallel processing. Such applications can use multiple computational units, such as the FPUs on a GPU or field programmable gate arrays (FPGAs)[1], without explicitly managing allocation, synchronization, or communication among those units.
The stream processing paradigm simplifies parallel software and hardware by restricting the parallel computation that can be performed. Given a set of data (a stream), a series of operations (kernel functions) are applied to each element in the stream. Uniform streaming, where one kernel function is applied to all elements in the stream, is typical. Kernel functions are usually pipelined, and local on-chip memory is reused to minimize external memory bandwidth. Since the kernel and stream abstractions expose data dependencies, compiler tools can fully automate and optimize on-chip management tasks. Stream processing hardware can use scoreboarding, for example, to launch DMAs at runtime, when dependencies become known. The elimination of manual DMA management reduces software complexity, and the elimination of hardware caches reduces the amount of die area not dedicated to computational units such as ALUs.
During the 1980s stream processing was explored within dataflow programming. An example is the language SISAL (Streams and Iteration in a Single Assignment Language).

Applications

Stream processing is essentially a compromise, driven by a data-centric model that works very well for traditional DSP or GPU-type applications (such as image, video and digital signal processing) but less so for general purpose processing with more randomized data access (such as databases). By sacrificing some flexibility in the model, the implications allow easier, faster and more efficient execution. Depending on the context, processor design may be tuned for maximum efficiency or a trade-off for flexibility.
Stream processing is especially suitable for applications that exhibit three application characteristics[citation needed]:
  • Compute Intensity, the number of arithmetic operations per I/O or global memory reference. In many signal processing applications today it is well over 50:1 and increasing with algorithmic complexity.
  • Data Parallelism exists in a kernel if the same function is applied to all records of an input stream and a number of records can be processed simultaneously without waiting for results from previous records.
  • Data Locality is a specific type of temporal locality common in signal and media processing applications where data is produced once, read once or twice later in the application, and never read again. Intermediate streams passed between kernels as well as intermediate data within kernel functions can capture this locality directly using the 

For More Info Please visit Vikipedia link....


 http://en.wikipedia.org/wiki/Stream_processing

Thank You...

What is Stream Computing ??

In computing, the term stream is used in a number of ways, in all cases referring to a sequence of data elements made available over time. A stream can be thought of as a conveyor belt that allows items to be processed one at a time rather than in large batches.
  • On Unix and related systems based on the C language, a stream is a source or sink of data, usually individual bytes or characters. Streams are an abstraction used when reading or writing files, or communicating over network sockets. The standard streams are three streams made available to all programs.
  • Pipelines can also be understood as streams as well as any unlimited (non-packaged) information that is inserted by a device.
  • In the Scheme language and some others, a stream is a lazily evaluated or delayed sequence of data elements. A stream can be used similarly to a list, but later elements are only calculated when needed. Streams can therefore represent infinite sequences and series.[1] See Stream (type theory).
  • In the Smalltalk standard library and in other programming languages as well, a stream is an external iterator. As in Scheme, streams can represent finite or infinite sequences.
  • Stream processing — in parallel processing, especially in graphic processing, the term stream is applied to hardware as well as software. There it defines the quasi-continuous flow of data that is processed in a dataflow programming language as soon as the program state meets the starting condition of the stream.[2]
  • Filesystems can store multiple named independent streams against a single filename. There is one main stream that makes up the normal file data. Additional streams can be used to store icons, summary and indexing information, zone information (i.e., where the file was downloaded from) etc.[3]
  •  
  •  
  • For More Info.... Please Visit Wikipedia Link
  • http://en.wikipedia.org/wiki/Stream_%28computing%29

  • http://en.wikipedia.org/wiki/Stream_%28computing%29

What is Distributed Computing ??

Distributed computing is a field of computer science that studies distributed systems. A distributed system consists of multiple autonomous computers that communicate through a computer network. The computers interact with each other in order to achieve a common goal. A computer program that runs in a distributed system is called a distributed program, and distributed programming is the process of writing such programs.[1]
Distributed computing also refers to the use of distributed systems to solve computational problems. In distributed computing, a problem is divided into many tasks, each of which is solved by one or more computers.[2]

Parallel and distributed computing

Distributed systems are groups of networked computers, which have the same goal for their work. The terms "concurrent computing", "parallel computing", and "distributed computing" have a lot of overlap, and no clear distinction exists between them.[13] The same system may be characterised both as "parallel" and "distributed"; the processors in a typical distributed system run concurrently in parallel.[14] Parallel computing may be seen as a particular tightly-coupled form of distributed computing,[15] and distributed computing may be seen as a loosely-coupled form of parallel computing.[5] Nevertheless, it is possible to roughly classify concurrent systems as "parallel" or "distributed" using the following criteria:
  • In parallel computing, all processors have access to a shared memory. Shared memory can be used to exchange information between processors.[16]
  • In distributed computing, each processor has its own private memory (distributed memory). Information is exchanged by passing messages between the processors.[17]
The figure on the right illustrates the difference between distributed and parallel systems. Figure (a) is a schematic view of a typical distributed system; as usual, the system is represented as a network topology in which each node is a computer and each line connecting the nodes is a communication link. Figure (b) shows the same distributed system in more detail: each computer has its own local memory, and information can be exchanged only by passing messages from one node to another by using the available communication links. Figure (c) shows a parallel system in which each processor has a direct access to a shared memory.
The situation is further complicated by the traditional uses of the terms parallel and distributed algorithm that do not quite match the above definitions of parallel and distributed systems; see the section Theoretical foundations below for more detailed discussion. Nevertheless, as a rule of thumb, high-performance parallel computation in a shared-memory multiprocessor uses parallel algorithms while the coordination of a large-scale distributed system uses distributed algorithms.

Applications

There are two main reasons for using distributed systems and distributed computing. First, the very nature of the application may require the use of a communication network that connects several computers. For example, data is produced in one physical location and it is needed in another location.
Second, there are many cases in which the use of a single computer would be possible in principle, but the use of a distributed system is beneficial for practical reasons. For example, it may be more cost-efficient to obtain the desired level of performance by using a cluster of several low-end computers, in comparison with a single high-end computer. A distributed system can be more reliable than a non-distributed system, as there is no single point of failure. Moreover, a distributed system may be easier to expand and manage than a monolithic uniprocessor system.[21]
Examples of distributed systems and applications of distributed computing include the following:[22]

 Thank You....

What is Cloud Computing ??

Cloud computing is the delivery of computing as a service rather than a product, whereby shared resources, software, and information are provided to computers and other devices as a metered service over a network (typically the Internet).

Cloud computing is a marketing term for technologies that provide computation, software, data access, and storage services that do not require end-user knowledge of the physical location and configuration of the system that delivers the services. A parallel to this concept can be drawn with the electricity grid, wherein end-users consume power without needing to understand the component devices or infrastructure required to provide the service.
Cloud computing describes a new supplement, consumption, and delivery model for IT services based on Internet protocols, and it typically involves provisioning of dynamically scalable and often virtualised resources.[1][2] It is a byproduct and consequence of the ease-of-access to remote computing sites provided by the Internet.[3] This may take the form of web-based tools or applications that users can access and use through a web browser as if the programs were installed locally on their own computers.[4]
Cloud computing providers deliver applications via the internet, which are accessed from web browsers and desktop and mobile apps, while the business software and data are stored on servers at a remote location. In some cases, legacy applications (line of business applications that until now have been prevalent in thin client Windows computing) are delivered via a screen-sharing technology, while the computing resources are consolidated at a remote data center location; in other cases, entire business applications have been coded using web-based technologies such as AJAX.
At the foundation of cloud computing is the broader concept of infrastructure convergence (or Converged Infrastructure) and shared services.[5] This type of data center environment allows enterprises to get their applications up and running faster, with easier manageability and less maintenance, and enables IT to more rapidly adjust IT resources (such as servers, storage, and networking) to meet fluctuating and unpredictable business demand.[6][7]
Most cloud computing infrastructures consist of services delivered through shared data-centers and appearing as a single point of access for consumers' computing needs. Commercial offerings may be required to meet service-level agreements (SLAs), but specific terms are less often negotiated by smaller companies.[8][9]
The tremendous impact of cloud computing on business has prompted the federal United States government to look to the cloud as a means to reorganize their IT infrastructure and decrease their spending budgets. With the advent of the top government official mandating cloud adoption, many agencies already have at least one or more cloud systems online.[10]

Cloud computing shares characteristics with:


Cloud computing exhibits the following key characteristics:
  • Empowerment of end-users of computing resources by putting the provisioning of those resources in their own control, as opposed to the control of a centralized IT service (for example)
  • Agility improves with users' ability to re-provision technological infrastructure resources.
  • Application programming interface (API) accessibility to software that enables machines to interact with cloud software in the same way the user interface facilitates interaction between humans and computers. Cloud computing systems typically use REST-based APIs.
  • Cost is claimed to be reduced and in a public cloud delivery model capital expenditure is converted to operational expenditure.[15] This is purported to lower barriers to entry, as infrastructure is typically provided by a third-party and does not need to be purchased for one-time or infrequent intensive computing tasks. Pricing on a utility computing basis is fine-grained with usage-based options and fewer IT skills are required for implementation (in-house).[16]
  • Device and location independence[17] enable users to access systems using a web browser regardless of their location or what device they are using (e.g., PC, mobile phone). As infrastructure is off-site (typically provided by a third-party) and accessed via the Internet, users can connect from anywhere.[16]
  • Multi-tenancy enables sharing of resources and costs across a large pool of users thus allowing for:
    • Centralisation of infrastructure in locations with lower costs (such as real estate, electricity, etc.)
    • Peak-load capacity increases (users need not engineer for highest possible load-levels)
    • Utilisation and efficiency improvements for systems that are often only 10–20% utilised.[18]
  • Reliability is improved if multiple redundant sites are used, which makes well-designed cloud computing suitable for business continuity and disaster recovery.[19]
  • Scalability and Elasticity via dynamic ("on-demand") provisioning of resources on a fine-grained, self-service basis near real-time, without users having to engineer for peak loads.[20][21]
  • Performance is monitored, and consistent and loosely coupled architectures are constructed using web services as the system interface.[16]
  • Security could improve due to centralisation of data, increased security-focused resources, etc., but concerns can persist about loss of control over certain sensitive data, and the lack of security for stored kernels.[22] Security is often as good as or better than other traditional systems, in part because providers are able to devote resources to solving security issues that many customers cannot afford.[23] However, the complexity of security is greatly increased when data is distributed over a wider area or greater number of devices and in multi-tenant systems that are being shared by unrelated users. In addition, user access to security audit logs may be difficult or impossible. Private cloud installations are in part motivated by users' desire to retain control over the infrastructure and avoid losing control of information security.
  • Maintenance of cloud computing applications is easier, because they do not need to be installed on each user's computer.

For more info please visit Wikipedia link

http://en.wikipedia.org/wiki/Cloud_computing

Thank you....