::::::::::::::
EmbeddedReberGrammar.c
::::::::::::::

/* _embedded_ Reber grammar */

#include 
#include 
#include 
#include 


/* maximal sequence length is 512 */
typedef struct sequence_struct Sequence;
struct sequence_struct {
  char data[512][128];
  char descriptor[512];
  int  number_of_datapoints; 
};

Sequence sequence[2048];

char* gen_B() {

  /*      B T P S X V E    */
  return("1 0 0 0 0 0 0 ");
			
} 			
			
char* gen_T() {		
			
  /*      B T P S X V E  */
  return("0 1 0 0 0 0 0 ");
			
} 			
			
			
char* gen_P() {		
			
  /*      B T P S X V E  */
  return("0 0 1 0 0 0 0 ");
			
} 			
			
			
char* gen_S() {		
			
  /*      B T P S X V E  */
  return("0 0 0 1 0 0 0 ");
			
} 			
			
			
char* gen_X() {		
			
  /*      B T P S X V E  */
  return("0 0 0 0 1 0 0 ");
			
} 			
			
			
char* gen_V() {		
			
  /*      B T P S X V E  */
  return("0 0 0 0 0 1 0 ");
			
} 			
			
			
char* gen_E() {		
			
  /*      B T P S X V E  */
  return("0 0 0 0 0 0 1 ");
			
} 			
			
			
char* gen_SX() {		
			
  /*      B T P S X V E  */
  return("0 0 0 1 1 0 0 ");
			
} 			
			
			
char* gen_TV() {		
			
  /*      B T P S X V E  */
  return("0 1 0 0 0 1 0 ");
			
} 			
			
			
char* gen_PV() {		
			
  /*      B T P S X V E  */
  return("0 0 1 0 0 1 0 ");

} 


/* only needed for embedded Reber grammar */
char* gen_TP() {		
			
  /*      B T P S X V E    */
  return("0 1 1 0 0 0 0 ");

} 


void generate_sequence(int seq_no) {

  int state;
  char state_transition_0_1;

  sequence[seq_no].number_of_datapoints = 0;
  
  /* embedded part */
  
  /* generate B */
  sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]), 
	  "%s  %s\n", gen_B(), gen_TP());
  sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'B';
  sequence[seq_no].number_of_datapoints++;
  
  /* generate T or P */
  if (drand48() < 0.5) {
    sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
	    "%s  %s\n", gen_T(), gen_B());
    sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'T';
    state_transition_0_1 = 'T';
  }
  else {
    sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
	    "%s  %s\n", gen_P(), gen_B());
    sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'P';
    state_transition_0_1 = 'P';
  }
  sequence[seq_no].number_of_datapoints++;

  
  /* Reber grammar */
  
  /* generate B */
  sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]), 
	  "%s  %s\n", gen_B(), gen_TP());
  sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'B';
  sequence[seq_no].number_of_datapoints++;
  
  state = 1;
  while (state != 6) {
    switch (state) {
    case 1:  
      /* generate T or P */
      if (drand48() < 0.5) {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
	    "%s  %s\n", gen_T(), gen_SX());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'T';
	state = 2;
      }
      else {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
		"%s  %s\n", gen_P(), gen_TV());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'P';
	state = 3;
      }
      sequence[seq_no].number_of_datapoints++;
      break;
    case 2:
      /* generate S or X */
      if (drand48() < 0.5) {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
	    "%s  %s\n", gen_S(), gen_SX());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'S';
	state = 2;
      }
      else {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
		"%s  %s\n", gen_X(), gen_SX());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'X';
	state = 4;
      }
      sequence[seq_no].number_of_datapoints++;
      break;
    case 3: 
      /* generate T or V */
      if (drand48() < 0.5) {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
	    "%s  %s\n", gen_T(), gen_TV());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'T';
	state = 3;
      }
      else {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
		"%s  %s\n", gen_V(), gen_PV());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'V';
	state = 5;
      }
      sequence[seq_no].number_of_datapoints++;
      break;
    case 4:
      /* generate S or X */
      if (drand48() < 0.5) {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
	    "%s  %s\n", gen_S(), gen_E());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'S';
	state = 6;
      }
      else {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
		"%s  %s\n", gen_X(), gen_TV());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'X';
	state = 3;
      }
      sequence[seq_no].number_of_datapoints++;
      break;
    case 5: 
      /* generate P or V */
      if (drand48() < 0.5) {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
	    "%s  %s\n", gen_P(), gen_SX());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'P';
	state = 4;
      }
      else {
	sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]),
		"%s  %s\n", gen_V(), gen_E());
	sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'V';
	state = 6;
      }
      sequence[seq_no].number_of_datapoints++;
      break;
    default:
      fprintf(stderr, "reber: unknown state %d...\n", state);
    }
  }
  
  /* embedded part */
  
  /* generate E */
  if (state_transition_0_1 == 'T') {
    sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]), 
	    "%s  %s\n", gen_E(), gen_T());
    sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'E';
  }
  else {
    sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]), 
	    "%s  %s\n", gen_E(), gen_P());
    sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'E';
  }
  sequence[seq_no].number_of_datapoints++;
  
  /* generate T or P */
  if (state_transition_0_1 == 'T') {
    sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]), 
	    "%s  %s\n", gen_T(), gen_E());
    sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'T';
  }
  else {
    sprintf(&(sequence[seq_no].data[sequence[seq_no].number_of_datapoints][0]), 
	    "%s  %s\n", gen_P(), gen_E());
    sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = 'P';
  }
  sequence[seq_no].number_of_datapoints++;
  
  sequence[seq_no].descriptor[sequence[seq_no].number_of_datapoints] = '\0';


} /* generate_sequence */


int unique_sequence(int seq_no) {

  int i;
  
  for(i=0; i         // that is in unix C-d (Control + d)
 */

#include 

main(int argc, char **argv)
{
  if (argc < 3) {
    fprintf(stderr, "usage: %s -w|-r filename ; read or write file\n", argv[0])
;
    exit(1);
  }
  if (strcmp(argv[1], "-w") == 0) /* stringcompare */
    writefile(argv[2]);
  else if (strcmp(argv[1], "-r") == 0)
    readfile(argv[2]);
  else {
    fprintf(stderr, "unknown switch '%s' -- quitting\n", argv[1]);
    exit(1);
  }
}

/* copy standard in to file */

writefile(char *filename)
{
  int s;
  char buf[512];
  FILE *f;

  f = fopen(filename, "w");
  if (f == NULL) {
    fprintf(stderr, "couldn't open file '%s'\n", filename);
    exit(1);
  }
  
  while ((s = fread(buf, 1, sizeof(buf), stdin)) != NULL)
    fwrite(buf, 1, s, f);
  fclose(f);
}

/* copy file to standard out */

readfile(char *filename)
{
  int s;
  char buf[512];
  FILE *f;

  f = fopen(filename, "r");
  if (f == NULL) {
    fprintf(stderr, "couldn't open file '%s'\n", filename);
    exit(1);
  }
  
  while ((s = fread(buf, 1, sizeof(buf), f)) != NULL)
    fwrite(buf, 1, s, stdout);
  fclose(f);
}

::::::::::::::
ncurses.c
::::::::::::::
/* compile with : 
 * gcc ncurses.c -L/usr/distrib/lib  -I/usr/distrib/include -lncurses 
 * see: man curses
 */
#include 

int x, y;

main()
{
  initscr();
  getmaxyx(stdscr, x, y);   
  mvwprintw(stdscr, x/2, (y-5)/2, "In the mid!");
  refresh(); sleep(2);
  endwin();
}
::::::::::::::
random-test.c
::::::::::::::
#include 
#include 

main()
{
  float f, min, max;
  int i,ii;
  for(ii=0;ii<2;ii++) {
    for(i=0;i<100000;i++) {
      f =  (float) ((double) random()) / ((1 << 30)-1)-1;
      if (i==0) { min=0.5; max=0.3; }
      if (f>max) max=f;
      if (f

char a[10] = "ciao", c;


main() {
  c=a[2];
  printf("\n%s\n",&c);
  a[3] = a[2];
  printf("\n%s\n",a);
}
::::::::::::::
system.c
::::::::::::::
#include 
#include 

main()
{
  //system("ls");
  printf("ls\r");
  printf("ls\r\n");
}
::::::::::::::
systemcall.c
::::::::::::::
#include 

main()
{
  system("clear");
  system("date");
}
::::::::::::::
AddStrings.cpp
::::::::::::::
// use g++ not gcc
#include 
#include 
#include 

main()
{ 
  char s1[64] = "abc";
  char s2[64] = "def";
  char s3[64];
  // s3 = "ghijklmnopqrstuvwxyz\0";
  //s3 = s1 + s2;
  cout << s3 << "/n";
}
::::::::::::::
AndOrXorBitwise.cpp
::::::::::::::
#include 
#include 
#include 

main() {
    for(unsigned int i=0;i<2;i++)
      for(unsigned int ii=0;ii<2;ii++)
        cout< and:"<<(i&ii)
            <<" or:"<<(i|ii)<<" xor:"<<(i^ii)<
#include 
#include 

struct TS {
  union {
    int ia;
    int ib;
  };
};

main()
{
  TS s;
  s.ia = 3;
  cout << s.ia << "\t" << s.ib << endl;
  s.ib = 4;
  cout << s.ia << "\t" << s.ib << endl;
}
::::::::::::::
array.cpp
::::::::::::::


double *pd;

main()
{
  pd = new double[200];
  // pd = new double[10][20];
  delete[] pd;
}
::::::::::::::
ArrayIndexZero.cpp
::::::::::::::
#include 

void f(int *&i) { i[0]=17; }

main() { 
  int i=13; int *ip; ip=&i;
  f(((int *)&i)); 
  //f(ip);
  cout << i << endl; 
  cout << ip[0] << "   " << *ip << "   " << ip << endl; 
  (&i)[0] = 5;
  cout << i << endl; 
}
::::::::::::::
ArrayParaInit.cpp
::::::::::::::
int *pi;

main()
{ 
  pi = new int[2] = {3,4};
}

::::::::::::::
binary-file.cpp
::::::::::::::

#include 

test1() {
  FILE *f = fopen("bin-test","w");
  char c = 254;
  fputc(c,f);
  fclose(f);
  c =0;
  f = fopen("bin-test","r");
  fscanf(f,"%c", &c);
  printf("\n%c\n", c);
  float d;
  rewind(f);
  fscanf(f,"%f", &d);
  printf("\n%f\n", d);
  rewind(f);
  fscanf(f,"%d", &c);
  printf("\n%d\n", c);
  fclose(f);
}
test2() {
  FILE *f = fopen("bin-test","r");
  float d = 17.13;
  float dd;
  //fprintf(f,"%f",d);
  //rewind(f);
  fscanf(f,"%f", &dd);
  printf("\n%f\n", dd);
  fclose(f);
}

main() {
  test1();
}
::::::::::::::
bitfield.cpp
::::::::::::::
#include 
#include 
#include 
 
main() {
  struct {
    unsigned a :3;
    unsigned b :2;
    unsigned c :3;
  } f;
  f.a=7;f.b=3;f.c=7;
  cout << f.a << " " << f.b << " " << f.c << endl;
}
::::::::::::::
bool.cpp
::::::::::::::

bool b;

main()
{
  b = true;
}
::::::::::::::
Cast-Class-Pointers.cpp
::::::::::::::
#include
#include


// be aware of pointers to virtual inherited parts of classes
class A 
{
public:
  A() { cout << "Con A\n"; ia=17; }
  ~A(){ ia=76; cout << "Des A\n"; }
  int ia;
};

class B : public A
{
public:
  B() { cout << "Con B\n"; }
  ~B(){ cout << "Des B\n"; }
};

class C :  public B
{
public:
  C() { cout << "Con C\n"; ia=9; }
  ~C(){ cout << "Des C\n"; }
  void fonc() { cout << "do nothing"; }
};

main()
{
  cout << "new C...\n"; C* c = new C();
  cout << "cast up ...!\n";
  cout << "cast C* to A*\t"; A* a = (A*) c;
  cout << "c: " << c << " a  : " << a << "\n";
  cout << "cast C* to B*\t"; B* b = (B*) c;
  cout << "c: " << c << " b  : " << b << "\n";
  cout << "cast B* to A*\t"; A* b2a = (A*) b;
  cout << "b: " << b << " b2a: " << b2a << "\n";
  cout << "cast down ...!\n";
  cout << "cast A* to B*\t"; B* a2b = (B*) a;
  cout << "a: " << a << " a2b: " << a2b << "\n";
  cout << "cast A* to C*\t"; C* a2c = (C*) a;
  cout << "a: " << a << " a2c: " << a2c << "\n";
  cout << "cast B* to C*\t"; C* b2c = (C*) b;
  cout << "b: " << b << " b2c: " << b2c << "\n";
}
::::::::::::::
CellStateAndRecursion.cpp
::::::::::::::
#include 
#include 
#include "/home/felix/c-cpp/BaseClasses/MathMacros.h"
  
double G(double x) { return (4*LOGC(x)-2); }
double H(double x) { return (2*LOGC(x)-1); }

void Recursion(double &s,double x,double w,double scale, bool Frac) {
  double y; y = LOGC(x); //cout << y << endl; exit(0);
  cout << " " << scale*s;
  if(!Frac) { 
    //s=s*y+G(H(s)*w);
    s=s*y+H(s)*w;
    //s=s*y;
    //s=s+H(s)*w;
  } else {
    s=s/(1+fabs(s)*EXP(-x))+H(s)*w;
    //s=s/(1+fabs(s)*EXP(-x));
    //s=s/(1+SQR(fabs(s))*EXP(-x));
    //s=s/EXP(n)*(EXP(n)+1/(1+fabs(s)*EXP(-x)))+H(s)*w;
    //s=s/(1+pow(fabs(s),x))+H(s)*w;
    //s=s/(1+SQR(s)*EXP(-x))+H(s)*w;
    //s=s/(1+exp(log(fabs(s))/x))+H(s)*w;
  }
}

void st() {
  double s,s1,d,d1,w,x,xd,ds,dd;
  s=0.1; s1=s+0.1; d=s; d1=s1; 
  w=0.4; 
  x=+5; xd=x;
  for(int t=0;t<1000;t++) {
    cout << t;
    Recursion(s,x,w,1,false); //Recursion(s1,x,w,1,false);
    //Recursion(d,xd,w,1,true); Recursion(d1,xd,w,1,true);
    //ds=(s1-s)/s; dd=(d1-d)/d;
    //cout << " " << ds;///(s1+s);
    //cout << " " << dd;///(d1+d);
    //cout << " " << 1*(dd-ds);
    cout << endl;
  }
}

void ghs() {
  double s,w; w=-10;
  for(s=-10;s<10;s+=0.1)  cout << s << " " << -s << " " << s+G(H(s)*w) << endl;
}

void ghw() {
  double s,w; s=0.1;
  for(w=-1.5;w>-2.5;w-=0.1)  cout << w << " " << s+G(H(s)*w) << endl;
}

main() {
  st();
  //ghs();
  //ghw();
}
::::::::::::::
cerr2file.cpp
::::::::::::::
#include 
#include 
#include 
#include 
//#include 
//#include 
//#include 
//#include 
#include 
 
Log1()
{
  cerr << "out" << endl;
  cout << "out" << endl;
  //  &cerr 
  // ofstream o = new ofstream("cerr.log");
  // use fileno to get the file descriptor
  // or user open:
  int fd1 = open("cout.log", O_WRONLY | O_CREAT | O_TRUNC, 1);
  int fd2 = open("cerr.log", O_WRONLY | O_CREAT | O_TRUNC, 0777);
  //int fd = creat("cerr.log");
  // close(STDOUT_FILENO);
  dup2(fd1, STDOUT_FILENO);
  dup2(fd2, STDERR_FILENO);
  cerr << "out to cerr" << endl;
  cout << "out to cout" << endl;
  close(fd1); close(fd2);
}

Log2()
{
  dup2(open("cerr.log", O_WRONLY | O_CREAT | O_TRUNC, 0777), STDERR_FILENO);
  cerr << "out to cerr" << endl;
}

main() 
{
  Log2();
}
::::::::::::::
cin-input.cpp
::::::::::::::
#include 
#include 

void ReadInt(int &i)
{
  char c;
  cout << "$ " << "[" << i << "]" << ":";
  cin.unsetf(ios::skipws); // read also white space
  // get rid of white space
  for(c=cin.peek();c==' '||c=='\t';c=cin.peek()) cin.ignore(1);
  if (c == '\n') { 
    cin >> c; cout << "You want the default!" << endl; }
  else {
    cin.setf(ios::skipws); // overlook leading white space
    cin >> i;
    if (!cin) { 
      cout << "You typed some fuck! Try again." << endl; i=i; cin.clear(); }
    cin.unsetf(ios::skipws); // read also white space
    for(cin >> c;c != '\n';cin >> c); // read the ws and the trailing \n 
  }
  cout << "i= " << i << endl;
}

main()
{
  int i=17;
  do {
    ReadInt(i);
  } while (i);
}
::::::::::::::
cin-input-string.cpp
::::::::::::::
#include 
#include 

void ReadString(int &i)
{
  char c;
  cout << "$ " << "[" << i << "]" << ":";
  cin.unsetf(ios::skipws); // read also white space
  // get rid of white space
  for(c=cin.peek();c==' '||c=='\t';c=cin.peek()) cin.ignore(1);
  if (c == '\n') { 
    cin >> c; cout << "You want the default!" << endl; }
  else {
    cin.setf(ios::skipws); // overlook leading white space
    cin >> i;
    if (!cin) { 
      cout << "You typed some fuck! Try again." << endl; i=i; cin.clear(); }
    cin.unsetf(ios::skipws); // read also white space
    for(cin >> c;c != '\n';cin >> c); // read the ws and the trailing \n 
  }
  cout << "i= " << i << endl;
}

main()
{
  char cS[32];
  cin >> cS;
  cout << cS<< endl;
}
::::::::::::::
Con-Destructor.cpp
::::::::::::::
#include

class A 
{
public:
  A() {; fprintf(stdout,"con-A,x:%i\n", x); }
  A(char c){  x = c; fprintf(stdout,"con-A,x:%i\n", x); } 
  ~A(){ fprintf(stdout,"des-A\n"); }
  char x;
};

 class B : public A
{
public:
  B(char c, char cc) : A(c) 
   { x = cc; fprintf(stdout,"con-B,x:%i\n", x); }
  ~B(){ fprintf(stdout,"des-B\n"); }
};

main()
{
  A* a = new A(1);
  B* b = new B(2,3);
  delete a;
  delete b;
}
::::::::::::::
ConsructorPara.cpp
::::::::::::::
#include

class A
{
public:
  A(char c) { a = c; cout << "Con A\n"; }
  A()   // called by constructor B()
  { cout << "Con A()\n"; 
  // A::A('a'); // this leads to a destructor call
  }
  ~A() { cout << "Des A()\n"; }
  char a;
protected:
  char pra;
};

class B : public virtual A
{
public:
  B(char c, char cc) : A(c) { cout << "Con B\n"; }
  B() { cout << "Con B()\n"; } // called by class D
  ~B() { cout << "Des B()\n"; }
};

class C : public virtual B
{
public:
  C(char c, char cc, char ccc) //: B(c, cc)
  { cout << "Con C\n\n"; }
  ~C() { cout << "Des C()\n"; }
};

class D : public virtual B //, public virtual A
{
public:
  // To call A(c) from D we need A to be a virtual child of B.
  D(char c, char cc, char ccc) : A(c), A::a('d'),  string("string")
    // A(c) in the init list here leads to a call of A(char) instead of
    // A() as the constructor parameters are different. Calling 
    // both constructors is not possible, also not in class A itself
    // (no tricks possible here!!, one constructor that's it!).
  { cout << "Con D\n"; 
  // A::A(c); // this leads to a destructor call (for a tmp A instance)
  }
  ~D() { cout << "Des D()\n"; }
  char* string;
};

class X
{
public:
  X();
};

X::X() {}

main()
{
  A AA; // no brackets here !! no: A A();
  cout << " virtual test:\n";
  cout << "Init A...\n"; A A('a'); 
  cout << "Init B...\n"; B B('b','b'); 
  cout << "Init C...\n"; C C('c','c','c'); 
  cout << "Init D...\n"; D D('d','d','d');
  // some variable tests
  cout << D.a << endl;
  // cout << D.string << endl;
  cout << ".. and destroy it again." << endl;
}

::::::::::::::
continue.cpp
::::::::::::::
#include 

main() {
  for(int i=0;i<10;i++) {
    if(i==3) continue;
    cout << i << endl;
  }
}
::::::::::::::
coutFromat.cpp
::::::::::::::
// use g++ not gcc
#include 
#include 
#include 

main()
{
  bool b = true; cout << "bool b: " << b << endl; 
  cout << "aaa" << setw(10) << "bbb" << "ccc" << endl; 
  cout << "a" << flush << "b" << endl; 
  cout.precision(5);
  //cout.setf(ios::internal, ios::adjustfield);
  cout.setf(ios::showpos);
  cout.setf(ios::showpoint);
  //cout.setf(ios::right, ios::adjustfield);
  cout.fill('*');
  //cout.setf(ios::scientific, ios::floatfield);
  // cout.setf(ios::);
  cout.setf(ios::left, ios::adjustfield);
  cout.width(10);
  cout 
    << "abbd: " << 0.0 << "\t" << 0 << "\t"<< 0 << "\n";
  cout 
    << "asbd: " << -12312.12344 << "\t" << 3434.23423 << "\t" << 0 << "\n";
  for(int i=0; i<6;i++) {
    cout.width(5);
  cout << 1 << 19 << " \n";
    cout.fill(' ');
    cout.width(11);
    cout << setw(11) << 0.0 << " \n";
    cout << 4.458290e-09 << " \n";
  }
  cout << "------" << endl;
  cout << 4.4582902342342424234 << endl;
  cout.precision(25);
  cout << 4.4582902342342424234 << endl;
  cout << 4.4582902342342424234 << endl;
}
::::::::::::::
CreatePatternProtein2DTest.cpp
::::::::::::::
#include 
#include 
#include 
#include 

main() {
  srandom((unsigned)time(NULL)); 
  //while(1)cout<<((long)time(NULL))<MinPat) NbPat+=(unsigned int)fmod(random(),MaxPat-MinPat);
    for(unsigned int i=0;iNbPat-1) Out|=0; else Out|=In[i+dT];
      cout<
#include 
#include 
#include 

// not madatory (for more than one WINDOW (buffer) on ascreen)
WINDOW *AppWindow; 
SCREEN *AppScreen, *ControlScreen;
int i;

main()
{
  // get a second term
  if (!(ControlScreen = 
    newterm("xterm" , stdout, stdin))) 
    cout << "newterm error!" << endl;
  initscr();
  //if (!(AppScreen = set_term(ControlScreen)))
  //cout << "set_term error!" << endl;
  for (i=0;i<1;i++) wprintw(stdscr, "hallo stdscr\n");
  for (i=0;i<1;i++) printw("hallo\n");
  refresh();
  //for(;;);
  // addch
  // newterm();
  // initscr,cbreak,noecho;
  // nonl,intrflush(stdscr,FALSE),keypad(stdscr,TRUE);
  

  // stdscr

  //newwin(3X)
 
  // delete and reset ControlSreen
  if (endwin() == ERR) cout << "endwin error!" << endl;
  //  delscreen(ControlScreen);
}
::::::::::::::
curses.cpp
::::::::::::::
// compile with : g++ curses.cpp -lcurses
// see: man curses
//#include  // already included in curses.h
#include 
#include 
#include 
#include 

// not madatory (for more than one WINDOW (buffer) on ascreen)
WINDOW *AppWin, *ControlWin, *OneMoreWin; 
int i, x, y;

main()
{
  // opens a window named stdscr and clears the screen
  if (!(initscr())) cout << "initscr error!" << endl; 
  getmaxyx(stdscr, x, y); // x=rows y=cols
  // clearok(curscr, TRUE); // global clear before write behavior
  wprintw(stdscr, "hallo stdscr: %u %u",x ,y);
  wmove(stdscr,10,10); printw("(10,10)");
  wrefresh(stdscr); sleep(1); // must be called to flush the buffer (window)
  // get a new window (buffer)
  if (!(ControlWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  wmove(ControlWin,10,13); wprintw(ControlWin, "hallo ControlWin");
  wrefresh(ControlWin); sleep(1);
  // get one more new window (buffer)
  if (!(OneMoreWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  mvwprintw(OneMoreWin,14,4, "OneMoreWin");
  mvwprintw(OneMoreWin,14,4, "xxxxxx");
  wrefresh(OneMoreWin); sleep(1);
  clearok(ControlWin, TRUE); wrefresh(ControlWin); sleep(1);
  wclear(stdscr); wrefresh(stdscr); sleep(1);
  overlay(ControlWin, OneMoreWin);
  wrefresh(OneMoreWin); sleep(1);
  /*
  //wrefresh(AppWin); // must be called to flush the buffer
  wmove(AppWin,10,10); for (i=0;i<1;i++) printw("(10,10)");
  wrefresh(AppWin);
  //cout << "c++ test" << endl;
  sleep(1);
  // get a new window (buffer)
  if (!(ControlWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  // wclear(ControlWin);
  wmove(ControlWin,10,13); wprintw(ControlWin, "hallo ControlWin");
  clearok(ControlWin, TRUE); // make it clear a screen with undefined content
  wrefresh(ControlWin);
  sleep(1);
  // get one more  new window (buffer)
  if (!(OneMoreWin = newwin(y,x,0,0))) cout << "newwin error!" << endl;
  // wclear(ControlWin);
  mvwprintw(OneMoreWin,14,4, "OneMoreWin");
  clearok(OneMoreWin, TRUE);
  wrefresh(OneMoreWin);
  sleep(1);
  // switch back
  wrefresh(ControlWin);
  sleep(1);  
  // the AppWindow does not realy store its stuff, it changes with the 
  // actual screen
  wrefresh(AppWin);
  sleep(1);
  */
  // delete windows and reset stdscr
  //delwin(OneMoreWin);
  delwin(ControlWin);
  if (endwin() == ERR) cout << "endwin error!" << endl;
}
::::::::::::::
curses-simple.cpp
::::::::::::::
// compile with : g++ curses.cpp -lcurses
// see: man curses
//#include  // already included in curses.h
#include 
#include 
#include 
#include 

// not madatory (for more than one WINDOW (buffer) on ascreen)
WINDOW *AppWin, *ControlWin, *OneMoreWin; 
int i, x, y;

main()
{
  // should only be called once per application
  // opens a window on stdscr (so AppWin is redundant)
  if (!(AppWin = initscr())) cout << "initscr error!" << endl;
  getmaxyx(AppWin, x, y); 
  start_color(); 
  init_pair(3, COLOR_RED, COLOR_BLACK);
  wattron(AppWin, COLOR_PAIR(3));
  wattron(AppWin, A_REVERSE);
  //wrefresh(AppWin);
  // clearok(curscr, TRUE); // global clear before write behavior
  for (i=0;i<1;i++) wprintw(AppWin, "hallo AppWindow\n");
  wattroff(AppWin, A_REVERSE);
  for (i=0;i<1;i++) wprintw(stdscr, "hallo stdscr/n");
  for (i=0;i<1;i++) printw("hallo\n");
  printw("%u %u",x ,y);
  //wrefresh(AppWin); // must be called to flush the buffer
  wmove(AppWin,10,10); for (i=0;i<1;i++) printw("(10,10)");
  wrefresh(AppWin);
  //cout << "c++ test" << endl;
  sleep(1);
  // get a new window (buffer)
  if (!(ControlWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  // wclear(ControlWin);
  wmove(ControlWin,10,10); wprintw(ControlWin, "hallo ControlWin");
  clearok(ControlWin, TRUE); // make it clear a screen with undefined content
  wrefresh(ControlWin);
  sleep(1);
  // get one more  new window (buffer)
  if (!(OneMoreWin = newwin(y,x,0,0))) cout << "newwin error!" << endl;
  // wclear(ControlWin);
  mvwprintw(OneMoreWin,14,4, "OneMoreWin");
  clearok(OneMoreWin, TRUE);
  wrefresh(OneMoreWin);
  sleep(1);
  // switch back
  wrefresh(ControlWin);
  sleep(1);  
  // the AppWindow does not realy store its stuff, it changes with the 
  // actual screen
  wrefresh(AppWin);
  sleep(1);
  // delete windows and reset stdscr
  delwin(OneMoreWin);
  delwin(ControlWin);
  if (endwin() == ERR) cout << "endwin error!" << endl;
}
::::::::::::::
delete-test.cpp
::::::::::::::
#include 

int* pi1; 
int* pi2;

main()
{
  pi1 = new int(1);
  pi2 = new int(2);
  void* p;
  p = NULL;
  delete pi1; // can!!! lead troube, but not always !@#&!
  delete pi2; pi2 = NULL;
  delete pi2; // fine (there is a check for NULL).
  delete pi1; free p1;// .... hmm, nothing happens! (but if someone else
  // uses the space in the meantime -> @!#$%#!).
  cout << "pi1: " << ((void*)pi1) << " = " << *pi1 << endl
       << "pi2: " << ((void*)pi2) << " = " 
    // << *pi2 // leads to seg-violation
       << endl
       << p << endl;
}
::::::::::::::
Destructor.cpp
::::::::::::::
#include
#include


// be aware of pointers to virtual inherited parts of classes
class A 
{
public:
  A() { cout << "Con A\n"; ia=17; }
  virtual ~A(){ ia=76; cout << "Des A\n"; }
  int ia;
};

class B : public A
{
public:
  B() { cout << "Con B\n"; }
  virtual ~B(){ cout << "Des B\n"; }
};

class C :  public B
{
public:
  C() { cout << "Con C\n"; ia=9; }
  virtual ~C(){ cout << "Des C\n"; }
  void fonc() { cout << "do nothing"; }
  char s[1024]; // to see if it lasts
};

main()
{
  //cout << "new A...\n"; A* a = new A();
  cout << "new B...\n"; B* b = new B();
  delete b; exit(0);
  cout << "new C...\n"; C* c = new C();
  //cout << "del A...\n"; delete a;
  A* xa = (A*) c; // type convertion
  B* xc = (B*) c; // type convertion  
  // x = (B*) x; // back convertion not nessecairy
  // Des B is called only when destructors are virtuall
  cout << xa << " xa->ai: " << xa->ia << endl;
  cout << xc << " xc->ai: " << xc->ia << endl;
  cout << c << " c->ai: " << c->ia << endl;
  strcpy(c->s, "string");
  char* cs = c->s;
  cout << cs << endl;
  cout << "del xa...\n";  delete xa; 
  cout << xc << " xc->ai: " << xc->ia << endl;
  cout << "del xc...\n";  delete xc; 
  cout << xa << " xa->ai: " << xa->ia << endl;
  cout << xc << " xc->ai: " << xc->ia << endl;
  cout << c << " c->ai: " << c->ia << endl;
  /*
  cout << "del c...\n" delete c;
  cout << cs << endl;
  //free(cs);
  delete cs;
  free(cs);
  strcpy(cs, "writeToit");
  cout << cs << endl;
  */
  // see if it grows
  while(true) { C* c = new C(); xa = (A*) c; delete xa; }
  
}
::::::::::::::
DosUnixCR.cpp
::::::::::::::
#include 
#include 

main() { 
  ofstream f;// = new ofstream("test.out");
  f.open("test.out");
  f<<"conrolM \r";
  f.close();
}
::::::::::::::
double.cpp
::::::::::::::
#include 
#include 

main() {
long double d;
cout << sizeof(d) << endl;

}
::::::::::::::
drand48-test.cpp
::::::::::::::
# random and srandom is better
#include 
#include 
#include 
#include 

  float f, min, max;
  int i,ii;

Double_Test()
{
  for(ii=0;ii<2;ii++) {
    for(i=0;i<100000;i++) {
      /* range -1 to 1 ; open interval */
      f = (float) (drand48()*2-1);
      if (i==0) { min=0.5; max=0.3; }
      if (f>max) max=f;
      if (f=limit) exit();
  }
 cout<<"Done.";
}

InitSeed() {
  // init random generator
  time_t t;
  long lseed = (long) time(&t);
  srand48(lseed);
}

main() { IntTest(); }
::::::::::::::
enum.cpp
::::::::::::::
#include 
#include 

enum color { yellow, red, blue } Fiat=blue;
enum color CarCol;

Function(enum color aeCar)
{
  int i;
  CarCol = aeCar; cout << CarCol << "\n";
  cin >> i; CarCol = (enum color) i; cout << CarCol << "\n";
  // cin >> (enum color) CarCol; cout << CarCol << "\n";
} 

main()
{
  CarCol = red;
  cout << CarCol << "\n";
  // Fiat = blue;
  cout << Fiat << "\n";
  // #### color = red;
  Fiat = (enum color) 1;
  cout << Fiat << "\n";
  Function(Fiat);
  Function((enum color) 2);
}

::::::::::::::
exp.cpp
::::::::::::::
#include 
#include 
#include "/home/felix/c-cpp/BaseClasses/MathMacros.h"

  
main() {
  double e,E,s,S,SS;
    cout.precision(10); 
    for(double i=-1.5;i<1.5;i+=0.001) {
    e=exp(i); E=EXP(i);
    s=2/(1+exp(-i))-1; S=2/(1+EXP(-i))-1; SS = 2*LOGC(i)-1;
    //cout << "i:" << i << " e:" << e << " E:" << E << " e-E:" << e-E << " ,";
    //cout << " s:" << s << " S:" << S << " s-S:" << s-S << " ,\n ";
    cout << i << " " << s << " " << S << " " << SS << "\n";
    //cout << i << " " << S-s << "\n";
    cout.flush();
  }
}
::::::::::::::
FastExp.cpp
::::::::::::::

#include 
#include 
#include "Error.h"

static union {
  double d;
  struct {
    // machine dependent storage of multi-byte quantities.
#ifdef LITTLE_ENDIAN
    int j, i;
#else
    int i, j;
#endif
  } n;
} _eco;

#define EXP(y) ((_eco.n.i = (int)(1512775*(y)) + 1072632448,_eco.n.j=0),\
 _eco.d)

main() {
  double y = 3.0234234, ey = exp(y), Ey = EXP(y),de=0,rde=0 ;
  int iRange=10;
  de=0;rde=0;
  for(y=-iRange;y
#include 
#include 
#include 
#include 
#include 
#include  //MAXPATHLEN
#include 

struct stat buf;

main(int argc, char *argv[]) {
  if(argc < 2) { printf("usage: file to query\n"); exit(1); }
  if(lstat(argv[1], &buf) < 0) { printf("lstat errror\n"); }//exit(1); }
  if(S_ISREG(buf.st_mode)) {
    printf("regular file.\n");
    printf("size %i\n", (int) buf.st_size);
  }
     else printf("no regular file.\n");
  // read the directory
  char cPathname[MAXPATHLEN];
  getcwd(cPathname, MAXPATHLEN);
  printf("ls dir: %s\n", cPathname);
  DIR *dir;
  struct dirent *dr;
  dir = opendir(".");
  while(dr = readdir(dir)) {
    printf("%s\n", dr->d_name);
    if(strstr(dr->d_name, argv[1])) {
       printf("sub-string %s found in %s!\n", argv[1], dr->d_name);
       break;
    }
    if(!strcmp(argv[1], dr->d_name)) {
       printf("file %s found !\n", argv[1]);
       break;
    }
  }
  closedir(dir);
}
::::::::::::::
file-status.cpp
::::::::::::::
// use g++ not gcc
#include 
#include 

main()
{ 
  int i1=0, i2=0, i3=0;
  float l;
  double d;
  fstream *f = new fstream();
  cout << "start-state: " << f->rdstate() << endl;
  // f->open("f-test", ios::in | ios::out );
  f->open("f-test");
  cout << "open-state: " << f->rdstate() << endl;
  *f << "test143\n"; f->tellg(); f->tellp();
  cout << "used-state: " << f->rdstate() << endl;
  f->close();
  cout << "close-state: " << f->rdstate() << endl;
  f->tellg();
  cout << "misused-state: " << f->rdstate() << endl;
  f->clear();
  *f << "test666\n";
  cout << "misused-state: " << f->rdstate() << endl;
  f->clear();
  cout << "cleared-state: " << f->rdstate() << endl;
  // open..close .. ..100 times
  cout << " open..close....." << endl;
  for(i1=0;i1<100;i1++) {
    f->open("f-test", ios::in | ios::out ); f->close();
  }
 delete f;
}
::::::::::::::
file-stream-test.cpp
::::::::::::::
#include 
#include 
#include 
#include 

void FlieIO();

void FileIO()
{
  int i1, i2, i3;
  ifstream f;// = new ifstream("test");
  f.open("test");
  f >> i1;
  f.ignore(1000, ':');
  f >> i2;
  if (! f.good()) { cout << "error"; f.clear(); }
  f.ignore(1000, ':');
  f >> i3;
  cout << i1 << "," << i2 << "," << i3;
}

main()
{ 
 FileIO();
 return 0;
 char c;
  int  i;
  while(c != 'q') {
    cin >> resetiosflags(ios::skipws) >> c;
    cout << ":" << c << ":\n";
    if (c != '\n') cin.putback(c);
    if (cin >> i) cin >> c; // read the non digits
    cout << "|" << i << "|\n";
    cin >> resetiosflags(ios::skipws) >> c; // kill the remaing \n
    cin.clear();
  }
}
::::::::::::::
floatingPointPrecision.cpp
::::::::::::::
#include 
#include 

main() {
  printf("FLT_DIG: %d\n", FLT_DIG);
  printf("DBL_DIG: %d\n", DBL_DIG);
  printf("LDBL_DIG: %d\n", LDBL_DIG);
}
::::::::::::::
fmod++.cpp
::::::::::::::
#include 
#include 
#include 
#include 

main()
{
  cout << fmod(7,0) << endl;
  cout << -1 % 7 << 1 % 7 << endl;  
  int i,ii=0;
  for(i=0;i<20;i++) {
    cout << "i: " << i << "\t" << "ii: " << ii << "\t"
	 << "fmod: " << fmod(ii, 7) << "\t"
         << "++fmod: " << fmod(++ii, 7) << "\t"
	// << "fmod++: " << fmod(ii++, 7) << "\t"
	 << "ii: " << ii << "\n";
  }
}
::::::::::::::
folgen.cpp
::::::::::::::
#include 
#include 

main() {
  double s0,s,s1,s2,s3,y,x,p,g;
  s0 = -0.1; s=s0; s1=s; s2=s; s3=s;
  y = 0.9;
  x = 3;
  p=1/(1+exp(-x));
  g=exp(x);
  for(int i=0;i<1000;i++) {
    //cout << i << " " << s << " " << s1 << " " << s/s1 << endl;
    //cout << i << " " << s << " " << s1 << " "<< s2 << " "<< s3 << endl;
    cout << i << " " << s << endl;
    //s2=s1; s1=s;
    //s = log(s+1)+((s)-log(s+1))*y;// sqrt(x+s);//s/(1+s/exp(x));//n 0.01*n;
    // Extrem nonlinear in y -> almost linar deacy + good switch.
    //s=log(exp(s)*pow(y,1/y)+1)-log(exp(-s)*pow(y,1/y)+1);
    // Combine 'brokenpoly' with forget gate net input.
    // The time constant gets exponetial.
    s=s/(1+fabs(s)/exp(x));
    s1=s1/(1+1/exp(x));
    s2=g*s0/(g+s0*(i+1));
    s3=pow(p,i+1)*s0;
    // The same linear for pre squashed gate activation.
    //s=s/(1+fabs(s)/y);
  }
}
::::::::::::::
for.cpp
::::::::::::::
// use g++ not gcc
#include 
#include 
#include 
 
main()
{
  for(int i=-1;i<10;i++) cout << i << endl;
  int ii =1; for(int i=0;i

// friendship is not inherited !!
// To use a friends private fields you need an instance of the friend or
// the friend must be a chield.
class B;

class X { friend B; 
public:
  X() { cForFriendsAndThereChilds = 'x'; }
  char cPublic;
protected:
  char cForFriendsAndThereChilds;
  // void testBsFriendship() { bc = 'x'; }
};

class A : public X {};

class B : public A { friend X; // also X can work with B's private stuff
public:
  X pX;
  char c;
  void testFriendship() { 
    c = pX.cPublic;
    c = pX.cForFriendsAndThereChilds;
    cForFriendsAndThereChilds = 'b'; 
    c = cForFriendsAndThereChilds;
  }
private:
  char bc;
};

main()
{
  X x; A a; B b;
  //  x.cForFriendsAndThereChilds=7;
  // b.c = b.cForFriendsAndThereChilds;
  b.testFriendship();
  fprintf(stdout,"b.c: %c\n", b.c);
  //fprintf(stdout,"b.cForFriendsAndThereChilds: %c\n", 
  //  b.cForFriendsAndThereChilds);
  // b.pX = &x;
  // b.c = b.pX->cForFriendsAndThereChilds;
  // fprintf(stdout,"%c\n", b.c);
}
::::::::::::::
FuncPatView.cpp
::::::::::::::
#include 
#include 
#include 
#include 

int iVal,i,pos=30;
ifstream f;

main() {
  cout << endl;
  f.open("/home/felix/c-cpp/RNN/ResultTrain.pat");
  while(f.good()) {
    iVal=0; for(i=-2;!iVal&&f.good();i++) f >> iVal; f.ignore(1000, '\n');
    pos+=i; 
    cout << setw(pos) << 0 <

int func(int k) { cout << "f\n" << k << endl; return k; }

class S {
public:
  S(char cc[], void (*ffp)() ) { strcpy(c,cc); fp = ffp; }
  char c[5];
  void (*fp)();
};

main() {
  int (*fp)(int);
  fp = &func;
  int i = fp(13);
  fp(17);
  cout << i << endl;
  S s("func",(void (*)()) &func);
  if(strcmp(s.c,"func")==0) ((int (*)(int))(s.fp))(101);
}
::::::::::::::
GetWorkingDirectory.cpp
::::::::::::::
#include 
#include 
#include 
#include 

main() {
  char cPathname[MAXPATHLEN];
  getcwd(cPathname, MAXPATHLEN);
  cout << "Actual directory: " << cPathname << "\n";
}
 
::::::::::::::
GnuPlot-Pipe.cpp
::::::::::::::
#include
#include
#include
#include
#include
#include
#include // for mkfifo
#include
#include

#define BufSize 256
#define GNU_GEOMETRY "450x450+300+20"
 
int n, fd[2];
pid_t pid, WaitStatus;
char cBuf[BufSize];
char* program = "/usr/local/bin/gnuplot";
char cOpt[64] = "";//"gnuplot.gp";


HandmadePipeToGnuPlot()
{
  FILE *fd2FILE, *fd02FILE;
  if(pipe(fd) < 0) cout << "pipe error!" << endl;
  if((pid = fork()) < 0) cout << "fork error!" << endl;
  else if(pid > 0) { // parent (child gets a 0 as pid)
    cout << "parent" << endl;
    // get a file object for the file descriptor
    if (!(fd2FILE = fdopen(fd[1], "w"))) 
      cerr << "fdopen error!" << endl;
    if (!(fd02FILE = fdopen(STDIN_FILENO, "w"))) 
      cerr << "fdopen error!" << endl;
    fprintf(fd02FILE, "20\n");
    close(fd[0]);
    // write(fd[1], "hello\n", 6);
    do {
    sleep(1);
      if ((WaitStatus = waitpid(pid, NULL, WNOHANG)) < 0) 
        cout << "waitpid error" << endl;
      if (WaitStatus == 0) {
        //cout << "child not terminated" << endl;
        //kill(pid, SIGINT);
	strcpy(cBuf, "pause 0 'togp'\n");
	//strcpy(cBuf, "load 'gnuplot.gp'\n");
	n = strlen(cBuf);
	//write(STDOUT_FILENO, "load 'gnuplot-data.gp'", BufSize);
	//write(fd[1], cBuf, n);
	//write(fd[1], "hello\n", 6);
	fprintf(fd2FILE, "pause 0 'togp'\n"); fflush(fd2FILE);
	fprintf(fd2FILE, "plot 'test-data.gp-dat'\n"); fflush(fd2FILE);
      } 
    } while (WaitStatus <= 0);
    if (WaitStatus > 0) {
      cout << "child terminated status: " << WaitStatus << endl;
    }
  } else  { // child
    cout << "child" << endl;
    close(fd[1]);   
    //n = read(fd[0], cBuf, BufSize);
    //write(STDOUT_FILENO, cBuf, n);
    // cout << cBuf << endl;
    // set standard in
    if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO) 
      cout << "dup2 error!" << endl;
    cout << "child exec" << endl;
    //execlp("echo", "echo", "hi", "hdi",(char *) 0 ); 
    //execlp(program, program, (char *) cOpt, NULL); 
    execlp(program, program, NULL);
    //execl(program, program, (char *) cOpt,(char *) 0 );
    write(STDOUT_FILENO, "load 'gnuplot-data.gp'", BufSize);
    cout << "ready to exit pid : " << pid << endl;
    exit(0);
  }
  exit(0);
}  

void bailout(char *s){ perror(s); exit(1); }
#define GNU_GEOMETRY "450x450+300+20"
FIFOPipeToGnuPlot()
{
  int childPid, result;
  char gnuCommands[256] = { "/tmp/gnuplot.input" };
  char gnuData[256] = { "/tmp/gnuplot.data" };
  FILE *gnustr,*gnudat;
 
  sprintf(gnuCommands + strlen(gnuCommands), ".%d", getpid() );
  result = mkfifo(gnuCommands, 0666);
  if(result) bailout("mkfifo ");
 
  sprintf(gnuData + strlen(gnuData), ".%d", getpid() );
  result = mkfifo(gnuData, 0666);
  if(result) bailout("mkfifo ");
 
  childPid = fork();
  if(childPid == -1) bailout("fork ");
  if(!childPid){
    execlp("gnuplot", "gnuplot", "-geometry", 
           GNU_GEOMETRY, gnuCommands, NULL); 
    bailout("execlp "); 
  } else {
    gnustr = fopen(gnuCommands, "w");
 
/*    fprintf(gnustr, "set term tek40xx\n");  /* or whatever */
 
    /* send some commands to the command pipe */
    fprintf(gnustr, "set samples 200\nset xrange[-4*pi:4*pi]\n");
    for(result = 1; result < 5; result++){
      fprintf(gnustr, "plot sin(x/%d)*cos(%d*x)\n", result, result);
      fflush(gnustr);
      sleep(2);
    }
 
    /* now put commands in command pipe
       and data in data pipe */
    fprintf(gnustr,"set data style lines\n");
    fprintf(gnustr,"set xrange[0:10]\nset yrange[0:100]\n");
    fprintf(gnustr,"plot '%s' w l %d\n", gnuData, result);
    fflush(gnustr);
 
    /* this fopen must occur AFTER gnuplot has already
       tried to open the pipe for reading */
    gnudat = fopen(gnuData, "w");
    if(!gnudat) bailout("fopen");
    for(result = 0; result <= 10; result++) 
      fprintf(gnudat,"%d %d\n", result, result*result);
 
    fclose(gnudat);
    unlink(gnuData);
    sleep(3);
 
    fclose(gnustr);
    kill(childPid, SIGKILL); 
    unlink(gnuCommands);
  }
}

int PopenPipeToGnuPlot(char command[100], FILE *&pstream) {
  //int gnucmd(char command[100], FILE *pstream){
  char GNUPLOT[50];
  /* open the pipe */
  if(pstream == NULL){
    strcpy(GNUPLOT,"gnuplot");
#ifdef OS2 
    strcpy(GNUPLOT,"gnuplot 2> gnuout");
#endif
    /* under UNIX, this rather complicated command string is needed. */
    /* If modified, you should comment this one out and make another */
    /* so you can go back to this one if needed. */
    /* Things work pretty well with just a "gnuplot" command, */
    /* except that some of the things gnuplot writes to stderr */
    /* make it to the user's screen.  Simply using "gnuplot >& gnuout" */
    /* does not work, because popen() uses sh commands, and  */
    /* "gnuplot >& gnuout" uses csh redirection. */
#define UNIX 
#ifdef UNIX 
    //strcpy(GNUPLOT,"/bin/csh -f -c \"gnuplot >& /tmp/gnuout\""); 
    strcpy(GNUPLOT,"gnuplot");
    cout << ": " << GNUPLOT << endl;
#endif
    pstream = popen(GNUPLOT,"w"); // use pclose(FILE* fp) to close pipe
    if(pstream == NULL){
      printf("Failed to open pipe to gnuplot\n");
      return 1;
    }
  }
    fprintf(pstream, command);
    fflush(pstream);
    return 0;
}

char DisplayDataFileWithGnuPlot(char *DataFileName) {
  FILE *GnuPlotPipe = NULL;
  // opens a pipe (with
  if (!GnuPlotPipe) GnuPlotPipe = popen("gnuplot","w");
  if (!GnuPlotPipe) return 1;
  fprintf(GnuPlotPipe,"plot '%s'\n", DataFileName ); fflush(GnuPlotPipe);
  cout << "sleep" << endl; sleep(2);
}

test_PopenPipeToGnuPlot() {
  FILE *TOGP = NULL;
  //PopenPipeToGnuPlot("load 'gnuplot-data.gp'",TOGP);
  PopenPipeToGnuPlot("plot 'test-data.gp-dat'\n",TOGP);
  //PopenPipeToGnuPlot("pause 3 'pause 3'\n",TOGP);
  //PopenPipeToGnuPlot("pause -1 'pause -1'\n",TOGP);
  cout << "sleep" << endl; sleep(2);
  PopenPipeToGnuPlot("plot 'test-data01.gp-dat'\n",TOGP);
  cout << "sleep" << endl; sleep(2);
  PopenPipeToGnuPlot("\n",TOGP);
  pclose(TOGP);
  cout << "sleep again" << endl; sleep(2);
}

main() {
 DisplayDataFileWithGnuPlot("test-data01.gp-dat");
}
::::::::::::::
if++.cpp
::::::::::::::
#include 
 
main()
{
  int i=0,ii=0, iii=0, k[3]={4,5,6};
  if(i++) cout << "i: " << i << endl;
  if(++ii) cout << "ii: " << ii << endl;
  cout << k[iii++] << " iii: " << iii << endl;
  iii=0;
  cout << k[++iii] << " iii: " << iii << endl;

}
::::::::::::::
ifdef.cpp
::::::::::::::
#include 
#include 

#define debug
//#define fuck

main()
{
#ifdef fuck
  cout << "fuck\n";
#ifdef debug
  cout << "debug\n";
#else
  cout << " not debug\n";
#endif
#endif
exit(0);
#ifndef debug
  cout << " not debug\n";
#ifdef fuck
  cout << "fuck\n";
#endif
#else
  cout << "debug\n";
#endif
  exit(0);
  #if defined(debug) && defined(fuck)
  cout << "debug'nfuck\n";
  #else
    #ifdef debug
    cout << "debug\n";
    #elif defined(fuck)
    cout << "fuck\n";
    #else
    cout << " not debug\n";
    #endif
  #endif
  // but not in one line
  //   #ifdef fuck  cout << "fuck.\n"; #endif
}
::::::::::::::
IO-template.cpp
::::::::::::::
#include 
#include  // system
#include  // sleep 


template  X ReadAnything(const char* acInfo,X &x);
template  X ReadAnythingNoRef(const char* acInfo,X x);

template  X  
ReadAnything(const char* acInfo, X &x) {
  char c;
  bool bValueValid = false;
  system("clear"); cout << acInfo;
  while(!bValueValid) {
    cout << "[" << x << "]" << ": ";
    cin.unsetf(ios::skipws); // read also white space
    // get rid of white space
    for(c=cin.peek();c==' '||c=='\t';c=cin.peek()) cin.ignore(1);
    if (c != '\n') { // cout << "You don't want the default!" << endl; 
      cin.setf(ios::skipws); // overlook leading white space
      cin >> x;
      if (!cin) { 
	x=x; cin.clear();  cin.ignore(1000, '\n'); 
        bValueValid = false; 
	cout << "Not a valid value!" << endl; 
	sleep(1); system("clear"); cout << acInfo; continue; 
      } 
    }
    cin.unsetf(ios::skipws); // read also white space
    for(cin >> c;c != '\n';cin >> c); // read the ws and the trailing \n
    bValueValid = true;
  }
  return x;
}
template  X  
ReadAnythingNoRef(const char* acInfo, X x) {
  char c;
  bool bValueValid = false;
  system("clear"); cout << acInfo;
  while(!bValueValid) {
    cout << "[" << x << "]" << ": ";
    cin.unsetf(ios::skipws); // read also white space
    // get rid of white space
    for(c=cin.peek();c==' '||c=='\t';c=cin.peek()) cin.ignore(1);
    if (c != '\n') { // cout << "You don't want the default!" << endl; 
      cin.setf(ios::skipws); // overlook leading white space
      cin >> x;
      if (!cin) { 
	x=x; cin.clear();  cin.ignore(1000, '\n'); 
        bValueValid = false; 
	cout << "Not a valid value!" << endl; 
	sleep(1); system("clear"); cout << acInfo; continue; 
      } 
    }
    cin.unsetf(ios::skipws); // read also white space
    for(cin >> c;c != '\n';cin >> c); // read the ws and the trailing \n
    bValueValid = true;
  }
  return x;
}

main() {
  double d = 13.13;
  cout << "___:" << ReadAnything("Double: ",d) << " " << d << endl;
  sleep(1);
  int i = 17;
  cout << "___:" << ReadAnything("Int: ",i) << " " <<  i << endl;
  sleep(1);
  cout << "___:" << ReadAnythingNoRef("Double: ", 9) << endl;
  char S;
  cout << "___:" << ReadAnything("Char[]: ", i) << " " << S << endl;

}

::::::::::::::
keypressed.cpp
::::::::::::::
#include 
#include  // STDIN_FILENO
#include 
#include  // struct termios
  
struct termios term, termsave;
int size;
char TermName[L_ctermid];
int iBS = 50*50;
char c;
int iReturnValue;

tty_noncanonical(int fd)
{
  if (tcgetattr(STDIN_FILENO, &termsave) < 0) cout << "get error" << endl;
  term = termsave;
  term.c_lflag &= ~(ICANON | ECHO ); // noncanonical and no echo 
  term.c_cc[VMIN] = 0; // buffer size
  term.c_cc[VTIME] = 0;
  if (tcsetattr(fd, TCSANOW, &term) < 0) 
    cout << "set error" << endl;  
}
tty_reset(int fd)
{
  if (tcsetattr(fd, TCSANOW, &termsave) < 0) 
    cout << "set error" << endl;  
}

tty_cbraek(int fd)
{
  term = termsave; 
  term.c_lflag &= ~(ECHO | ICANON | IEXTEN);
  term.c_iflag &= ~(ICRNL | IXON | INPCK);
  term.c_oflag &= ~(OPOST);
  term.c_cc[VMIN] = 1;
  term.c_cc[VTIME] = 0;
  if (tcsetattr(fd, TCSANOW, &term) < 0) 
    cout << "set error" << endl;  
}

char 
Keypressd() {
  c = '_';
  tty_noncanonical(STDIN_FILENO);
  iReturnValue = read(STDIN_FILENO, &c, 1);
  tty_reset(STDIN_FILENO);
  return iReturnValue;
}


char  
KeypressedAllInOne(char &ac) {
  // We are not always in noncanonical mode without local echo, so if
  // a key is pressed "outside" this function (which is likely)
  // it will be echoed.
  struct termios term, termsave;
  int iReturnValue = 0;
  // tty_noncanonical(STDIN_FILENO);
  if (tcgetattr(STDIN_FILENO, &termsave) < 0) cout << "get error" << endl;
  term = termsave;
  term.c_lflag &= ~(ICANON | ECHO ); // noncanonical and no echo 
  term.c_cc[VMIN] = 0; // buffer size
  term.c_cc[VTIME] = 0;
  if (tcsetattr(STDIN_FILENO, TCSANOW, &term) < 0) 
    cout << "set error" << endl;  
  // Check for keypressed
  iReturnValue = read(STDIN_FILENO, &ac, 1);
  // tty_reset(STDIN_FILENO);
  if (tcsetattr(STDIN_FILENO, TCSANOW, &termsave) < 0) 
    cout << "set error" << endl;
  // Done. Return nuber of chars read.
  return iReturnValue;
}


main() {
  // while (!Keypressd());
  // cout << "<" << c << ">" << endl;
  char cc = ' '; int i=0;
  while (cc != 'q') 
    if( (i=KeypressedAllInOne(cc)) ) cout << i << "<" << cc << ">" << endl;
}
::::::::::::::
komma-for-loop.cpp
::::::::::::::
#include 

main() {
  int i, iprev;
  for(i=0,iprev=9;i<10;i++,iprev=i-1)
    cout << "i: " << i << " iprev: " << iprev << endl;
}
::::::::::::::
log2.cpp
::::::::::::::
// given d, what is x, so that d<2**x
#include 
#include 

int log2(int d) { int i=0; while(d>0) { d>>=1; i++;} return i; }
 
main() { for(int d=0;d<260;d++) cout <"<
#include 
#include 
#include 
#include 
#include 

void Func(long double &ld, double d) { ld=d; }
void Fld(long double &d) { d=4/(1+exp(-d))-2; }
void Fd(double &d) { d=4/(1+exp(-d))-2; }
 
main() {
  long double ld, *pld;
  double d;
  pld = new long double;
  cout.precision(50);
  d=0.1234567890123456789012345678901234567890;  
  ld=0.1234567890123456789012345678901234567890;
  *pld = ld;
  Func(ld,d);  
  Fld(ld); Fd(d);  
  cout << "d   " << d << endl;
  cout << "ld  " << ld << endl;
  cout << "pld " << *pld << endl;
  strstream DisplayBuf;
  DisplayBuf.precision(10);
  DisplayBuf << "d   " << d << "\n";
  DisplayBuf << "ld  " << ld << "\n";
  DisplayBuf << ends;
  char* DisplayStr = DisplayBuf.str();
  cout << DisplayStr; cout.flush(); 
  free(DisplayStr);
  cout << "d   " << d << endl;
  cout << "ld  " << ld << endl;
  cout << "pld " << *pld << endl;
  ifstream f; f.open("tt");
  f >> (float) ld;
  f.seekg(0); f >> d;
  cout << "file" << endl;
  cout << "d   " << d << endl;
  cout << "ld  " << ld << endl; 
  ofstream ff; ff.open("t");
  d=0.1234567890123456789012345678901234567890;  
  ff.precision(10); ff << d;
  cout << "file out" << endl;
  cout << "d   " << d << endl; 
  f.close();
  ff.close();
}
::::::::::::::
matherr.cpp
::::::::::::::
#include 
#include 
#include 
#include 
#include 

/*
int matherr(struct exception *x) {
  switch (x->type) {
  case DOMAIN:
    // change sqrt to return sqrt(-arg1), not NaN 
    if (!strcmp(x->name, "sqrt")) {
      x->retval = sqrt(-x->arg1);
      cout << "correct math error." << endl;
      return (0); // print message and set errno 
    } // FALLTHRU 
  case SING:
    // all other domain or sing exceptions, print message and 
    // abort 
    fprintf(stderr, "domain exception in %s\n", x->name);
    abort();
    break;
  }
  return (0); // all other exceptions, execute default procedure 
}
*/

void CheckError()
{
  if(errno) cout << "error" << endl;
  if(errno==EDOM) cout << "EDOM error" << endl;
  if(errno==ERANGE) cout << "ERANGE error" << endl;
  if(!errno) cout << "NO error detecteed" << endl;
  errno=0;
}

main()
{
  double d=1; float f=1; float x, y;
  errno=0;
  f=0; d/=f; 
  cout << "f: " << f << " "; cout << "d: " << d << endl; CheckError();
  x=-1; y=sqrt(x);
  cout << "x: " << x << " "; cout << "y: " << y << endl; CheckError();
}
 
::::::::::::::
Math-Infinity.cpp
::::::::::::::
#include 
#include 

main()
{
  double d=0,dd;
  dd=1/d;
  cout << dd << endl;
  if(dd > 100) cout << dd << " > 100" << endl;
  else cout << dd << " not > 100" << endl;
}

::::::::::::::
math-Operator.cpp
::::::::::::::
#include 
#include 
#include 

main()
{
  double x1=7, x2=3, y;
  y = x1 / x2 * 100;
  cout << "x1: " << x1 << "\n"; 
  cout << "x2: " << x2 << "\n";
  cout << "y: " << y << endl;
}

::::::::::::::
Method-Namespace.cpp
::::::::::::::
#include

class A {
public:
  void Out()  { cout << "A" << endl; }
};

class B : public A {
public:
  void Out()  { cout << "B" << endl; A::Out(); }
};

main() {
  A a; B b;
  a.Out();b.Out();
}

::::::::::::::
method-template.cpp
::::::::::::::
#include 

template  class OUT
{
public:
  X GetOut(X x);
};

template  X
OUT::GetOut(X x) {
  cout << x << endl;
  return x;
}
class OUTAll
{
public:
  // static template  Y GetOutAll(Y y) {return Y;}
};

template  class Printer
{
public:
  Print(X x) { cout << x << endl; }
};

class Include
{
public:
  Printer PInt;
  Printer PFloat;
};

class Inherit : public Printer, public Printer
{
};

main() {
  OUT O;
  O.GetOut(17);
  Include I;
  I.PInt.Print(13);  
  I.PFloat.Print(17.17);
  Inherit H;
  // This is ambiguous
  /*
  H.Print(12.12); is ambiguous
  float f = 12.12; H.Print(f); 
  H.Print(14);
  */
}
::::::::::::::
motif-drawingArea.cpp
::::::::::::::
// Uses Motif.
// gcc -o $1 $1.c -I/usr/dt/include -I/usr/openwin/include -R/usr/dt/lib\
//   -R/usr/openwin/lib -L/usr/dt/lib -lXm -L/usr/openwin/lib -lXt -lX11  


// Standart motif includes.
#include 
#include 
// Motif witgets.
#include  // MainWindow
#include  
#include  
#include  // MenuBar
#include 
#include 
#include 
#include   // drawing area
#include  // canvas
#include       // pixmap box 

// GUI variables
XtAppContext app_context;
Widget topLevel, mainWindow, drawingArea;
GC gc;
XGCValues gc_values;
XtGCMask mask;

void draw_cbk(_WidgetRec *, void *, void *);
void Init_Graphics();

char InitApp(int argc, char** argv) {
  topLevel = XtVaAppInitialize(&app_context, 
			       "XApp",        // application class name
			       NULL, 0,       // command line option list
			       &argc, argv,   // command line args
			       NULL,          // app defaults file
			       XmNwidth, 200,
			       XmNheight, 100,
			       NULL);         // terminate varargs list
  mainWindow = 
    XtVaCreateManagedWidget("mainWindow",           // widget name
			    xmMainWindowWidgetClass,// widget class
			    topLevel,               // parent widget
			    NULL);                  // terminate varargs list
  drawingArea = 
    XtVaCreateManagedWidget("drawingArea",xmDrawingAreaWidgetClass,
 			    mainWindow, NULL);
  // add callback for exposure event
  XtAddCallback(drawingArea, XmNexposeCallback, draw_cbk, NULL);
           
  XtRealizeWidget(topLevel);
  Init_Graphics();
  XtAppMainLoop(app_context);
}

void Init_Graphics() {
  gc_values.foreground = BlackPixelOfScreen(XtScreen(drawingArea));
  gc = XCreateGC(XtDisplay(drawingArea),XtWindow(drawingArea),
		 GCForeground, &gc_values);
}

void draw_cbk(Widget w, XtPointer data, XtPointer call_data) {
  if (!XtIsRealized(drawingArea)) return;  
  XClearWindow(XtDisplay(drawingArea),XtWindow(drawingArea));
  XDrawLine(XtDisplay(drawingArea),XtWindow(drawingArea),gc,10,10,20,20);
}

//// main
main(int argc, char** argv) {
  InitApp(argc, argv);
}
::::::::::::::
motif-pixmap-color-drawing.cpp
::::::::::::::
// Uses Motif.
// gcc -o $1 $1.c -I/usr/dt/include -I/usr/openwin/include -R/usr/dt/lib\
//   -R/usr/openwin/lib -L/usr/dt/lib -lXm -L/usr/openwin/lib -lXt -lX11  


#include 
#include 
#include  // Standard motif.
#include 
#include  // MainWindow
#include  
#include  
#include  // MenuBar
#include 
#include 
#include 
#include   // drawing area
#include  // canvas
#include       // pixmap box

// GUI variables
XtAppContext app_context;
Widget topLevel, mainWindow, drawingArea;
Display *display;
Pixmap pixmap;
GC gc;
XGCValues gc_values;
XtGCMask mask;
int pixmapWidth=200;
int pixmapHeight=200;
String colours[] = { "Black",  "Red", "Green", "Blue", 
                     "Grey", "White"};
long int fill_pixel = 1; // stores current colour of fill - black default
Colormap cmap;
void draw_cbk(_WidgetRec *, void *, void *);
void resize_cbk(_WidgetRec *, void *, void *);
void Init_Graphics();
void set_color(String color);

char InitApp(int argc, char** argv) {
  topLevel = XtVaAppInitialize(&app_context, 
			       "XApp",        // application class name
			       NULL, 0,       // command line option list
			       &argc, argv,   // command line args
			       NULL,          // app defaults file
			       XmNwidth, pixmapWidth,
			       XmNheight, pixmapHeight,
			       NULL);         // terminate varargs list
  mainWindow = 
    XtVaCreateManagedWidget("mainWindow",           // widget name
			    xmMainWindowWidgetClass,// widget class
			    topLevel,               // parent widget
			    NULL);                  // terminate varargs list
  drawingArea = XtVaCreateManagedWidget
    ("drawingArea",xmDrawingAreaWidgetClass, mainWindow,
     XmNresizePolicy,XmNONE,//remain this a fixed size
     NULL);
  // Add callback for exposure event.
  XtAddCallback(drawingArea, XmNexposeCallback, draw_cbk, NULL);
  XtAddCallback(drawingArea, XmNresizeCallback, resize_cbk, NULL);
           
  XtRealizeWidget(topLevel);
  Init_Graphics();
  XtAppMainLoop(app_context);
}

void Init_Graphics() {
  display = XtDisplay(drawingArea);
  // Init color.
  cmap = DefaultColormapOfScreen(XtScreen(drawingArea));
  // Graphics context.
  gc_values.foreground = BlackPixelOfScreen(XtScreen(drawingArea));
  gc = XCreateGC(XtDisplay(drawingArea),XtWindow(drawingArea),
		 GCForeground, &gc_values);
  // Create a pixmap the same size as the drawing area.
  pixmap = 
    XCreatePixmap(XtDisplay(drawingArea),
		  RootWindowOfScreen(XtScreen(drawingArea)), 
		  pixmapWidth, pixmapHeight,
		  DefaultDepthOfScreen(XtScreen(drawingArea)));
  // Clear pixmap with white.
  XSetForeground(XtDisplay(drawingArea), gc,
        WhitePixelOfScreen(XtScreen(drawingArea)));
  XFillRectangle(XtDisplay(drawingArea), pixmap, gc, 0, 0, 
		 pixmapWidth, pixmapHeight);
  XSetForeground(XtDisplay(drawingArea), gc,
        BlackPixelOfScreen(XtScreen(drawingArea)));
}

void draw_cbk(Widget w, XtPointer client_data, XtPointer call_data) {
  //if (!XtIsRealized(drawingArea)) return;  
  //XClearWindow(XtDisplay(drawingArea),XtWindow(drawingArea));
  //XDrawLine(XtDisplay(drawingArea),XtWindow(drawingArea),gc,10,10,20,20);
  Dimension Width, Height;
  XtVaGetValues(w,XmNwidth,&Width,NULL);
  XtVaGetValues(w,XmNheight,&Height,NULL);
  set_color("Red");
  XDrawLine(XtDisplay(drawingArea),pixmap,gc,10,10,20,20);
  set_color("Green");
  XDrawLine(XtDisplay(drawingArea),pixmap,gc,15,15,25,30);
  XCopyArea(XtDisplay(drawingArea), pixmap, XtWindow(drawingArea), 
	    gc, 0, 0, Width, Height, 0, 0);
}

void resize_cbk(Widget w, XtPointer data, XtPointer call_data) {
  Dimension newWidth, newHeight;
  XtVaGetValues(w,XmNwidth,&newWidth,NULL);
  XtVaGetValues(w,XmNheight,&newHeight,NULL);
  cout << "width:" << newWidth << " height:" << newHeight << endl;
  //  resize does nothing unless new size is bigger than entire pixmap
  if( (newWidth <= pixmapWidth) && (newHeight <= pixmapHeight)) return;
  // Reallocate a bigger pixmap.
  Pixmap tmpPixmap = XCreatePixmap
    (XtDisplay(w), RootWindowOfScreen(XtScreen(w)), newWidth, newHeight,
     DefaultDepthOfScreen(XtScreen(w)));
  XCopyArea(display, pixmap, tmpPixmap,
	    gc ,0, 0, pixmapWidth, pixmapHeight, 0, 0);
  XFreePixmap(display, pixmap);
  pixmap = tmpPixmap; pixmapWidth=newWidth; pixmapHeight=newHeight;
  XDrawLine(display,pixmap,gc, 0, 0, pixmapWidth, pixmapHeight);
}

void set_color(String color) {
  XColor col, unused;
  if (!XAllocNamedColor(display, cmap, color, &col, &unused)) {
    char buf[32];
    sprintf(buf, "Can't alloc %s", color);
    XtWarning(buf);
    return;
  }
  XSetForeground(display, gc, col.pixel);
}

//// main
main(int argc, char** argv) {
  InitApp(argc, argv);
}
::::::::::::::
MSE.cpp
::::::::::::::
// MSE and MSE root debug
#include 
#include 
#include 

double e,ME,MSE,RMSE;
const unsigned int N=1000;

main() {
  for(unsigned int i=0;i
#include 
#include 
#include 
//matherr 

//extern int errno;

main()
{
  double d=1;
  float f=1;
  int i;
  for(i=0;i<1;i++) {
    f/=1000; cout << "f: " << f << " ";
    d/=1000; cout << "d: " << d << " ";
  }
  errno=0;
  f=0; d/=f; 
  if(errno==EDOM) cout << "EDOM error" << endl;
  if(errno==ERANGE) cout << "ERANGE error" << endl;
  cout << "f: " << f << " "; cout << "d: " << d << endl;
  //if(d==Infinity) cout << "Infinity ?!" << endl;
  float x, y;
  errno=0;
  x=-1; y=sqrt(x); if(errno) cout << "error" << endl;
  cout << "x: " << x << " "; cout << "y: " << y << endl;
  if(errno==EDOM) cout << "EDOM error" << endl;
  if(errno==ERANGE) cout << "ERANGE error" << endl;
}

::::::::::::::
ncurses.cpp
::::::::::::::
/* compile with : 
 * g++ ncurses.c -L/usr/distrib/lib  -I/usr/distrib/include -lncurses 
 * see: man curses
 */
#include 
#include  // sleep 
#include 

// windows shoiuld not overlap
// use subwin instead
int x, y;
WINDOW *AppWin, *ControlWin, *OneMoreWin;
SCREEN *AppScreen, *ControlScreen;

main()
{
  if (!(AppWin = initscr())) cout << "initscr error!" << endl;
  getmaxyx(AppWin, x, y); 
  mvwprintw(AppWin, x/2, (y-5)/2, "In the mid!");
  refresh(); sleep(1);
  if (!(ControlWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  wmove(ControlWin,10,13); wprintw(ControlWin, "hallo ControlWin");
  wrefresh(ControlWin); sleep(1);
   // switch back
  redrawwin(AppWin);sleep(1);  
   // switch back
  redrawwin(ControlWin);sleep(1);  
  // get one more  new window (buffer)
  if (!(OneMoreWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  // wclear(ControlWin);
  mvwprintw(OneMoreWin,14,4, "OneMoreWin");
  //clearok(OneMoreWin, TRUE);
  redrawwin(OneMoreWin);sleep(1);
   // switch back
  redrawwin(ControlWin);sleep(1);  
  // get a second term
  if (!(ControlScreen = newterm("xterm" , stdout, stdin)));
    cout << "newterm error!" << endl;
  if (!(AppScreen = set_term(ControlScreen)))
    cout << "set_term error!" << endl;
 sleep(10);
  endwin(); delscreen(ControlScreen); 
  delwin(ControlWin);
  if (endwin() == ERR) cout << "endwin error!" << endl;
}
::::::::::::::
ncurses_menu.cpp
::::::::::::::
/* compile with : 
 * g++ ncurses_touchwin.cpp 
 * -L/usr/distrib/lib  -I/usr/distrib/include -lncurses 
 * see: man curses
 */
#include 
//#include  // sleep 
//#include 
#include 

// windows shoiuld not overlap
// use touchwin or use subwin instead
int x, y;
WINDOW *AppWin, *ControlWin;
MENU *AppMenu;
ITEM **items

main()
{
  if (!(AppWin = initscr())) cout << "initscr error!" << endl;
  if (!(AppMenu = new_menu())) cout << "new_menu error!" << endl;
  



  /*
  getmaxyx(AppWin, x, y); 
  mvwprintw(AppWin, x/2, (y-5)/2, "In the mid!");
  refresh(); sleep(1);
  if (!(ControlWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  wmove(ControlWin,10,13); wprintw(ControlWin, "hallo ControlWin");
  wrefresh(ControlWin); sleep(1);
   // switch back
  touchwin(AppWin); wrefresh(AppWin);sleep(1);  
   // switch back
  touchwin(ControlWin); wrefresh(ControlWin);sleep(1);  
  // get one more  new window (buffer)
  if (!(OneMoreWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  // wclear(ControlWin);
  mvwprintw(OneMoreWin,14,4, "OneMoreWin");
  //clearok(OneMoreWin, TRUE);
  touchwin(OneMoreWin); wrefresh(OneMoreWin);sleep(1);
   // switch back
  touchwin(ControlWin); wrefresh(ControlWin);sleep(1);  
  // delete wins
  delwin(OneMoreWin);delwin(ControlWin);

  */
  if (endwin() == ERR) cout << "endwin error!" << endl;
}
::::::::::::::
ncurses_subwin.cpp
::::::::::::::
/* compile with : 
 * g++ ncurses.c -L/usr/distrib/lib  -I/usr/distrib/include -lncurses 
 * see: man curses
 */
#include 
#include  // sleep 
#include 

// windows shoiuld not overlap
// use subwin instead
int x, y;
WINDOW *AppWin, *ControlWin, *OneMoreWin;
SCREEN *AppScreen, *ControlScreen;

main()
{
  if (!(AppWin = initscr())) cout << "initscr error!" << endl;
  getmaxyx(AppWin, x, y); 
  mvwprintw(AppWin, x/2, (y-5)/2, "In the mid!");
  refresh(); sleep(1);
  if (!(ControlWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  wmove(ControlWin,10,13); wprintw(ControlWin, "hallo ControlWin");
  wrefresh(ControlWin); sleep(1);
   // switch back
  redrawwin(AppWin);sleep(1);  
   // switch back
  redrawwin(ControlWin);sleep(1);  
  // get one more  new window (buffer)
  if (!(OneMoreWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  // wclear(ControlWin);
  mvwprintw(OneMoreWin,14,4, "OneMoreWin");
  //clearok(OneMoreWin, TRUE);
  redrawwin(OneMoreWin);sleep(1);
   // switch back
  redrawwin(ControlWin);sleep(1);  
  // get a second term
  if (!(ControlScreen = newterm("xterm" , stdout, stdin)));
    cout << "newterm error!" << endl;
  if (!(AppScreen = set_term(ControlScreen)))
    cout << "set_term error!" << endl;
 sleep(10);
  endwin(); delscreen(ControlScreen); 
  delwin(ControlWin);
  if (endwin() == ERR) cout << "endwin error!" << endl;
}
::::::::::::::
ncurses_touchwin.cpp
::::::::::::::
/* compile with : 
 * g++ ncurses_touchwin.cpp 
 * -L/usr/distrib/lib  -I/usr/distrib/include -lncurses 
 * see: man curses
 */
#include 
#include  // sleep 
#include 

// windows shoiuld not overlap
// use touchwin or use subwin instead
int x, y;
WINDOW *AppWin, *ControlWin, *OneMoreWin;
SCREEN *AppScreen, *ControlScreen;

main()
{
  if (!(AppWin = initscr())) cout << "initscr error!" << endl;
  getmaxyx(AppWin, x, y); 
  mvwprintw(AppWin, x/2, (y-5)/2, "In the mid!");
  refresh(); sleep(1);
  if (!(ControlWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  wmove(ControlWin,10,13); wprintw(ControlWin, "hallo ControlWin");
  wrefresh(ControlWin); sleep(1);
   // switch back
  touchwin(AppWin); wrefresh(AppWin);sleep(1);  
   // switch back
  touchwin(ControlWin); wrefresh(ControlWin);sleep(1);  
  // get one more  new window (buffer)
  if (!(OneMoreWin = newwin(0,0,0,0))) cout << "newwin error!" << endl;
  // wclear(ControlWin);
  mvwprintw(OneMoreWin,14,4, "OneMoreWin");
  //clearok(OneMoreWin, TRUE);
  touchwin(OneMoreWin); wrefresh(OneMoreWin);sleep(1);
   // switch back
  touchwin(ControlWin); wrefresh(ControlWin);sleep(1);  
  // delete wins
  delwin(OneMoreWin);delwin(ControlWin);
  if (endwin() == ERR) cout << "endwin error!" << endl;
}
::::::::::::::
NS.cpp
::::::::::::::
// Nullstelle

#include
#include

#define START 9
#define STOP 100
#define STEP 0.1

int n, nStepSize;

double Func(double x) { 
  // return x-13;
  double p,dp;
  p = (1-exp(-0.27273*(x-9)));
  dp=(0.27273*exp(-0.27273*(x-9)));
  return (n-1)*pow(p,(n-2))*dp*(1-p)-pow(p,(n-1))*dp;
}

main() {
  double x,xMax,LastMax,NLastMax,y,y0;
  nStepSize = 1;
  LastMax=0; NLastMax=0;
  for(n=1;n<1000000;n+=nStepSize) { 
    y0=Func(START);
    for(x=START+STEP;x<=STOP;x+=STEP) {
      y=Func(x);
      if(y0*y<0) {
	xMax=(x-STEP/2);
	//cout << n << " " << xMax
	// << "NS:" << (x-STEP/2) << " y:" << y << " y0:" << y0 
	//   << "\n";
      }
      y0=y;
    }
    // Reduce data.
    if(xMax-LastMax>0.1){ 
      cout << n << " " << xMax << "\n"; 
      LastMax=xMax; nStepSize=(int)(n-NLastMax+1)/2; NLastMax=n;
      // cout << nStepSize  << "\n";
    }
  } 
}
::::::::::::::
NumToDigit.cpp
::::::::::::::

// To get a local input representation out of a Class number.

#include
#include

unsigned int iSeq, iPat;
int NbSeq, NbIn, Dim, In, NbClass;

main() {
  NbIn = 3;
  Dim = 3; 
  NbSeq = (int) pow(NbIn,Dim);
  for(iSeq=0;iSeq " << NbClass << endl;
  }
}
::::::::::::::
ofstream.cpp
::::::::::::::
#include 
#include 

int FileIO()
{
  return 17;
}

main()
{ 
  ofstream f;// = new ofstream("test.out");
  f.open("test.out");
  f << FileIO();
  f << FileIO();
  f.close();
}
::::::::::::::
OperatorAsPara.cpp
::::::::::::::
#include 
#include 
#include 
#include 
//NO !!
//void F(operator) {}
//BUT:
void W(iostream *s, double &d, void(*f)(iostream *s, double &d)) { f(s,d); }
void d2s(iostream *s, double &d) { *s << d; }
void s2d(iostream *s, double &d) { *s >> d; }

main() {
  double d=17;
  strstream Buf;
  W(&Buf,d,&d2s);
  char *BufStr = Buf.str(); 
  cout << BufStr << endl; free(BufStr); cout.flush();
  fstream f; f.open("tt", ios::in);
  d=13; W(&f,d,&s2d); cout << d << endl;
  f.close();
}

::::::::::::::
parallelPort.cpp
::::::::::::::
//
//Save the source code to file lpt_test.c and compile it with command: 
//gcc -O lpt_test.c -o lpt_test
//
//Parallel port controlling in Linux
//
//Linux will allow acess to any port using the ioperm syscall.
//Here is some code parts for Linux to write 255 to printer port: 

#include 
#include 
#include 
#include 

#define base 0x378           /* printer port base address */
#define value 255            /* numeric value to send to printer port */

main(int argc, char **argv)
{
   if (ioperm(base,1,1))
    fprintf(stderr, "Couldn't get the port at %x\n", base), exit(1);

   outb(value, base);
}

::::::::::::::
Paramter-Optional.cpp
::::::::::::::
#include 

void Func(int i1,int i2 =1) {
  cout << i1 << i2 << endl;
}

main() {
  Func(2);
}
::::::::::::::
PatternManagementTest.cpp
::::::::::::::
//purify g++ /home/felix/c-cpp/BaseClasses/PatternManagement.o /home/felix/c-cpp/BaseClasses/IOBase.o  -I /home/felix/c-cpp/BaseClasses  -L /home/felix/c-cpp/BaseClasses PatternManagementTest.cpp
#define TEST_ONLINE_PAT_FUNCNAME Online_Timer
#include "PatternManagement.h"

class TPatternTest : public TPatternGenerator {
public:
  Test(struct TPatData &apsPatData) {
    strcpy(cTrainPatFilename,
	   "/home/felix/Data/artificial/E_Reber.Cont.TaT.500.dat"); 
    for(unsigned int tri=0;tri<3;tri++) { cout <<"\ntri: "<
#include
#include
#include
#include
#include
#include
#include

#define BufSize 256
#define GNU_GEOMETRY "450x450+300+20"
 
int n, fd[2];
pid_t pid, WaitStatus;
char cBuf[BufSize];
char* program = "/usr/local/bin/gnuplot";
char cOpt[64] = "";//"gnuplot.gp";


main()
{
  FILE *fd2FILE, *fd02FILE;
  if(pipe(fd) < 0) cout << "pipe error!" << endl;
  if((pid = fork()) < 0) cout << "fork error!" << endl;
  else if(pid > 0) { // parent (child gets a 0 as pid)
    cout << "parent" << endl;
    // get a file object for the file descriptor
    if (!(fd2FILE = fdopen(fd[1], "w"))) 
      cerr << "fdopen error!" << endl;
    if (!(fd02FILE = fdopen(STDIN_FILENO, "w"))) 
      cerr << "fdopen error!" << endl;
    fprintf(fd02FILE, "20\n");
    close(fd[0]);
    // write(fd[1], "hello\n", 6);
    do {
    sleep(1);
      if ((WaitStatus = waitpid(pid, NULL, WNOHANG)) < 0) 
        cout << "waitpid error" << endl;
      if (WaitStatus == 0) {
        //cout << "child not terminated" << endl;
        //kill(pid, SIGINT);
	strcpy(cBuf, "pause 0 'togp'\n");
	//strcpy(cBuf, "load 'gnuplot.gp'\n");
	n = strlen(cBuf);
	//write(STDOUT_FILENO, "load 'gnuplot-data.gp'", BufSize);
	//write(fd[1], cBuf, n);
	write(fd[1], "hello\n", 6);
	fprintf(fd2FILE, "mmm\n"); fflush(fd2FILE);
      } 
    } while (WaitStatus <= 0);
    if (WaitStatus > 0) {
      cout << "child terminated status: " << WaitStatus << endl;
    }
  } else  { // child
    cout << "child" << endl;
    close(fd[1]);   
    //n = read(fd[0], cBuf, BufSize);
    //write(STDOUT_FILENO, cBuf, n);
    // cout << cBuf << endl;
    // set standard in
    if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO) 
      cout << "dup2 error!" << endl;
    cout << "child exec" << endl;
    //execlp("echo", "echo", "hi", "hdi",(char *) 0 ); 
    //execlp(program, program, (char *) cOpt, NULL); 
    //execlp(program, program, NULL);
    execlp("cat", "cat", NULL);
    //execl(program, program, (char *) cOpt,(char *) 0 );
    write(STDOUT_FILENO, "load 'gnuplot-data.gp'", BufSize);
    cout << "ready to exit pid : " << pid << endl;
    exit(0);
  }
  exit(0);
}  
::::::::::::::
pipe.cpp
::::::::::::::
#include
#include
#include

#define BufSize 256
 
int n, fd[2];
pid_t pid;
char cBuf[BufSize];

main()
{
  if(pipe(fd) < 0) cout << "pipe error!" << endl;
  if((pid = fork()) < 0) cout << "fork error!" << endl;
  else if(pid > 0) { // parent (child gets a 0 as pid)
    cout << "parent" << endl;
    close(fd[0]);
    write(fd[1], "hello\n", 6);
  } else  { // child
    cout << "child" << endl;
    close(fd[1]);
    n = read(fd[0], cBuf, BufSize);
    write(STDOUT_FILENO, cBuf, n);
    // cout << cBuf << endl;
  }
  exit(0);
}  
::::::::::::::
pointer++.cpp
::::::::::::::
# include 

main()
{
  cout << sizeof(long int) << endl;
  int i; // for loop
  long int *pi, *pj;
  pi = new long int[3];
  pj = pi;
  for(i=0;i<3;i++) cout << pj[i]; cout << endl;
  *pi = 7;
  *(++pi)++ = 8;
  *pi = 9;
  for(i=0;i<3;i++) cout << pj[i]; cout << endl;
  pj = pi;
  pj -= 2; // we don't need sizeof()
  for(i=0;i<3;i++) cout << pj[i]; cout << endl;
  pj = pi;
  pj -= 2*sizeof(long int); // WRONG !! equals -= 8
  for(i=0;i<9;i++) cout << pj[i]; cout << endl;
}
::::::::::::::
PointerPara.cpp
::::::::::::::
#include 
#include 

int* pi1; 
int* pi2;
char c64[64];
struct st { char a; char b; } *S,s;

// func(int &api) // changes the content of an int
func(int *&api) // this allows to change the pointer itself
//func(int &*api) // cannot declare pointers to references
//func(int *api) // this allows to change the content of the pointer
{
  cout << "api: " << api << " = " << *api << endl;
  api = pi2;
}

StringFunc(char (&ac)[64])
{
  strcpy(ac, "different string");
}

StructFunc(struct st &as) {
  S=&as;
}

funcB(int &ai) {
  cout << "ai: " << ai << " = " << &ai << endl;
  ai = 17;
  cout << "ai: " << ai << " = " << &ai << endl;
}

funcA(int &ai) {
  cout << "ai: " << ai << " = " << &ai << endl;
  ai = 13;
  cout << "ai: " << ai << " = " << &ai << endl;
  funcB(ai);
}

main() {
  pi1 = new int(1);
  pi2 = new int(2);
  void* p;
  func(pi1);
  cout << "pi1: " << ((void*)pi1) << " = " << *pi1 << endl
       << "pi2: " << ((void*)pi2) << " = " << *pi2 << endl
       << p << endl;
  delete pi1; delete pi2;
  // now with a char[64] we have to use ().
  strcpy(c64, "test string");
  StringFunc(c64);
  cout << c64 << endl;
  s.a='a'; s.b='b'; StructFunc(s);
  cout << S->a << S->b << endl;
  // nested function calls with a reference parameter
  int i=11;
  funcA(i);
  cout << "i: " << i << " = " << &i << endl;
}
::::::::::::::
PolyPlot.cpp
::::::::::::::
#include 
#include 
#include "/home/felix/c-cpp/BaseClasses/MathMacros.h"

  
main() {
    cout.precision(10);
    const double N=3; 
    for(double i=0;i
#include 
#include 
#include 

int i;

main() {
  fstream f; f.open("t", ios::ate | ios::out );
  if(!f) cout << "file error" << endl;
  for(i=0;i<5;i++) f << i << "\n";
  int fPos = f.tellp();
  f << "    \n";
  for(i=0;i<5;i++) f << i << "\n";
  f.seekp(fPos);
  f << "here" << endl;
  f.close();
}
  
  
::::::::::::::
PrivateClasses.cpp
::::::::::::::
#include

// protected and privated have the same problem that they lead
// to ambiguity though they should not. So we need virtual.
// g++ warning: `protected' access not implemented
// protected = private
class A {
public:
  int ia;
};

class B : virtual protected A { // public protected private
public:
};

class BB : virtual protected A { // public protected private
public:
};

class C : virtual public B , virtual public BB {
public:
  void fc() { ia = 3; }
};

main() {
  cout << "new C...\n"; C* c = new C();
  c->fc();
  delete c;
}
::::::::::::::
PtrFunc.cpp
::::::::::::::
#include 

void Func(void) { cout << "Func" << endl; }

main()
{
  void (*FuncPtr)(void);
  FuncPtr = Func;
  // FuncPtr = &Func; // is also possible
  FuncPtr();
}
::::::::::::::
qsort.cpp
::::::::::::::
#include 
#include 
// Use vector and sort in c++ (see sort.cpp).

struct TNeighbor { unsigned int Nb; double dist; };

int CompareDist(TNeighbor *N1, TNeighbor *N2) { 
  if(N1->distdist) return -1; 
  else if(N1->dist>N2->dist) return 1; 
  return 0; 
}

main() {
  TNeighbor N[] = { {1,3},{2,1},{3,7},{4,3} };
  qsort(N,4,sizeof(TNeighbor),&CompareDist);
  for(unsigned int i=0;i<4;i++) 
    cout <
#include 

main() {
  char s[64];
  cin >> s;
  cout << s << endl;
  // Read from file.
  ifstream f;
  f.open("read-string-test");
  f >> s;
  cout << s << endl;
  f >> s;
  cout << s << endl;
  f.close();
}
::::::::::::::
recursion.cpp
::::::::::::::
// Output iteration of recursive function.
#include 
#include 
#include 
#include 


static double a=2;  //Para.

double Recursion(double &x) {
  return (a*x*(1-x));
}

main(int argc, char *argv[]) {
  ofstream f; 
  double x=0.1; // Initial value.
  if(argc < 2) { cout<<"parameter: a  x_0\n"; }
  //cout<<"argc: "<
#include 
#include  // System Calls 
#include 
#include 
#include 
 
main()
{
  //remove("t");
  char file[257]= "rm_test";
  char files[257]= "rm_test*";
  char com[257]= "echo ll ; ll rm_test*";
  system(com);
  remove(file);
  system(com);
  remove(files);
  system(com);
}
::::::::::::::
RNN.CreatePattern.cpp
::::::::::::::
// To create Training pattern for RNN-project.
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define NB_SEQS  11
#define NB_PATTERN  50
#define MIN_PAT_LENGTH 10
#define NB_VALUES 13

ofstream f;
int i, ii, iii, iv;
double d;

void
SeppTestPats()
{
  for(ii=0;ii 0.5) d = +1; else d = -1;
    f << d << "\t" << 0 << "\n";
    for(i=0;i 0.1);i++)// varable seq length
      f << 0 << "\t" << 0 << "\n";
    if(d==1) 
      f << 1 << "\t" << 1 << "\n";
    else
      f << 1 << "\t" << 0 << "\n";
    f <<  "\n\n";
  }
}

void
SeppTestPatsPlus() // multiple outputs
{
  for(ii=0;ii 0.5) d = +1; else d = -1;
    f << d << "\t" << 0 << "\t" << 0 << "\n";
    for(i=0;i 0.1);i++)// varable seq length
      f << 0 << "\t" << 0 << "\t" << 0 << "\n";
    if(d==1) 
      f << 1 << "\t" << 1 << "\t" << 0 << "\n";
    else
      f << 1 << "\t" << 0 << "\t" << 1 << "\n";
    f <<  "\n\n";
  }
}

ConstIO()
{
  for(i=0;i<20;i++) {
    f << 3 << "\t" << 0.3 << "\n";
    f << -1 << "\t" << 0.8 << "\n";
  }
  f <<  "\n\n";
}

StepByStepPredictionaPats() {
  int noise;
  for(ii=0;ii 0.5) d = +1; else d = -1;
    f << d << "\t" << 0 << "\t" << 0 << "\n";
    for(i=0;i 0.1);i++) { // varable seq length
      noise = (int)fmod(lrand48(),9)+1; 
      f << noise << "\t" << noise << "\t" << noise << "\n"; // noise
    }
    if(d==1) 
      f << 1 << "\t" << 1 << "\t" << 0 << "\n";
    else
      f << 1 << "\t" << 0 << "\t" << 1 << "\n";
    f <<  "\n\n";
  }
}

SpeechPats() {
  // init random generator
  time_t t;
  long lseed = (long) time(&t);
  srand48(lseed);
  int noise[NB_SEQS][NB_PATTERN][NB_VALUES];
  // random init, but all seqs equal
  for(ii=0;ii 0.5) XNotYt1 =1; else XNotYt1 =0;
    //if(drand48() > 0.5) XNotYt2 =1; else XNotYt2 =0;
    XNotYt1 = (int)fmod(iSeq,2);
    if(((int)fmod(iSeq,4))>1) XNotYt2 =1; else XNotYt2 =0;
    // Start with the Begin symbol.
    f << 1; for(i=1;i<12;i++) f << " " << 0; f << "\n";
    // Pattern loop.
    for(int iPat=0;iPat 0.5) XNotYt1 =1; else XNotYt1 =0;
    //if(drand48() > 0.5) XNotYt2 =1; else XNotYt2 =0;
    XNotYt1 = (int)fmod(iSeq,2);
    if(((int)fmod(iSeq,4))>1) XNotYt2 =1; else XNotYt2 =0;
    // Start with the Begin symbol.
    f << 1; for(i=1;i<12;i++) f << " " << 0; f << "\n";
    // Pattern loop.
    for(int iPat=0;iPat 0.5) XNotYt1 =1; else XNotYt1 =0;
//     //if(drand48() > 0.5) XNotYt2 =1; else XNotYt2 =0;
//     XNotYt1 = (int)fmod(iSeq,2);
//     if(((int)fmod(iSeq,4))>1) XNotYt2 =1; else XNotYt2 =0;
//     if(((int)fmod(iSeq,8))>3) XNotYt3 =1; else XNotYt3 =0;
//     for(int iPat=0;iPat
#include 
#include 
#include 

#define START_WORD 1
#define END_WORD 11

// Determine which data
char Path[32] = "./feats";
char OutPath[32] = "./TmpPattern";
//int NbWords = END_WORD - START_WORD;
int Speaker_Number, iSN, NbSpeakers;
int Word_Number;
// Read parameters of the data file.
int dim,nSamples,sampPeriod;
short sampSize,sampKind;
char str[100];
FILE *W;
// Read the data.
ifstream g2s_lis;
ifstream g1s_lis;
ofstream fPattern;
float Val;
int iSample, iByte;
int iTarget;
 
DisplayFeatureData()
{
  sprintf(str,"%s/EWS%dW%d.cep",Path,Speaker_Number,Word_Number);
 
  if ((W=fopen(str,"r"))==NULL) 
  { printf("\nError opening File %s!\n",str);
    exit(0);
  }
  fread(&nSamples,sizeof(nSamples),1,W);
  printf("%d samples in file!\n",nSamples);
  fread(&sampPeriod,sizeof(sampPeriod),1,W);
  printf("sample period in 100ns units is: %d\n",sampPeriod);
  fread(&sampSize,sizeof(sampSize),1,W);
  printf("number of bytes per sample: %d\n",(int)sampSize);
  fread(&sampKind,sizeof(sampKind),1,W);
  printf("code for sample kind: %d\n",(int)sampKind);
  dim = (int) sampSize/4; // 4 = sizeof(float)
  //
  // Now you can read the consecutiv feature-vector components with 
  fprintf(stdout, "feature-vector component [Sample][Byte]\n");
  for(iSample=0;iSample> NbSpeakers; // number of speakers
  for(iSN=0;iSN<500;iSN++) { // loop over speakers
    // Get next Speaker_Number of train pattern
    g1s_lis >> Speaker_Number;     
    // loop over words
    for(Word_Number=START_WORD;Word_Number<=END_WORD;Word_Number++) { 
      // open feats file      
      sprintf(str,"%s/EWS%dW%d.cep",Path,Speaker_Number,Word_Number);
      if ((W=fopen(str,"r"))==NULL) {
	printf("\nError opening File %s!\n",str); exit(0); }
      // open pattern file (output file)
      sprintf(str,"%s/EWS%dW%d.pat",OutPath,Speaker_Number,Word_Number);
      fPattern.open(str);
      if(!g1s_lis) {
	cout << ("\nError opening File %s!\n",str); exit(0); }
      // read feats file
      fread(&nSamples,sizeof(nSamples),1,W);
      printf("%d samples in file!\n",nSamples);
      fread(&sampPeriod,sizeof(sampPeriod),1,W);
      printf("sample period in 100ns units is: %d\n",sampPeriod);
      fread(&sampSize,sizeof(sampSize),1,W);
      printf("number of bytes per sample: %d\n",(int)sampSize);
      fread(&sampKind,sizeof(sampKind),1,W);
      printf("code for sample kind: %d\n",(int)sampKind);
      dim = (int) sampSize/sizeof(float); // 4 = sizeof(float)
      //
      // Now you can read the consecutiv feature-vector components
      // One feature vector is one pattern, one word (one feat file) is
      // one sequence.
      fprintf(stdout, "feature-vector component [Sample][Byte]\n");
      for(iSample=0;iSample
#include 
#include 
#include 

void FlieIO();

void FileIO()
{
  int i1=0, i2=0, i3=0;
  ifstream f;  // = new ifstream("test");
  f.open("test");
   f.scan("two:");
  //f >> "two:"; // leads to segmentation violation
  f >> i1;
  cout << "pos: " << f.tellg() << "\n";
  cout << f.eof() << "\n";
  f.scan("seven:");
  //f >> "seven:";
  cout << "pos: " << f.tellg() << "\n";
  while(! f.good()) { 
    f.seekg(1, f.cur);
    if(f.eof()) { cout << "eof\n"; return;}
    cout << "..again..\n"; 
    cout << "pos: " << f.tellg() << "\n";
    f.clear();    
    cout << "pos: " << f.tellg() << "\n";
    f.scan("seven:"); 
    cout << "gcount: " << f.gcount() << "\n";
  }
  f >> i2;
  if (! f.good()) { cout << "error"; f.clear(); }
  cout << i1 << "," << i2 << "," << i3;
}

main()
{ 
 FileIO();
 return 0;
}
::::::::::::::
scan-stream-short.cpp
::::::::::::::
// use g++ not gcc
#include 
#include 

main()
{ 
  int i1=0, i2=0, i3=0;
  float l;
  double d;
  ifstream f;
  f.open("test");
  f.scan("two:"); f >> i1;
  f.ignore(1000, '\n');
  f.scan("# three:"); f >> i3; cout << "i3: " << i3 << endl;
  f.scan("seven:");
  while(! f.good()) { 
    f.seekg(1, f.cur);
    if(f.eof()) { cout << "eof\n"; return 1;}
    f.clear();    
    f.scan("seven:"); 
  }
  f >> i2;
  if (! f.good()) { cout << "error\n"; f.clear(); }
  cout << i1 << "," << i2 << "\n";
  // floats and doubles
  f.close();
  f.open("f-test");
  f >> l; cout << "l: " << l << "\n";
  f.seekg(f.beg);
  f >> d; cout << "d: " << d << "\n";
  // strings
  f.close();
  f.open("s-test");
      f.scan("# uno:");
  f >> l; cout << "l: " << l << "\n";
  // and close it
  f.close();
}
::::::::::::::
shift.cpp
::::::::::::::
// use g++ not gcc
#include 
#include 
#include 
 

short c, cc;
int d,i;

main()
{
  i=0; d=35; while(d>0) { d>>=1; i++; cout <> 1;
  cout << c << " cc " << cc << endl;
  int i,mask;
  for(i=0,mask=1;i<7;i++,mask+=1<
#include 
#include "/home/felix/c-cpp/BaseClasses/MathMacros.h"

main() {
  double sig, sig_d;
    cout.precision(10); 
    for(double i=-5;i<5;i+=0.01) {
      // Tradional. 
      sig=1/(1+EXP(-x)); sig_d=(y*(1-y));
      // (1+k)/
    (1+OUTPUT_SIGMOID) * LOGC(x) - OUTPUT_SIGMOID;

    e=exp(i); E=EXP(i);
    s=2/(1+exp(-i))-1; S=2/(1+EXP(-i))-1; SS = 2*LOGC(i)-1;
    //cout << "i:" << i << " e:" << e << " E:" << E << " e-E:" << e-E << " ,
";
    //cout << " s:" << s << " S:" << S << " s-S:" << s-S << " ,\n ";
    cout << i << " " << s << " " << S << " " << SS << "\n";
    //cout << i << " " << S-s << "\n";
    cout.flush();
  }
}
::::::::::::::
sort.cpp
::::::::::::::
#include 
#include 
#include 
#include 
#include 
// Use vector and sort instead of qsort().

class TNeighbor {
public:
  TNeighbor() { Nb=7; dist=17; }
  Init(unsigned int Nb, double dist) {
    TNeighbor::Nb=Nb; TNeighbor::dist=dist; }
  bool operator>(TNeighbor &N) { return dist>N.dist; }
  bool operator<(TNeighbor &N) { return dist NVec(4);
  for(unsigned int i=0;i<4;i++) NVec[i].Init(i,fmod(i,2));
    //NVec.reserve(4);
  
  //TNeighbor& NRef=NVec[1]; // A Ref & nothing else.
  //TNeighbor  NVar; NVar.Nb=17; NVar.dist=27;
  //for(unsigned int i=0;i<4;i++) //NVec.push_back(NRef);//NVec.push_back(NRef);
  //NVec.push_back(new TNeighbor(i,fmod(i,2)));
  //NVec[2].Nb=9; cout <Nb<Nb<Nb<
#include 
#include 

main()
{ 
  char c[101];
  int iLength;
  // cout << "\f";
  strcpy(c, "soon we delete this.....wait.."); iLength = strlen(c);
  cout << c; cout.flush(); system("sleep 2");
  for(int i=0;i

char *pc;
 
main()
{
  int i = 17;
  pc = new char[16];
  sprintf(pc, " int i : %d\n", i);
  fprintf(stdout, "pc : %s", pc);
  //sprintf(stdout, "a"+" b");
  sprintf(pc, "%s.%d\n","iii",i);
  fprintf(stdout, "pc : %s", pc);
}
::::::::::::::
sqrt.cpp
::::::::::::::
#include 
#include 
#include 

double SQRT(double d) { 
  if(!d) return 0;
  double dd = d/2; 
  for(int i=0;i<10;i++) dd = 0.5*(dd+d/dd); 
  return dd;
}

main() {
  double s,S;
  for(float f=0.000001;f<1000;f*=10) {
    s = sqrt(f);
    S = SQRT(f);
    cout << setw(20) << f
	 << setw(20) << s 
	 << setw(20) << S 
	 << setw(20) << (s-S) 
	 << setw(20) << (s-S)/s
	 << endl;
  }
  cout << "start sqrt..." << endl;
  for(float f=0;f<100000;f+=0.1) s = sqrt(f);
  cout << "ready!\n" << endl;
  cout << "start SQRT..." << endl;
  for(float f=0;f<100000;f+=0.1) s = SQRT(f); // slower
  cout << "ready!\n" << endl;
}
::::::::::::::
staticVar.cpp
::::::::::::::
#include 

class X {
public:
  int K() { return k; }
  static int i;
  int j;
private:
  static int k;
};

int X::i = 0;
int X::k = 17;

class Y {
public:
  static X x;
  static void J() { x.j = 14; cout << x.j << endl; }
};

X Y::x;

main() {
  X x;
  cout << X::i << endl;
  //X::i = X::k;
  X::i = x.K();
  cout << X::i << endl;
  Y y; y.J();
}
::::::::::::::
strcpy.cpp
::::::::::::::
#include
#include

main()
{
  char* string;
  strcpy(string, "fuck");
  cout << string << endl;
  strcpy(string, "duckduck");
  cout << string << endl;
  strcpy(string, "duck");
  cout << string << endl;
  delete string;
  string = new char[30]("pig");
  cout << string << endl;
}

/*
string = new char[30]("pig");
strcpy.cpp: In function `int main()':
strcpy.cpp:14: Internal compiler error.
strcpy.cpp:14: Please submit a full bug report to `bug-g++@prep.ai.mit.edu'.
*/
::::::::::::::
StringArray.cpp
::::::::::::::

typedef char char64[64];
 
// char pc[64][];
char64 *pc;

main()
{
  pc = new (char64) = {"xxx"};;
  pc = new (char64)[3];
  // pc = new (char*)[3] = {"abc", "def", "efg"};
} 
::::::::::::::
StringConstReturn.cpp
::::::::::::::
#include 
#include 

char* GetSring() { return("String"); }

main()
{
  char c[11];
  char* pc;
  cout << GetSring() << endl;
  strcpy(c, GetSring());
  cout << c << endl;
  free(GetSring());
  // do we produce zonbie memory ??, see $>top --no!!
  while(true) GetSring();
  // while(true) pc =  GetSring();
  // but .. of cause:
  //while(true) pc =  new char;
}
::::::::::::::
String.cpp
::::::::::::::
// Compile with My_make_motif
#include 
#include 
#include 
#include 


main() {
  String str; //char* str;
  str = new char[256];
  //str = new String("fuck");
  strcpy(str, "fuck");
  cout << str << endl;
}
::::::::::::::
string-stream.cpp
::::::::::::::
// test a string stream to replace char*
#include 
#include 
#include 
#include 
#include 


test_ostream()
{ 
  void* v;
  char* c = new char[256];
  v = c;
  fprintf(stdout, "c:%p\n", c);
  fprintf(stdout, "v:%p\n", v);
  strcpy(c, "fuck");
  ostrstream Out; // dynamic buffer
  Out << "one" << 1 << "three.two" << 3.2 << "end.\n";// << ends;
  c = Out.str();
  fprintf(stdout, "c:%p\n", c);
  cout << "BufPtr: " << c << "\n";
  c = Out.str();
  fprintf(stdout, "c:%p\n", c);
  free(c);// delete c;
  // cout << Out.str();
  // Out.frozen();
  // Out.clear();  
  Out << "go on...\n" << ends;
  c = Out.str();
  fprintf(stdout, "c:%p\n", c);
  cout << "BufPtr: " << c << "\n";
  // cout << Out.str();
  //  istrstream In()
  Out.seekp(Out.beg);
  Out << "rewrite...soooooooooooooooooooooooooooooooooooooo long\n" << ends;;
  c = Out.str();
  fprintf(stdout, "c:%p\n", c);
  cout << "BufPtr: " << c << "\n";

  delete c;
}
test_stream()
{ // !! strings have to be without blanks
  char input[516];
  char cpar1[256], cpar2[256];
  double dpar1, dpar2;
  strstream S;
  //cout << "empty string " <<  S.str() << endl;
  // str on an empty string freezes the string
  S << " " << ends; 
  cout << "almost empty string " <<  S.str() << endl;
  S.seekg(0); S.seekp(0);
  S << " cpar1: " << 12.12 << " cpar2: " << 0.23 << ends; 
  S >> cpar1 >> dpar1 >> cpar2 >> dpar2;
  cout << cpar1 << dpar1 << cpar2 << dpar2 << endl;
  S.seekg(0); S.seekp(0);
  //delete S.str(); // doesn't work.
  //cin.get(input, 516); S << input;
  S << " w " << 1 << " q " << 2 << ends; 
  S >> cpar1 >> dpar1 >> cpar2 >> dpar2;
  cout << cpar1 << dpar1 << cpar2 << dpar2 << endl;
  //cout << S << endl; // no !
  cout << S.str() << endl;
  //S.clear(); // does not do anything
  S.seekg(0); S.seekp(0);
  S << "new " << ends;
  cout << S.str() << endl;
  // but once handled badly the string freezes until a clear()
  S >> cpar1 >> dpar1 >> cpar2 >> dpar2 >> cpar1 >> dpar1 >> cpar2 >> dpar2;
  S.clear(); // does not do anything
  S.seekg(0); S.seekp(0);
  S << "else" << ends;
    cout << S.str() << endl;
  //cout << cpar1 << dpar1 << cpar2 << dpar2 << endl;
  
}

void ReUse() {
  strstream Buf;
  // once
  Buf << "123\n" << ends; ;
  cout << Buf.str();//.flush (); 
  cout.flush();
  Buf.clear(); Buf.seekg(0); Buf.seekp(0);
  // again
  Buf << "12345678\n";
  cout << Buf.str(); 
  cout.flush();
  Buf.clear(); Buf.seekg(0); Buf.seekp(0);  
}

main()
{
  //test_stream();
  ReUse();
}
::::::::::::::
strlen.cpp
::::::::::::::
#include
#include

main()
{
  char* string;
  string = new char[64];
  strcpy(string, "pig");
  cout << string << strlen(string) << endl;
  delete string;
}
 
::::::::::::::
struct.cpp
::::::::::::::
#include

struct S {int i;};
//struct T { typedef struct {int i;}S; S s; };
struct T { S s; };

main()
{
  T t;
  t.s.i = 3;
  cout << t.s.i << endl;
  S s;
  s.i = 5;
  cout << s.i << endl;
}
::::::::::::::
sum.cpp
::::::::::::::
// Sum of small numbers.
// Best: Sort nums and start with the smallest one: cost +=n*log(n).
// Fastest: linear. cost +=0.
// Tree sum: cost +=0.

#include
#include

main () {
  //cout.precision(20);
  const unsigned long N=100000;//try 1000
  //const float _d=1/(float)N; cout<<_d<
#include 
#include  // System Calls 
#include 
#include 
#include 

main()
{
  char* cTmpName;
  char** arg;
  char cBuf[501];
  arg = NULL;
  // strcpy(cBuf, system("stty | grep rows"));
  //system("stty | grep rows");
  // cout << execv("echo fuck", arg);
  // get system info
  cTmpName = tmpnam(NULL);
  strcpy(cBuf, "cat "); strcat(cBuf, cTmpName); 
  system(cBuf);
  cout << cBuf;
  // save system info into file and read it again...mmh?
  //remove(tmpnam);
  cout << "\nend.\n";
  system("ls ttt*");
}
::::::::::::::
term_control.cpp
::::::::::::::
// see man terminfo , manual tparm, man tput
#include

// \033 for 

main()
{
  printf("\033]2; fuckterm. \007");
  // printf("\033[1J\007"); //Clear Above
  printf("\033[;H\007"); // position curser
  printf("\033[3;B\007"); // position move
  printf("here");
  printf("\033[10;B\007"); // position move
  printf("\033[8;C\007"); // position move
  printf("there");
  printf("\033[3;B\007"); // position move
  // new start
  printf("\033[2J\007");
  int col=7, row=3;
  printf("\033[%d;%dH\007",row,col);
  printf("and here");
}

/*
                          Xterm Control Sequences

                                 Edward Moy

                     University of California, Berkeley

                                 Revised by

                               Stephen Gildea

                                X Consortium

Definitions

c    The literal character c.

C    A single (required) character.

Ps   A single (usually optional) numeric parameter, composed of one of  more
     digits.

Pm   A multiple numeric parameter composed of any number of  single  numeric
     parameters, separated by ;  character(s).

Pt   A text parameter composed of printable characters.

VT100 Mode

	Most of these control sequences are standard VT102  control  sequences,  but
	there  are  some  sequences  here  from  later DEC VT terminals, too.  VT102
	features not supported are smooth scrolling, double size characters,  blink-
	ing  characters,  and  VT52 mode.  There are additional control sequences to
	provide xterm-dependent functions, like the scrollbar or window size.  Where
	the  function  is  specified  by DEC or ISO 6429, the code assigned to it is
	given in parentheses.  The escape codes to designate  and  invoke  character
	sets  are specified by ISO 2022; see that document for a discussion of char-
	acter sets.
	BEL            Bell (Ctrl-G)
	BS             Backspace (Ctrl-H)
	TAB            Horizontal Tab (HT) (Ctrl-I)
	LF             Line Feed or New Line (NL) (Ctrl-J)
	VT             Vertical Tab (Ctrl-K) same as LF
	FF             Form Feed or New Page (NP) (Ctrl-L) same as LF
	CR             Carriage Return (Ctrl-M)
	SO             Shift Out (Ctrl-N) ->  Switch  to  Alternate  Character  Set:
	               invokes the G1 character set.
	SI             Shift In  (Ctrl-O)  ->  Switch  to  Standard  Character  Set:
	               invokes the G0 character set (the default).
	ESC # 8        DEC Screen Alignment Test (DECALN)
	ESC ( C        Designate G0 Character Set (ISO 2022)
	                 C = 0  -> DEC Special Character and Line Drawing Set
	                 C = A  -> United Kingdom (UK)
	                 C = B  -> United States (USASCII)
	ESC ) C        Designate G1 Character Set (ISO 2022)
	                 C = 0  -> DEC Special Character and Line Drawing Set
	                 C = A  -> United Kingdom (UK)
	                 C = B  -> United States (USASCII)
	ESC * C        Designate G2 Character Set (ISO 2022)
	                 C = 0  -> DEC Special Character and Line Drawing Set
	                 C = A  -> United Kingdom (UK)
	                 C = B  -> United States (USASCII)
	ESC + C        Designate G3 Character Set (ISO 2022)
	                 C = 0  -> DEC Special Character and Line Drawing Set
	                 C = A  -> United Kingdom (UK)
	                 C = B  -> United States (USASCII)
	ESC 7          Save Cursor (DECSC)
	ESC 8          Restore Cursor (DECRC)
	ESC =          Application Keypad (DECPAM)
	ESC >          Normal Keypad (DECPNM)
	ESC D          Index (IND)
	ESC E          Next Line (NEL)
	ESC F          Cursor to lower left corner of  screen  (if  enabled  by  the
	               hpLowerleftBugCompat resource).
	ESC H          Tab Set (HTS)
	ESC M          Reverse Index (RI)
	ESC N          Single Shift Select of G2 Character Set (SS2):  affects  next
	               character only
	ESC O          Single Shift Select of G3 Character Set (SS3):  affects  next
	               character only
	ESC P Pt ESC \ Device Control String (DCS)
	                 xterm implements no DCS functions; Pt is ignored.  Pt  need
	               not be printable characters.
	ESC Z          Return Terminal ID (DECID).  Obsolete form of ESC [ c  (DA).
	ESC [ Ps @     Insert Ps (Blank) Character(s) (default = 1) (ICH)
	ESC [ Ps A     Cursor Up Ps Times (default = 1) (CUU)
	ESC [ Ps B     Cursor Down Ps Times (default = 1) (CUD)
	ESC [ Ps C     Cursor Forward Ps Times (default = 1) (CUF)
	ESC [ Ps D     Cursor Backward Ps Times (default = 1) (CUB)
	ESC [ Ps ; Ps H Cursor Position [row;column] (default = [1,1]) (CUP)
	ESC [ Ps J     Erase in Display (ED)
	                 Ps = 0  -> Clear Below (default)
	                 Ps = 1  -> Clear Above
	                 Ps = 2  -> Clear All
	ESC [ Ps K     Erase in Line (EL)
	                 Ps = 0  -> Clear to Right (default)
	                 Ps = 1  -> Clear to Left
	                 Ps = 2  -> Clear All
	ESC [ Ps L     Insert Ps Line(s) (default = 1) (IL)
	ESC [ Ps M     Delete Ps Line(s) (default = 1) (DL)
	ESC [ Ps P     Delete Ps Character(s) (default = 1) (DCH)
	ESC [ Ps ; Ps ; Ps ; Ps ; Ps T
	               Initiate   hilite    mouse    tracking.     Parameters    are
	               [func;startx;starty;firstrow;lastrow].  See the section Mouse
	               Tracking.
	ESC [ Ps c     Send Device Attributes (DA)
	                 Ps = 0  or omitted -> request attributes from terminal
	                 -> ESC [ ? 1 ; 2 c  (``I am a  VT100  with  Advanced  Video
	               Option.'')
	ESC [ Ps ; Ps f Horizontal and Vertical  Position  [row;column]  (default  =
	               [1,1]) (HVP)
	ESC [ Ps g     Tab Clear (TBC)
	                 Ps = 0  -> Clear Current Column (default)
	                 Ps = 3  -> Clear All
	ESC [ Pm h     Set Mode (SM)
	                 Ps = 4  -> Insert Mode (IRM)
	                 Ps = 2 0  -> Automatic Newline (LNM)
	ESC [ Pm l     Reset Mode (RM)
	                 Ps = 4  -> Replace Mode (IRM)
	                 Ps = 2 0  -> Normal Linefeed (LNM)
	ESC [ Pm m     Character Attributes (SGR)
	                 Ps = 0  -> Normal (default)
	                 Ps = 1  -> Bold
	                 Ps = 4  -> Underscore
	                 Ps = 5  -> Blink (appears as Bold)
	                 Ps = 7  -> Inverse
	ESC [ Ps n     Device Status Report (DSR)
	                 Ps = 5  -> Status Report ESC [ 0 n  (``OK'')
	                 Ps = 6  -> Report Cursor Position (CPR) [row;column] as ESC
	               [ r ; c R
	ESC [ Ps ; Ps r Set Scrolling Region [top;bottom] (default =  full  size  of
	               window) (DECSTBM)
	ESC [ Ps x     Request Terminal Parameters (DECREQTPARM)
	ESC [ ? Pm h   DEC Private Mode Set (DECSET)
	                 Ps = 1  -> Application Cursor Keys (DECCKM)
	                 Ps = 2  -> Designate USASCII for character sets G0-G3.  (In
	               the  VT102,  this  selects  VT52  mode  (DECANM), which xterm
	               doesn't support.)
	                 Ps = 3  -> 132 Column Mode (DECCOLM)
	                 Ps = 4  -> Smooth (Slow) Scroll (DECSCLM)
	                 Ps = 5  -> Reverse Video (DECSCNM)
	                 Ps = 6  -> Origin Mode (DECOM)
	                 Ps = 7  -> Wraparound Mode (DECAWM)
	                 Ps = 8  -> Auto-repeat Keys (DECARM)
	                 Ps = 9  -> Send Mouse X & Y on button press.  See the  sec-
	               tion Mouse Tracking.
	                 Ps = 3 8  -> Enter Tektronix Mode (DECTEK)
	                 Ps = 4 0  -> Allow 80 <--> 132 Mode
	                 Ps = 4 1  -> more(1) fix (see curses resource)
	                 Ps = 4 4  -> Turn On Margin Bell
	                 Ps = 4 5  -> Reverse-wraparound Mode
	                 Ps =  4  6   ->  Start  Logging  (normally  disabled  by  a
	               compile-time option)
	                 Ps = 4 7  -> Use Alternate Screen Buffer  (unless  disabled
	               by the titeInhibit resource)
	                 Ps = 1 0 0 0  -> Send Mouse X  &  Y  on  button  press  and
	               release.  See the section Mouse Tracking.
	                 Ps = 1 0 0 1  -> Use Hilite Mouse Tracking.  See  the  sec-
	               tion Mouse Tracking.
	ESC [ ? Pm l   DEC Private Mode Reset (DECRST)
	                 Ps = 1  -> Normal Cursor Keys (DECCKM)
	                 Ps = 3  -> 80 Column Mode (DECCOLM)
	                 Ps = 4  -> Jump (Fast) Scroll (DECSCLM)
	                 Ps = 5  -> Normal Video (DECSCNM)
	                 Ps = 6  -> Normal Cursor Mode (DECOM)
	                 Ps = 7  -> No Wraparound Mode (DECAWM)
	                 Ps = 8  -> No Auto-repeat Keys (DECARM)
	                 Ps = 9  -> Don't Send Mouse X & Y on button press
	                 Ps = 4 0  -> Disallow 80 <--> 132 Mode
	                 Ps = 4 1  -> No more(1) fix (see curses resource)
	                 Ps = 4 4  -> Turn Off Margin Bell
	                 Ps = 4 5  -> No Reverse-wraparound Mode
	                 Ps = 4 6  -> Stop Logging (normally disabled by a  compile-
	               time option)
	                 Ps = 4 7  -> Use Normal Screen Buffer
	                 Ps = 1 0 0 0  -> Don't Send Mouse X & Y on button press and
	               release
	                 Ps = 1 0 0 1  -> Don't Use Hilite Mouse Tracking
	ESC [ ? Pm r   Restore DEC Private Mode Values.  The value of Ps  previously
	               saved is restored.  Ps values are the same as for DECSET.
	ESC [ ? Pm s   Save DEC Private Mode Values.  Ps values are the same as  for
	               DECSET.
	ESC ] Ps ; Pt BEL
	               Set Text Parameters
	                 Ps = 0  -> Change Icon Name and Window Title to Pt
	                 Ps = 1  -> Change Icon Name to Pt
	                 Ps = 2  -> Change Window Title to Pt
	                 Ps = 4 6  -> Change Log File to Pt (normally disabled by  a
	               compile-time option)
	                 Ps = 5 0  -> Set Font to Pt
	ESC ^ Pt ESC \ Privacy Message (PM)
	                 xterm implements no PM functions; Pt is ignored.   Pt  need
	               not be printable characters.
	ESC _ Pt ESC \ Application Program Command (APC)
	                 xterm implements no APC functions; Pt is ignored.  Pt  need
	               not be printable characters.
	ESC c          Full Reset (RIS)
	ESC l          Memory Lock (per HP terminals).  Locks memory above the  cur-
	               sor.
	ESC m          Memory Unlock (per HP terminals)
	ESC n          Invoke the G2 Character Set (LS2)
	ESC o          Invoke the G3 Character Set (LS3)
	ESC |          Invoke the G3 Character Set as GR  (LS3R).   Has  no  visible
	               effect in xterm.
	ESC }          Invoke the G2 Character Set as GR  (LS2R).   Has  no  visible
	               effect in xterm.
	ESC ~          Invoke the G1 Character Set as GR  (LS1R).   Has  no  visible
	               effect in xterm.

Mouse Tracking
	The VT widget can be set to send the mouse position and other information on
button  presses.   These modes are typically used by editors and other full-
screen applications that want to make use of the mouse.
	There are three mutually exclusive modes, each enabled (or  disabled)  by  a
different  parameter  in the DECSET (or DECRST) escape sequence.  Parameters
for all mouse tracking escape sequences generated by  xterm  encode  numeric
parameters  in  a single character as value+040.  For example, !  is 1.  The
screen coodinate system is 1-based.
	X10 compatibility mode sends an escape sequence on button press encoding the
location  and the mouse button pressed.  It is enabled by specifying parame-
ter 9 to DECSET.  On button press, xterm sends ESC [  M  CbCxCy  (6  charac-
ters).   Cb is button-1.  Cx and Cy are the x and y coordinates of the mouse
when the button was pressed.
	Normal tracking mode sends an escape  sequence  on  both  button  press  and
release.   Modifier  information  is also sent.  It is enabled by specifying
parameter 1000 to DECSET.  On button press or release, xterm sends ESC  [  M
CbCxCy.   The  low two bits of Cb encode button information:  0=MB1 pressed,
1=MB2 pressed, 2=MB3 pressed, 3=release.  The upper bits encode what  modif-
iers were down when the button was pressed and are added together.  4=Shift,
8=Meta, 16=Control.  Cx and Cy are the x and  y  coordinates  of  the  mouse
event.  The upper left corner is (1,1).
	Mouse hilite tracking notifies a program of a button press, receives a range
of lines from the program, highlights the region covered by the mouse within
that range until button release, and then  sends  the  program  the  release
coordinates.   It  is enabled by specifying parameter 1001 to DECSET.  Warn-
ing: use of this mode requires a cooperating program or it will hang  xterm.
On  button  press, the same information as for normal tracking is generated;
xterm then waits for the program to send mouse tracking information.  All  X
events  are  ignored  until  the proper escape sequence is received from the
pty:  ESC [ Ps ; Ps ; Ps ; Ps ; Ps T .  The  parameters  are  func,  startx,
starty, firstrow, and lastrow.  func is non-zero to initiate hilite tracking
and zero to abort.  startx and starty give the starting x and y location for
the  highlighted  region.   The  ending  location tracks the mouse, but will
never be above row firstrow and will always be above row lastrow.  (The  top
of  the  screen  is  row 1.)  When the button is released, xterm reports the
ending position one of two ways: if the start and end coordinates are  valid
text  locations:  ESC [ t CxCy.  If either coordinate is past the end of the
line:  ESC [ T CxCyCxCyCxCy.  The parameters are startx, starty, endx, endy,
mousex,  and  mousey.   startx, starty, endx, and endy give the starting and
ending character positions of the region.  mousex and mousey give the  loca-
tion of the mouse at button up, which may not be over a character.

Tektronix 4014 Mode
	Most of these sequences  are  standard  Tektronix  4014  control  sequences.
Graph  mode supports the 12-bit addressing of the Tektronix 4014.  The major
features missing are the write-thru and defocused modes.  This document does
not  describe  the commands used in the various Tektronix plotting modes but
does describe the commands to switch modes.

	BEL            Bell (Ctrl-G)
	BS             Backspace (Ctrl-H)
	TAB            Horizontal Tab (Ctrl-I)
	LF             Line Feed or New Line (Ctrl-J)
	VT             Cursor up (Ctrl-K)
	FF             Form Feed or New Page (Ctrl-L)
	CR             Carriage Return (Ctrl-M)
	ESC ETX        Switch to VT100 Mode (ESC Ctrl-C)
	ESC ENQ        Return Terminal Status (ESC Ctrl-E)
	ESC FF         PAGE (Clear Screen) (ESC Ctrl-L)
	ESC SO         Begin 4015 APL mode (ignored by xterm) (ESC Ctrl-N)
	ESC SI         End 4015 APL mode (ignored by xterm) (ESC Ctrl-O)
	ESC ETB        COPY (Save Tektronix  Codes  to  file  COPYyy-mm-dd.hh:mm:ss)
	               (ESC Ctrl-W)
	ESC CAN        Bypass Condition (ESC Ctrl-X)
	ESC SUB        GIN mode (ESC Ctrl-Z)
	ESC FS         Special Point Plot Mode (ESC Ctrl-\)
	ESC 8          Select Large Character Set
	ESC 9          Select #2 Character Set
	ESC :          Select #3 Character Set
	ESC ;          Select Small Character Set
	ESC ] Ps ; Pt BEL
	               Set Text Parameters of VT window
	                 Ps = 0  -> Change Icon Name and Window Title to Pt
	                 Ps = 1  -> Change Icon Name to Pt
	                 Ps = 2  -> Change Window Title to Pt
	                 Ps = 4 6  -> Change Log File to Pt (normally disabled by  a
	               compile-time option)
	ESC `          Normal Z Axis and Normal (solid) Vectors
	ESC a          Normal Z Axis and Dotted Line Vectors
	ESC b          Normal Z Axis and Dot-Dashed Vectors
	ESC c          Normal Z Axis and Short-Dashed Vectors
	ESC d          Normal Z Axis and Long-Dashed Vectors
	ESC h          Defocused Z Axis and Normal (solid) Vectors
	ESC i          Defocused Z Axis and Dotted Line Vectors
	ESC j          Defocused Z Axis and Dot-Dashed Vectors
	ESC k          Defocused Z Axis and Short-Dashed Vectors
	ESC l          Defocused Z Axis and Long-Dashed Vectors
	ESC p          Write-Thru Mode and Normal (solid) Vectors
	ESC q          Write-Thru Mode and Dotted Line Vectors
	ESC r          Write-Thru Mode and Dot-Dashed Vectors
	ESC s          Write-Thru Mode and Short-Dashed Vectors
	ESC t          Write-Thru Mode and Long-Dashed Vectors
	FS             Point Plot Mode (Ctrl-\)
	GS             Graph Mode (Ctrl-])
	RS             Incremental Plot Mode (Ctrl-^)
	US             Alpha Mode (Ctrl-_)

	*/
::::::::::::::
terminfo.cpp
::::::::::::::
// see man terminfo , manual tparm
#include

main()
{
  printf("\033]2; my xterm. \007");
}
::::::::::::::
TermOut.cpp
::::::::::::::
#include 
#include 
#include 
#include 
#include  // struct termios
#include  // STDIN_FILENO
#include 
//#include  // for winsize
//#include 
#include  // for winsize
#define A_STDIN_FILENO 0

struct termios term, termsave;
int size;
char TermName[L_ctermid];
int iBS = 50*50;
char c;
int i;

TermAttributes()
{
  if (isatty(STDIN_FILENO)) cout << "tty" << endl;
  ctermid(TermName); cout << TermName << endl;
  if (tcgetattr(STDIN_FILENO, &termsave) < 0) cout << "get error" << endl;
  term = termsave;
  size = term.c_cflag & CSIZE;
  cout << size << endl
       << (term.c_lflag) << endl
       << (term.c_lflag & ECHONL) << endl
       << (term.c_lflag & ECHO) << endl;
  term.c_cflag &= ~CSIZE;
  term.c_cflag |= CS8;
  if (tcsetattr(STDIN_FILENO, TCSANOW, &term) < 0) 
    cout << "set error" << endl;
  cout << (term.c_cflag & CSIZE) << endl;
  size = term.c_cflag & CSIZE;
  cout << size << endl;
  term.c_lflag |= ECHONL;
  if (tcsetattr(STDIN_FILENO, TCSANOW, &term) < 0) 
    cout << "set error" << endl;
  cout << (term.c_lflag & ECHONL) << endl;
  if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &termsave) < 0) 
    cout << "set error" << endl;  
}

tty_reset(int fd)
{
  if (tcsetattr(fd, TCSANOW, &termsave) < 0) 
    cout << "set error" << endl;  
}

tty_cbraek(int fd)
{
  term = termsave; 
  term.c_lflag &= ~(ECHO | ICANON | IEXTEN);
  term.c_iflag &= ~(ICRNL | IXON | INPCK);
  term.c_oflag &= ~(OPOST);
  term.c_cc[VMIN] = 1;
  term.c_cc[VTIME] = 0;
  if (tcsetattr(fd, TCSANOW, &term) < 0) 
    cout << "set error" << endl;  
}

tty_noncanonical(int fd)
{
  term = termsave; 
  term.c_lflag &= ~(ICANON);
  term.c_cc[VMIN] = 10*iBS; // buffer size
  term.c_cc[VTIME] = 0;
  if (tcsetattr(fd, TCSANOW, &term) < 0) 
    cout << "set error" << endl;  
}


NonCanonical()
{
  tty_cbraek(STDIN_FILENO);
  while (read(STDIN_FILENO, &c, 1) == 1) cout << c << "\n";
  tty_reset(STDIN_FILENO);
}

NonCanonicalFullScreen()
{
  clock_t cstart, cfinish, start, finish;
  time_t cs, cf, s, f;
  char cSceenBuffer[iBS];
  for(i=1;i
#include
#include
#include
#include
#include
#include
#include
#include

#include
#include

#define BufSize 256
#define PAGER "/usr/bin/more"
#define SHELL "/usr/local/bin/bash"

int n, fd[2];
pid_t pid, WaitStatus;
char cBuf[BufSize];
char* pager;
char cOpt[64];
FILE *fPin;
int i;


HandmadePipe()
{
  if(pipe(fd) < 0) cout << "pipe error!" << endl;
  if((pid = vfork()) < 0) cout << "fork error!" << endl;
  else if(pid > 0) { // parent (child gets a 0 as pid)
    cout << "parent" << endl;
    close(fd[0]);
    write(fd[1], "hello\n^D", 6);
    do {
    sleep(1);
      if ((WaitStatus = waitpid(pid, NULL, WNOHANG)) < 0) 
        cout << "waitpid error" << endl;
      if (WaitStatus == 0) {
	cout << "child not terminated" << endl;
	kill(pid, SIGINT);
      } 
    } while (WaitStatus <= 0);
    if (WaitStatus > 0)
      cout << "child terminated status: " << WaitStatus << endl;    
  } else  { // child
    cout << "child" << endl;
    close(fd[1]);
    // check stdin
    if (fd[0] != STDIN_FILENO) {
      if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO) 
	cout << "dup2 error!" << endl;
      close(fd[0]); // not needed anymore
    }
    pager = PAGER;
    strcpy(cOpt, "-e");
    execl(pager, (char *) cOpt, (char *) 0);
  }
  cout << "ready to exit pid : " << pid << endl;
  exit(0);
}  

PopenPipe()
{
  if (!(fPin = popen("cat >pipeout", "w"))) cout << "popen error!" << endl;
  fprintf(fPin, "parent to pipe-child....end!");
  if ((pclose(fPin)) == -1) cout << "pclose error!" << endl;
}

PipeToXTerm()
{ 
  if (!(fPin = popen("xterm", "w"))) cout << "popen error!" << endl;
  do { fprintf(fPin, "exit/n"); } while ((waitpid(pid, NULL, WNOHANG)) <= 0);
  if ((pclose(fPin)) == -1) cout << "pclose error!" << endl;
}

HandmadePipeToXTerm()
{ 
  if(pipe(fd) < 0) cout << "pipe error!" << endl;
  if((pid = vfork()) < 0) cout << "fork error!" << endl;
  else if(pid > 0) { // parent (child gets a 0 as pid)
    cout << "parent" << endl;
    close(fd[0]);
    write(fd[1], "hello\n", 6);
    for (i=0;i<100000;i++) {
      write(fd[1], "hello\n", 6);
      fprintf(stdout, "hi child?\n");
    }
  } else  {        // child
    cout << "child" << endl;
    close(fd[1]);
    if (fd[0] != STDIN_FILENO) {
      if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO) 
	cout << "dup2 error!" << endl;
      close(fd[0]); // not needed anymore
    }
    strcpy(cOpt, "-Snn2");
    // X causes problems
    // execlp(SHELL, "bash", "-c", "xterm", cOpt, (char *) 0);
    execlp("/usr/openwin/bin/xterm", "xterm","-t", 
	   (char *) 0);
    //char cc;
    //while ((cc=fgetc(stdin)) != EOF) fputc(toupper(cc), stdout);
    //_exit(127);
    //waitpid(getppid(), NULL, 0);
  }
  cout << "ready to exit pid : " << pid << endl;
  exit(0);
}

// extern char ptsname(int);
/*
PseudoXTerm()
{
  int fdm;
  int fds;
  char ptm_name[15];
  char pts_name[15];
  strcpy(pts_name, "/dev/ptmx"); // we should test for a valid name
  fdm = open(ptm_name, O_RDWR); // open master term
  if((pid = vfork()) < 0) cout << "fork error!" << endl;
  if(pid == 0) { // child
    cout << "child" << endl;
    strcpy(pts_name, ptsname(fdm)); // get slave name
    fds = open(pts_name, O_RDWR); // open slave term
    close(fdm); // close master in child
    // some BSD specials
    //    if (ioctl(fds, TIOCSCTTY, (char *) 0) < 0) cout << "ioctl error" << endl;
    if (dup2(fds, STDIN_FILENO) != STDIN_FILENO)
      cout << "dup2 error!" << endl;
    if (dup2(fds, STDOUT_FILENO) != STDOUT_FILENO)
      cout << "dup2 error!" << endl;
    if (dup2(fds, STDERR_FILENO) != STDERR_FILENO)
      cout << "dup2 error!" << endl;
    close(fds);
    cout << "still child" << endl;
    execlp("/usr/openwin/bin/xterm", "xterm", "-Smx2", (char *) 0);
    _exit(127);
  } else { // parent
    cout << "parent" << endl;
    for (;;) ;

  }
}
*/
main()
{
  // HandmadePipe();
  // PopenPipe();
   HandmadePipeToXTerm();
  // PseudoXTerm();
}
::::::::::::::
++test.cpp
::::::::::::::

#include 
#include 


main() {

int i=4;
cout <

class A {
public:
  A() { strcpy(Var,"A"); }
  void Func() { cout<<"this:"<Var<Var<Func();
  B* b = new B(); b->Func();
  b->fp = &(a->Func); b->a = a;
  b->CallFuncA();
}
::::::::::::::
time.cpp
::::::::::::::
#include 
#include 
#include  // sleep
#include 
#include 

main() {
  //unsigned int 
  unsigned int i,ii,iii,iv;
  double j;
  time_t  t=time(NULL);
  cout<<"CLOCKS_PER_SEC:"<
#include 

#define SQUARE(x) (x*x)
 
int B=4; // : Number of memory cell blocks.
int S=2; //: Number of memory cells in each block.
int I=7; //: Number of input units.
int K=7; //: Number of output units.
int BS; // = B*S : Total number of memory cells.
int SG; // = S+2 : Number of cells and gates in each block.
int BSG; // = (B*(S+2)) : Total number of memory cell and gates.
int Standard, Cascade, FiOrBl;

main() {
  ofstream St,Ca,Fi,GCa; 
  St.open("Standard.dat"); Ca.open("Cascade.dat");
  Fi.open("First-Order.dat"); GCa.open("Grown-Cascate.dat");
  for (B=1;B<11;B++) {
    BS = B*S;
    SG = S+2;
    BSG = B*SG;
    Standard = SQUARE(BSG) + BS*K + BSG*I + BS*(I+BSG)*3;
    Cascade = B*SQUARE(SG) + BS*K + BSG*I + BS*(SG+I)*3;
    for(int i=1;i
#include 

main()
{ 
  int i1=0, i2=0, i3=0;
  char c[51];
  double d;
  long lFilePos=432;
  ifstream* f;
  f = new ifstream("Topo.map", ios::in);
  if (!f) { cout << "not f" << endl; return 0; }
  f->seekg(lFilePos);
  cout << "rewind to: " << lFilePos << "\t"
       << "actual position: " << f->tellg() << "\n";
  f->scan("# ulUnitNb:"); *f >> i1; cout << i1 << endl;
  f->ignore(1000, '\n');
  f->scan("Type:"); *f >> c; cout << "Type: " << c << endl;
  f->scan("# pdSpecPar:"); f->ignore(1000, '\n');
  f->scan("iNbSpecPar:"); *f >> i2;  cout << i2 << endl;

  delete f;
}
::::::::::::::
typecast.cpp
::::::::::::::

#include 
#include 

#define FREQ 7

main() {
  double d;
  for(unsigned int i=0;i<25;i++) {
    d=(double)((unsigned int) (i/FREQ))*FREQ;
    cout<
#include 
#include 
#include  // system
#include  // sleep 

void
TypeInfo() {
  double *pd = new double(34);
  double dd = 34;
  cout << typeid(pd).name() << endl;
  cout << typeid(dd).name() << endl;
}

main() {
  TypeInfo();
}

::::::::::::::
VariableNbFuncPara.cpp
::::::::::::::
#include 
#include 
// #include  // There is an other way for traditional C

int i1,i2,i3,i4,i5;
int NbStr = 3;
char *Str[] = {"one","two","three"};

Func(int ai1, int ai2,...)
{
  i1 = ai1;
  i2 = ai2;
  va_list ap; va_start(ap,ai2);
  i3 = va_arg(ap, int);
  i4 = va_arg(ap, int);
  i5 = va_arg(ap, int);
  va_end(ap);
}

FuncStrings(int aNbStr,...)
{
  char **S = new (char *)[aNbStr];
  for(int i=0; i

class A
{
public:
  virtual void Out()  { cout << "A" << endl; }
};

class B : public A
{
public:
  inline void Out()  { cout << "B" << endl; }
};

class C : public  B
{
public:
  virtual void Out()  { cout << "C" << endl; }
};

main()
{
  A a; B b; C c;
  a.Out();b.Out();c.Out();
}

::::::::::::::
XTermIO.cpp
::::::::::::::
#include 
#include 
#include 
#include 
#include  // struct termios
#include  // STDIN_FILENO
#include 
//#include  // for winsize
//#include 
#include  // for winsize
#define A_STDIN_FILENO 0

struct termios term, termsave;
int size;
char TermName[L_ctermid];
int iBS = 50*50;
char c;
int i;

TermAttributes()
{
  if (isatty(STDIN_FILENO)) cout << "tty" << endl;
  ctermid(TermName); cout << TermName << endl;
  if (tcgetattr(STDIN_FILENO, &termsave) < 0) cout << "get error" << endl;
  term = termsave;
  size = term.c_cflag & CSIZE;
  cout << size << endl
       << (term.c_lflag) << endl
       << (term.c_lflag & ECHONL) << endl
       << (term.c_lflag & ECHO) << endl;
  term.c_cflag &= ~CSIZE;
  term.c_cflag |= CS8;
  if (tcsetattr(STDIN_FILENO, TCSANOW, &term) < 0) 
    cout << "set error" << endl;
  cout << (term.c_cflag & CSIZE) << endl;
  size = term.c_cflag & CSIZE;
  cout << size << endl;
  term.c_lflag |= ECHONL;
  if (tcsetattr(STDIN_FILENO, TCSANOW, &term) < 0) 
    cout << "set error" << endl;
  cout << (term.c_lflag & ECHONL) << endl;
  if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &termsave) < 0) 
    cout << "set error" << endl;  
}

tty_reset(int fd)
{
  if (tcsetattr(fd, TCSANOW, &termsave) < 0) 
    cout << "set error" << endl;  
}

tty_cbraek(int fd)
{
  term = termsave; 
  term.c_lflag &= ~(ECHO | ICANON | IEXTEN);
  term.c_iflag &= ~(ICRNL | IXON | INPCK);
  term.c_oflag &= ~(OPOST);
  term.c_cc[VMIN] = 1;
  term.c_cc[VTIME] = 0;
  if (tcsetattr(fd, TCSANOW, &term) < 0) 
    cout << "set error" << endl;  
}

tty_noncanonical(int fd)
{
  term = termsave; 
  term.c_lflag &= ~(ICANON);
  term.c_cc[VMIN] = 10*iBS; // buffer size
  term.c_cc[VTIME] = 0;
  if (tcsetattr(fd, TCSANOW, &term) < 0) 
    cout << "set error" << endl;  
}


NonCanonical()
{
  tty_cbraek(STDIN_FILENO);
  while (read(STDIN_FILENO, &c, 1) == 1) cout << c << "\n";
  tty_reset(STDIN_FILENO);
}

NonCanonicalFullScreen()
{
  clock_t cstart, cfinish, start, finish;
  time_t cs, cf, s, f;
  char cSceenBuffer[iBS];
  for(i=1;i


class C {
public:
  C() { i =17; }
  C *F() { i =18; return new C; }
 int i;
};

main()
{
 C *c, *cc;
 //c = NULL;
 cc = c;
 c = c->F();
 cout << c << "   " << cc << endl;
 int ii = c->i;
 cout << ii << endl;
 ii = cc->i;
 cout << ii << endl;
}