Page History
...
Code Block |
---|
#include <stdlib.h>
#include <string> // for string, substring
#include <sstream> // for stringstream
#include <iostream> // for cout, puts etc.
#include <stdio.h> // for sprintf, printf( "%lf\n", accum );
#include <time.h> // time
#include <fcntl.h> // open()
#include <unistd.h> // read()
#include <iomanip> // for setw
#include <fstream> // for ifstream
#include <cstring> // for memcpy, placed in the std namespace
#include <cstddef> // for size_t
#include <stdint.h> // uint8_t, uint32_t, etc.
using namespace std; // allows get rid of std:: prefix.
|
...
Code Block |
---|
std::string s("121 151 225 456"); std::stringstream ss(s); T val; do { ss >> val; cout << val << endl; } while( ss.good() ); |
...
String methods
Code Block |
---|
#include <fstream> // for ifstream<string> std::string basename(const 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::cout << "val: " << val << '\n';
}
f.close(); |
Input from file line by line
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 <fstream> // for ifstream std::ifstream f("file.txt"); std::string lineval; while (std::getline(f, line))f>>val) { std::cout << "lineval: " << lineval << '\n'; } f.close(); |
Print long space or repeated character
std::cout << std::setw(80) << " " << std::setw(4);
std::cout << std::setw(20) << setfill('=') << '=';
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
Check if the n-th bit is on: if( m_print_bits &
(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 <sys/stat.h>
bool dir_exists(const std::string& dir)
|
Code Block |
#include <iostream> #include <dirent.h> using namespace std; int main() { struct stat st; DIR* 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; dirent* pdir; dir = opendir("."); // open current directory while (pdir = readdir(dir)) { DIR* dir; dirent* pdir; cout << pdir->d_name << endl; dir = opendir("."); // open current }directory while (pdir = closedirreaddir(dir);) { return 0; } |
Using boost
cout << pdir->d_name << endl;
}
closedir(dir);
return 0;
}
|
Using boost
Code Block |
---|
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
fs::path path = " |
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 typedefxtc/e158-r0150-s00-c01.xtc"; fs::directory_iteratorpath dir_iter; = 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"; } |
...
Code Block |
---|
fs::path path = m_path; std::cout << "stem = " << path.stem().string() << "\n"; // e158-r0150-s00-c00 std::cout << "extension() = " << path.extension().string() << "\n"; // .xtc std::cout << "filename() = " << path.filename().string() << "\n"; // e158-r0150-s00-c00.xtc std::cout << "parent_path() = " << path.parent_path().string() << "\n"; // /reg/d/psdm/CXI/cxi49012/xtc |
Singleton
InputParameters.h :
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 |
---|
shared_ptr< ndarray<T,NDim> > shp = evt.get(m_source, m_key, &m_src |
Code Block |
#include <iostream> // for cout class InputParameters { public: static InputParameters* instance(); void print(); private: InputParameters () ; if (shp.get()) { ndarray<T,NDim>* pnda = shp.get(); // !!!!! Private so that it canndarray<const 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& ) ; }; |
InputParameters.cc :
Code Block |
---|
#include "<Package>/InputParameters.h"
InputParameters* InputParameters::m_pInstance = NULL; // !!!!!! make global pointer !!!!!
//----------------
InputParameters::InputParameters ()
{
std::cout << "!!!!!!!! Single instance for singleton class InputParameters is created \n";
}
//----------------
InputParameters* InputParameters::instance()
{
if( !m_pInstance ) m_pInstance = new InputParameters();
return m_pInstance;
}
//----------------
void InputParameters::print() { std::cout << "InputParameters::print()\n"; }
|
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> // 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& ) ;
};
|
InputParameters.cc Calls :
Code Block |
---|
#include "<Package>/InputParameters.h"
int main(int argc, char *argv[])
{
InputParameters::instance()->print("xyz...");
}
|
Shortcuts:
Code Block |
---|
#define PRINT InputParameters::instance()->print
int main(){
PRINT("This is a line of log");
return 0;
}
|
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; |
InputParameters* InputParameters::m_pInstance = NULL; // !!!!!! make global pointer !!!!!
//----------------
InputParameters::InputParameters ()
{
std::cout << "!!!!!!!! Single instance for singleton class InputParameters is created \n";
}
//----------------
InputParameters* InputParameters::instance()
{
if( !m_pInstance ) m_pInstance = new InputParameters();
return m_pInstance;
}
//----------------
void InputParameters::print() { std::cout << "InputParameters::print()\n"; }
|
Calls:
Code Block |
---|
#include "<Package>/InputParameters.h"
int main(int argc, char *argv[])
{
InputParameters::instance()->print("xyz...");
}
|
Shortcuts:
Code Block |
---|
#define PRINT InputParameters::instance()->print
int main(){
PRINT("This is a line of log");
return 0;
}
|
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;
} |
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
...