Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
#include <string> 

std::string basename(const std::string& path)
{
  size_t pos = path.find_last_of('/');
  //if (pos == std::string::npos) return std::string();
  if (pos < path.size()-1) return std::string(path,pos+1);
  else return std::string();
}

 

...

 

Input from file value by value

Code Block
#include <sys/stat.h><fstream>  // for ifstream

   bool dir_exists(conststd::ifstream f("file.txt");
  std::string& dir)val;
  while (f>>val) {
     struct stat st;
    if( (stat(dir.c_str(),&st) == 0) && (((st.st_mode) & S_IFMT) == S_IFDIR) ) return true;
    return false;
  }

 

Check if file exists

 std::cout << "val: " << val << '\n';
  }
  f.close();

Input from file line by line

 

Code Block
#include <fstream>  // for ifstream

  
Code Block
#include <fstream>  // for ifstream

  std::ifstream f("file.txt");
  if(not f.good()) ...

 

Input from file value by value

Code Block
#include <fstream>  // for ifstream

  std::ifstream f("file.txt");
  std::string val;
  while (f>>val) {
      std::std::string line;
  while (std::getline(f, line)) {
      std::cout << "valline: " << valline << '\n';
  }
  f.close();

Input from file line by line

 

Code Block
#include <fstream>  // for ifstream

  std::ifstream f("file.txt");
  std::string line;
  while (std::getline(f, line)) {
      std::cout << "line: " << line << '\n';
  }
  f.close();

Print long space or repeated character

std::cout << std::setw(80) << " " << std::setw(4);

std::cout << std::setw(20) << setfill('=') << '=';

Bit operations

Print long space or repeated character

std::cout << std::setw(80) << " " << std::setw(4);

std::cout << std::setw(20) << setfill('=') << '=';

Bit operations

Check if the n-th bit is on: if( m_print_bits & (Check if the n-th bit is on: if( m_print_bits & (1 << n) ) ...

Set n-th bit: mask |=  (1 << n)

Clear n-th bit: bit_fld &= ~(1 << n)

Toggle (swap 0<->1) n-th bit: bit_fld ^= (1 << n)

Check if the element is in the vector or list

...

Code Block
#include <getopt.h>
#include <stdio.h>
#include <iostream>
//===================
void usage(char* name) {
  std::cout << "Usage: " << name << " [-a <aaa>] [-b <bbb>] [-c <ccc>] [-h] <p1> [<p2> [<p3> ...]] \n";
}
//===================
int main (int argc, char **argv)
{
    char *avalue = NULL;
    char *bvalue = NULL;
    char *cvalue = NULL;
    int index;
    int c;
    extern char *optarg;
    extern int optind, optopt, opterr;

    while ((c = getopt (argc, argv, ":a:b:c:h")) != -1)
        switch (c)
        {
          case 'a':
            avalue = optarg;
            printf ("a: avalue = %s\n",avalue);
            break;
          case 'b':
            bvalue = optarg;
            printf ("b: bvalue = %s\n",bvalue);
            break;
          case 'c':
            cvalue = optarg;
            printf ("c: cvalue = %s\n",cvalue);
            break;
          case 'h':
            printf ("h: ");
	    usage(argv[0]);
            break;
          case ':':
            printf ("(:) Option -%c requires an argument.\n", optopt);
	    usage(argv[0]);
            return EXIT_FAILURE;
          case '?':
            printf ("?: Option -%c requires an argument.\n", optopt);
	    usage(argv[0]);
            return EXIT_FAILURE;
          default:
            printf ("default: You should not get here... option -%c .\n", optopt);
            abort ();
        }

    printf ("End of options: avalue = %s, bvalue = %s, cvalue = %s\n",
            avalue, bvalue, cvalue);

    for (index = optind; index < argc; index++)
        printf ("Non-option argument %s\n", argv[index]);
    return EXIT_SUCCESS;
}

Iterate over files in the directory

Using opendir, readdir, closedir from STL

Check if directory exists

Code Block
#include <iostream>
#include <dirent<sys/stat.h>

using namespace std;

int main()  bool dir_exists(const std::string& dir)
  {
    struct stat st;
   DIR*     dir;
        dirent*  pdir;

   if( (stat(dir.c_str(),&st) == 0) && (((st.st_mode) & S_IFMT) == S_IFDIR) ) return true;
    return false;
  }

 

Check if file exists

Code Block
#include <fstream>  // for ifstream

  std::ifstream f("file.txt");
  if(not f.good()) ...

 

Iterate over files in the directory

Using opendir, readdir, closedir from STL

Code Block
#include <iostream>
#include <dirent.h>
using namespace std;

int main() dir = opendir(".");      // open current directory
        while (pdir = readdir(dir)) {
        DIR*     dir;
   cout << pdir->d_name << endl  dirent*  pdir;

        }
 dir = opendir(".");       closedir(dir);
  // open current directory
      return 0;
}

Using boost

Code Block
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;

  fs::path path = "/reg/d/psdm/CXI/cxi49012/xtc/e158-r0150-s00-c01.xtc";
  fs::path dir  = path.parent_path(); // i.e.: /reg/d/psdm/CXI/cxi49012/xtc

  typedef fs::directory_iterator dir_iter;
  for (dir_iter dit = dir_iter(dir); dit != dir_iter(); ++ dit) {
    std::cout << dit->path().stem().string() << "\n";  
  } 

Other methods of fs::path

 while (pdir = readdir(dir)) {
                cout << pdir->d_name << endl;
        }
        closedir(dir);
        return 0;
}

Using boost

Code Block
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;

Code Block
  fs::path path = m_path"/reg/d/psdm/CXI/cxi49012/xtc/e158-r0150-s00-c01.xtc";
  stdfs::coutpath <<dir "stem = path.parent_path(); // i.e.: /reg/d/psdm/CXI/cxi49012/xtc

  typedef fs::directory_iterator dir_iter;
  = " << path.stem().string() << "\n";            // e158-r0150-s00-c00
  for (dir_iter dit = dir_iter(dir); dit != dir_iter(); ++ dit) {
    std::cout << "extensiondit->path()   = " << path.extension.stem().string() << "\n";  
  } 

Other methods of fs::path

Code Block
  fs::path path = m_path;  // .xtc
  std::cout << "filename()stem          = " << path.filenamestem().string() << "\n";            // e158-r0150-s00-c00.xtc
  std::cout << "parent_pathextension()   = " << path.parent_pathextension().string() << "\n";       // /reg/d/psdm/CXI/cxi49012/xtc

ndarray and shared pointer

Example of how to access ndarray data in psana module through the shared pointer and construct ndarray<const T,NDim>

Code Block
    .xtc
  std::cout << "filename()    shared_ptr< ndarray<T,NDim> > shp = evt.get(m_source, m_key, &m_src);
= " << path.filename().string() << "\n";        if (shp.get()) {

          ndarray<T,NDim>* pnda = shp.get();
// e158-r0150-s00-c00.xtc
  std::cout << "parent_path() = " << path.parent_path().string() << "\n";     // /reg/d/psdm/CXI/cxi49012/xtc

ndarray and shared pointer

Example of how to access ndarray data in psana module through the shared pointer and construct ndarray<const T,NDim>

Code Block
     ndarray<const  T,NDim> nda_const(pnda->data(), pnda->shape());

shared_ptr< ndarray<T,NDim> > shp = evt.get(m_source, m_key, &m_src);
          ndarray<const T,NDim> nda_const(shp->data(), shp->shape());
if (shp.get()) {

          }

 

 

 

Singleton

InputParameters.h :

Code Block
#include <iostream> // for cout

class InputParameters  {
public:
  static InputParameters* instance();
  void print();

private:
  InputParameters () ;ndarray<T,NDim>* pnda = shp.get();
          ndarray<const T,NDim> nda_const(pnda->data(), pnda->shape());

          ndarray<const T,NDim> nda_const(shp->data(), shp->shape());
        }

 

 

 

Singleton

InputParameters.h :

Code Block
#include <iostream> // !!!!! Private so that it can not be called from outside
  for cout

class InputParameters  {
public:
  static InputParameters* instance();
  void print();

private:
  InputParameters () ;                 // !!!!! Private so that it can not be called from outside
  virtual ~InputParameters () {}; 

  static InputParameters* m_pInstance; // !!!!! Singleton instance

  // Copy constructor and assignment are disabled by default
  InputParameters ( const InputParameters& ) ;
  InputParameters& operator = ( const InputParameters& ) ;
};

...

Declaration, Initialization, Definition of static const parameters

Code Block
// *.h :
class A {
public:

  static const int     INT_PAR    = 185;
  static const double  DOUBLE_PAR; 
}

// *.cpp :
const int    A::INT_PAR;
const double A::DOUBLE_PAR = 109.92;

 

Issue OS command from C++

Use method system

Code Block
// int system (const char* command);

#include <stdlib.h>     /* system, NULL, EXIT_FAILURE */
int status = system ("ls -l");

Use method popen

 

Code Block
#include <string>
#include <iostream>
#include <stdio.h>

std::string exec(char* cmd) {
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
    	if(fgets(buffer, 128, pipe) != NULL)
    		result += buffer;
    }
    pclose(pipe);
    return result;
}

 

 

 

 

 

 

 

...

parameters

Code Block
// *.h :
class A {
public:

  static const int     INT_PAR    = 185;
  static const double  DOUBLE_PAR; 
}

// *.cpp :
const int    A::INT_PAR;
const double A::DOUBLE_PAR = 109.92;

 

Issue OS command from C++

Use method system

Code Block
// int system (const char* command);

#include <stdlib.h>     /* system, NULL, EXIT_FAILURE */
int status = system ("ls -l");

Use method popen

 

Code Block
#include <string>
#include <iostream>
#include <stdio.h>

std::string exec(char* cmd) {
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
    	if(fgets(buffer, 128, pipe) != NULL)
    		result += buffer;
    }
    pclose(pipe);
    return result;
}

 

Valgrind - analysis of job memory consumption

Code Block
valgrind --tool=massif --time-unit=B psana -n 1 -m ImgAlgos.PixCoordsProducer exp=cxi86415:run=62

this command runs the job and produces the file like massif.out.23864, which can be printed by command:

Code Block
ms_print massif.out.23864

Building C/C++ library using  distutils.core  setup, Extension

http://stackoverflow.com/questions/16854066/using-distutils-and-build-clib-to-build-c-library

Instead of passing a library name as a string, pass a tuple with the sources to compile:

Code Block
# setup.py
#__________

import sys
from distutils.core import setup
from distutils.command.build_clib import build_clib
from distutils.extension import Extension
from Cython.Distutils import build_ext

libhello = ('hello', {'sources': ['hello.c']})  # <<<<==============

ext_modules=[
    Extension("demo", ["demo.pyx"])
]

setup(
        name = 'demo',
        libraries = [libhello],
        cmdclass = {'build_clib': build_clib, 'build_ext': build_ext},
        ext_modules = ext_modules
)
#__________

Using C++ in Cython