2011-11-21

A trivial character search and replace method in C++

A very long time ago I was searching for ways to replace individual characters in a string and some of the methods was summarized in a small test program. I found that test program in an old folder on my computer which I almost forgot. So, I share that little code with the world. It follows.

#include <algorithm>
#include <string>
#include <iostream>

using namespace std;

bool is_punct( const char& c )
{
 return ispunct( c );
}

bool is_l( const char& c )
{
 return 'l'==c;
}

struct mycomp
{
 bool operator()(const char& o)
 {
  return ispunct( o );
 }
};

int main()
{
 // Remove all characters that "ispunct" using a function.
 string s = "hello, world!";
 s.erase( remove_if( s.begin(), s.end(), &is_punct ), s.end() );
 cout << s << '\n';

 // Remove all characters that "ispunct" using a functor.
 s = "hello, world!";
 s.erase( remove_if( s.begin(), s.end(), mycomp() ), s.end() );
 cout << s << '\n';

 // Replace all 'l' with 'L' using a function.
 s = "hello, world!";
 replace_if( s.begin(), s.end(), &is_l, 'L' );
 cout << s << '\n';
}

2011-11-16

Creating a histogram in SQL using event data

Sometimes you may have gathered some data on event-by-event basis. For instance, the data may look like this when pulses from a radioactive decay have been processed by a peak sensing analog to digital converter (ADC):

2
2
2
8
8
8
8
8
8
8
8
8
100
100
250
250

A simple table in a relational database may be created to store this data:

CREATE TABLE samples( channel INTEGER NOT NULL );

BEGIN TRANSACTION;
INSERT INTO samples VALUES(2);
INSERT INTO samples VALUES(2);
INSERT INTO samples VALUES(2);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(8);
INSERT INTO samples VALUES(100);
INSERT INTO samples VALUES(100);
INSERT INTO samples VALUES(250);
INSERT INTO samples VALUES(250);
COMMIT;

I found the following SQL statement somewhere on the net (if you find it, please let me know where so that I can pay the appropriate tribute to its source). It is a demonstration of how to create a 1024 channel histogram with the above data. I hope you find it useful.

SELECT bin, COUNT(1) AS cnt
FROM (SELECT CAST((channel-mn) / (1.0*range/1024) AS INTEGER) + 1 AS bin
      FROM (SELECT MIN(channel) AS mn, MAX(channel)-MIN(channel)+1 AS range
            FROM samples) AS R
         CROSS JOIN
           (SELECT * FROM samples) AS S) AS RS
GROUP BY bin;

Using SQLite as database engine, I get the following output after executing the above SQL statements.

1|3
25|9
404|2
1020|2