Creating an extra object when making a condition C++ - class

When I create a condition in an overloading method operator+ compiler creates an extra object but in a strange way.
Created 0x73fe30
Created 0x73fe20
Created 0x73fdd0
Deleted 0x73fdd0 / 9
Press any key to continue . . .
Deleted 0x73fe10 / 9
Deleted 0x73fe20 / 4
Deleted 0x73fe30 / 5
How can I eliminate this?
If condition is gone the code will be running all right.
Created 0x73fe30
Created 0x73fe20
Created 0x73fe10
Press any key to continue . . .
Deleted 0x73fe10 / 9
Deleted 0x73fe20 / 4
Deleted 0x73fe30 / 5
The code:
#include <iostream>
using std::cout;
using std::ostream;
using std::endl;
class Numbers
{
friend Numbers operator+(Numbers & a, Numbers & b) {
if (a.value){ // Condition. May be any condition e.g. true
Numbers c(a.value+b.value);
return c;
}
}
public:
int value;
Numbers(){}
Numbers(int value) : value(value) {cout << "Created " << this << endl;}
~Numbers(){
cout << "Deleted " << this << " / " << value << endl;
}
};
int main(){
Numbers a(5);
Numbers b(4);
Numbers c = a+b;
system("pause");
}

Related

How to run a simple openMP example using eclipse?

I already have intel basekit installed, and eclipse for C / C ++: (eclipse-inst-jre-linux64.tar.gz), but I can't find a way to run a simple example using openmp.
In the terminal I compile my example with:
icpx -fiopenmp -fopenmp-targets = spir64 random_openmp.cpp
but I can't do the same using eclipse.
Please find the example code below:
# include <iostream>
# include <iomanip>
# include <cmath>
# include <ctime>
# include <omp.h>
using namespace std;
int main ( );
void monte_carlo ( int n, int &seed );
double random_value ( int &seed );
void timestamp ( );
/******************************************************************************/
int main ( void )
/******************************************************************************/
/*
Purpose:
MAIN is the main program for RANDOM_OPENMP.
Discussion:
This program simply explores one issue in the generation of random
numbers in a parallel program. If the random number generator uses
an integer seed to determine the next entry, then it is not easy for
a parallel program to reproduce the same exact sequence.
But what is worse is that it might not be clear how the separate
OpenMP threads should handle the SEED value - as a shared or private
variable? It seems clear that each thread should have a private
seed that is initialized to a distinct value at the beginning of
the computation.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 September 2012
Author:
John Burkardt
*/
{
int n;
int seed;
timestamp ( );
cout << "\n";
cout << "RANDOM_OPENMP\n";
cout << " C++ version\n";
cout << " An OpenMP program using random numbers.\n";
cout << " The random numbers depend on a seed.\n";
cout << " We need to insure that each OpenMP thread\n";
cout << " starts with a different seed.\n";
cout << "\n";
cout << " Number of processors available = " << omp_get_num_procs ( ) << "\n";
cout << " Number of threads = " << omp_get_max_threads ( ) << "\n";
n = 100;
seed = 123456789;
monte_carlo ( n, seed );
/*
Terminate.
*/
cout << "\n";
cout << "RANDOM_OPENMP\n";
cout << " Normal end of execution.\n";
cout << "\n";
timestamp ( );
return 0;
}
/******************************************************************************/
void monte_carlo ( int n, int &seed )
/******************************************************************************/
/*
Purpose:
MONTE_CARLO carries out a Monte Carlo calculation with random values.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 September 2012
Author:
John Burkardt
Parameter:
Input, int N, the number of values to generate.
Input, int &SEED, a seed for the random number generator.
*/
{
int i;
int my_id;
int *my_id_vec;
int my_seed;
int *my_seed_vec;
double *x;
x = new double[n];
my_id_vec = new int[n];
my_seed_vec = new int[n];
# pragma omp master
{
cout << "\n";
cout << " Thread Seed I X(I)\n";
cout << "\n";
}
# pragma omp parallel private ( i, my_id, my_seed ) shared ( my_id_vec, my_seed_vec, n, x )
{
my_id = omp_get_thread_num ( );
my_seed = seed + my_id;
cout << " " << setw(6) << my_id
<< " " << setw(12) << my_seed << "\n";
# pragma omp for
for ( i = 0; i < n; i++ )
{
my_id_vec[i] = my_id;
x[i] = random_value ( my_seed );
my_seed_vec[i] = my_seed;
// cout << " " << setw(6) << my_id
// << " " << setw(12) << my_seed
// << " " << setw(6) << i
// << " " << setw(14) << x[i] << "\n";
}
}
//
// C++ OpenMP IO from multiple processors comes out chaotically.
// For this reason only, we'll save the data from the loop and
// print it in the sequential section!
//
for ( i = 0; i < n; i++ )
{
cout << " " << setw(6) << my_id_vec[i]
<< " " << setw(12) << my_seed_vec[i]
<< " " << setw(6) << i
<< " " << setw(14) << x[i] << "\n";
}
delete [] my_id_vec;
delete [] my_seed_vec;
delete [] x;
return;
}
/******************************************************************************/
double random_value ( int &seed )
/******************************************************************************/
/*
Purpose:
RANDOM_VALUE generates a random value R.
Discussion:
This is not a good random number generator. It is a SIMPLE one.
It illustrates a model which works by accepting an integer seed value
as input, performing some simple operation on the seed, and then
producing a "random" real value using some simple transformation.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 September 2012
Author:
John Burkardt
Parameters:
Input/output, int &SEED, a seed for the random
number generator.
Output, double RANDOM_VALUE, the random value.
*/
{
double r;
seed = ( seed % 65536 );
seed = ( ( 3125 * seed ) % 65536 );
r = ( double ) ( seed ) / 65536.0;
return r;
}
//****************************************************************************80
void timestamp ( )
//****************************************************************************80
//
// Purpose:
//
// TIMESTAMP prints the current YMDHMS date as a time stamp.
//
// Example:
//
// 31 May 2001 09:45:54 AM
//
// Modified:
//
// 24 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// None
//
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct tm *tm;
time_t now;
now = time ( NULL );
tm = localtime ( &now );
strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm );
cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
There is an article explaining how to use Intel C++ compiler in Eclipse here: 
https://software.intel.com/content/www/us/en/develop/articles/intel-c-compiler-for-linux-using-intel...
, also one more recent documentation on running a sample program in Eclipse here:
https://software.intel.com/content/www/us/en/develop/documentation/get-started-with-intel-oneapi-base-linux/top/run-a-sample-project-using-an-ide.html
and
https://software.intel.com/content/www/us/en/develop/documentation/get-started-with-intel-oneapi-hpc-linux/top/run-a-sample-project-with-eclipse.html
The HPCKit Get Start used the matrix sample. It has an OpenMP version. So you need to launch Eclipse from terminal window where the env is set with "servars.sh".

How to use perform a select on table under schema in postgres Database?

I'm trying to perform a select operation on postgres DB table
and I'm getting below error:
[etb#centos etbtest]$ ./a.out
Opened database successfully: ETBDB
ERROR: relation "etb_reference.etb_member" does not exist
LINE 1: SELECT * FROM etb_reference.ETB_MEMBER
how do we refer the schema name in libpq++ exec function?
I tried escaping the schema name with other escape options like ",',\ etc but it didn't help.
my code :
try {
connection C("dbname = ETBDB user = etbadm password = etbtest \
hostaddr = 127.0.0.1 port = 5432");
if (C.is_open()) {
cout << "Opened database successfully: " << C.dbname() << endl;
} else {
cout << "Can't open database" << endl;
return 1;
}
work wrk(C);
result res = wrk.exec("SELECT * FROM etb_reference.ETB_MEMBER");
for (
pqxx::result::const_iterator row = res.begin();
row != res.end();
++row)
{
std::cout
<< row["MEMBER_ID"].as<int>() << "\t"
<< row["SYS_CRE_DATE"].as<std::string>() << "\t"
<< row["SYS_UPD_DATE"].as<std::string>() << "\t"
<< row["MEMBER_CS"].as<std::string>() << "\t"
<< row["MEMBER_TD"].as<std::string>() << "\t"
<< row["MEMBER_ASD"].as<std::string>() << "\t"
<< row["MEMBER_ITM"].as<std::string>() << "\t"
<< std::endl;
}
C.disconnect ();
return 0;
} catch (const std::exception &e) {
cerr << e.what() << std::endl;
return 1;
}
}
I can execute set search_path to 'schema' but I have divided by database into schemas like application tables, reference tables, configuration tables for easy management of porting and maintaining via automated shell and db scripts.
Opened database successfully: ETBDB ERROR: relation
"etb_reference.etb_member" does not exist LINE 1: SELECT * FROM
etb_reference.ETB_MEMBER
The error message contains the table name in lower cases. It also prints the line where the error occurs, and this line contains the table name in upper case.
SELECT * FROM etb_reference."ETB_MEMBER"
When you query by hand, you use upper case and put the table name between double quotes.
PostgreSQL works with lower case by default, unless the name is between double quotes, so to fix the issue, simply put the table name between double quotes in the query (or, better, only use lower case names)

Merging .root files causing copies of the merged file

I wrote a macro to loop through and merge several .root files of data collected hourly, in an attempt to take several hourly files and turn it into daily files instead. For some reason it is creating several copies of it and all the information within it. For example, when I try to look into the tree containing the data from all the trees, it says "clusters_Tree; 61".
I am attaching my macro, any idea how I could fix this?
#include "TChain.h"
#include "TTree.h"
#include "TParameter.h"
#include "TFile.h"
#include <iostream>
Double_t elow = 0.13;
Double_t ehigh = 100.;
void makeShort(TString year, TString month, TString day){
TChain* c = new TChain("clusters_tree");
TChain* d = new TChain("finfo");
int nFiles = 0;
double efact = 6.04E-3;
TString infolder = "/data/directory1/";
TString contains = year + month + day;
TString outfolder = "/data/directory1/";
TFile* fout = new
TFile(outfolder+"/short_test"+contains+".root","RECREATE");
TSystemDirectory dir(infolder, infolder);
TList *files = dir.GetListOfFiles();
if (files){
TSystemFile *file;
TString fname;
TIter next(files);
while ((file=(TSystemFile*)next())) {
fname = file->GetName();
if (file->IsDirectory() && fname.Contains(contains)) {
nFiles += c->Add(infolder+fname+"/*.root");
d->Add(infolder+fname+"/*.root");
}
}
cout << "Found " << nFiles << " files" << endl;
}
TTree* details = new TTree("details","details");
details->Branch("nFiles",&nFiles);
details->Branch("conversion",&efact);
TTree* t = c->CloneTree(0);
TParameter<double>* q = NULL;
c->SetBranchAddress("charge_total",&q);
Int_t nentries = c->GetEntries();
for(Int_t i=0; i<nentries; i++){
if(i%100000==0)
std::cout << "Processing cluster " << i << " of " << nentries << std::endl;
c->GetEntry(i);
Double_t e = q->GetVal()*efact;
if(e>elow && e<ehigh)
t->Fill();
}
TTree* f = d->CloneTree();
t->Write();
f->Write();
details->Write();
fout->Close();
}
You should really be using hadd. A default ROOT build should already have the binary.
That said, I see you are essentially filling a new tree. The way to do is to create a TChain, and merge to write back (as done by hadd). The clusters_Tree; 61 that you see, are not exactly copies. These are known as cycles, and are more like versions. I'm guessing you have 61 files (maybe 60)? They are probably because you use TTree::CloneTree(0) instead of TChain::Merge(..).

How To Create and Verify Blind RSA Signatures With Crypto++?

I've read through the whitepapers and specifications relating to blind signatures which I've been able to come across, inclusive of the Wikipedia entries, but these tend to focus on the mathematical theory behind it.
Is there a concise practical implementation of RSA blind signatures within c++ using the Crypto++ library?
Is there a concise practical implementation of RSA blind signatures within c++ using the Crypto++ library?
Yes. The Crypto++ wiki has a section on blind signatures for RSA at Raw RSA | RSA Blind Signature. Below is the code taken from the wiki.
Crypto++ lacks blind signature classes. The method below follows the basic algorithm as detailed at Blind Signatures. However, it differs from Wikipedia by applying the s(s'(x)) = x cross-check. The cross-check was present in Chaum's original paper, but it is missing from the wiki article. A second difference from Chaum's paper and wikipedia is, the code below uses H(m) rather than m. That's due to Rabin in 1979.
As far as we know there is no standard covering the signature scheme. The lack of standardization will surely cause interop problems. For example, the code below uses SHA256 to hash the message to be signed, while RSA Blind Signature Scheme for golang uses full domain hashing. Also see Is there a standard padding/format for RSA Blind Signatures? on Crypto.SE.
You may want to apply a padding function first per Usability of padding scheme in blinded RSA signature? or RSA blind signatures in practice.
#include "cryptlib.h"
#include "integer.h"
#include "nbtheory.h"
#include "osrng.h"
#include "rsa.h"
#include "sha.h"
using namespace CryptoPP;
#include <iostream>
#include <stdexcept>
using std::cout;
using std::endl;
using std::runtime_error;
int main(int argc, char* argv[])
{
// Bob artificially small key pair
AutoSeededRandomPool prng;
RSA::PrivateKey privKey;
privKey.GenerateRandomWithKeySize(prng, 64);
RSA::PublicKey pubKey(privKey);
// Convenience
const Integer& n = pubKey.GetModulus();
const Integer& e = pubKey.GetPublicExponent();
const Integer& d = privKey.GetPrivateExponent();
// Print params
cout << "Pub mod: " << std::hex << pubKey.GetModulus() << endl;
cout << "Pub exp: " << std::hex << e << endl;
cout << "Priv mod: " << std::hex << privKey.GetModulus() << endl;
cout << "Priv exp: " << std::hex << d << endl;
// For sizing the hashed message buffer. This should be SHA256 size.
const size_t SIG_SIZE = UnsignedMin(SHA256::BLOCKSIZE, n.ByteCount());
// Scratch
SecByteBlock buff1, buff2, buff3;
// Alice original message to be signed by Bob
SecByteBlock orig((const byte*)"secret", 6);
Integer m(orig.data(), orig.size());
cout << "Message: " << std::hex << m << endl;
// Hash message per Rabin (1979)
buff1.resize(SIG_SIZE);
SHA256 hash1;
hash1.CalculateTruncatedDigest(buff1, buff1.size(), orig, orig.size());
// H(m) as Integer
Integer hm(buff1.data(), buff1.size());
cout << "H(m): " << std::hex << hm << endl;
// Alice blinding
Integer r;
do {
r.Randomize(prng, Integer::One(), n - Integer::One());
} while (!RelativelyPrime(r, n));
// Blinding factor
Integer b = a_exp_b_mod_c(r, e, n);
cout << "Random: " << std::hex << b << endl;
// Alice blinded message
Integer mm = a_times_b_mod_c(hm, b, n);
cout << "Blind msg: " << std::hex << mm << endl;
// Bob sign
Integer ss = privKey.CalculateInverse(prng, mm);
cout << "Blind sign: " << ss << endl;
// Alice checks s(s'(x)) = x. This is from Chaum's paper
Integer c = pubKey.ApplyFunction(ss);
cout << "Check sign: " << c << endl;
if (c != mm)
throw runtime_error("Alice cross-check failed");
// Alice remove blinding
Integer s = a_times_b_mod_c(ss, r.InverseMod(n), n);
cout << "Unblind sign: " << s << endl;
// Eve verifies
Integer v = pubKey.ApplyFunction(s);
cout << "Verify: " << std::hex << v << endl;
// Convert to a string
size_t req = v.MinEncodedSize();
buff2.resize(req);
v.Encode(&buff2[0], buff2.size());
// Hash message per Rabin (1979)
buff3.resize(SIG_SIZE);
SHA256 hash2;
hash2.CalculateTruncatedDigest(buff3, buff3.size(), orig, orig.size());
// Constant time compare
bool equal = buff2.size() == buff3.size() && VerifyBufsEqual(
buff2.data(), buff3.data(), buff3.size());
if (!equal)
throw runtime_error("Eve verified failed");
cout << "Verified signature" << endl;
return 0;
}
Here is the result of building and running the program:
$ g++ blind.cxx ./libcryptopp.a -o blind.exe
$ ./blind.exe
Pub mod: b55dc5e79993680fh
Pub exp: 11h
Priv mod: b55dc5e79993680fh
Priv exp: 1b4fc70ff2e97f1h
Message: 736563726574h
H(m): 2bb80d537b1da3e3h
Random: 72dd6819f0fc5e5fh
Blinded msg: 27a2e2e5e6f4fbfh
Blind sign: 84e7039495bf0570h
Check sign: 27a2e2e5e6f4fbfh
Unblind sign: 61054203e843f380h
Verify: 2bb80d537b1da3e3h
Verified signature

Why does gtkmm row get_value not work?

With this code:
size = 100;
uint64_t work;
row.get_value(3, work);
cout << "value was " << work << endl;
work += size;
cout << "value set to " << work << endl;
row.set_value(3, work);
row.get_value(3, work);
cout << "value now " << work << endl;
I expect this output:
value was 0
value set to 100
value now 100
but I get:
value was 0
value set to 100
value now 0
The updated value, 100, does display correctly in the tree view widget, I just cannot read it with get_value. What am I doing wrong?
Turns out the problem was the uint64_t; row[3] was defined (in Glade) as a guint, the work variable must match that type exactly or get_value will not work.