Archive for September, 2006

2006-09-07 21:16

Thursday, September 7th, 2006

Life is good…

There’s something nice in that that most of the coups and in general politically significant events in Bulgaria have happened in the autumn (mostly September), so we can rest after the summer… Wednesday I had a nice rest and came back to my senses, today was the day of st. Moneypour Cashbringer, Tuesday I and the girlfriend separated (we’ve grown tired of each other), so the week was somewhat okay :) I’m now lying in the chair with the beer and listening to Irfan…

I’m looking for the Piano tribute to Tool, does someone know where can it be found? Also the normal tribute, if someone has it :)

Today Damyan gave me the Debian t-shirts, soon a photo will follow – they’re great :)

2006-09-07 21:11

Thursday, September 7th, 2006

Животът е хубав…

Има нещо хубаво в това, че повечето преврати и въобще политически значими събития в България са се случвали есента (основно септември), да можем да си починем след лятото… В сряда си починах и поосвестих, днес пък беше деня на св. Паралей Кинтоносец, вторник се разделихме с жената (с която сме си поомръзнали), та седмицата се оказа приблизително поносима :) Лежа си в стола с биричката и си слушам Irfan…

Търся си Piano tribute to Tool, някой да знае откъде може да се открие? Също така и нормалния tribute, ако му се намира на някой:)

Днеска Дамян ми даде Debian-ските тениски, скоро очаквайте някоя снимка – страхотни са :)

2006-09-03 12:01

Sunday, September 3rd, 2006

These are a few small tricks I use to gather stats and see how the data looks like…

(a note – this is mostly postgresql related, but is easily ported to another database)

Let’s say we have a table in the database, which looks like a log file, with two columns – timestamp and event_id, which is integer from 1 to 5. The tasks is to get in X minute intervals what type of event happened how much times and to draw them.

The first step is the following query:

SELECT  
	((EXTRACT(epoch FROM timestamp)::int/90)*90) AS period,
        SUM((event_id=1)::int) AS type_1,
	SUM((event_id=2)::int) AS type_2, 
	SUM((event_id=3 OR event_id=4 OR event_id=5)::int) AS type_rest,
	SUM(1) AS all
FROM
	log
WHERE 
	timestamp => '2006-08-28 00:00:00' AND timestamp < '2006-08-29 00:00:00'
GROUP BY
	period 
ORDER BY
	period ASC;

(thanks to Aqua for the testing ang the notes :) )

A short explanation - period is a timestamp rounded to 90 seconds (using integer division), which we use to do the grouping. For every such period we're counting how many of each event we have with the small trick with the typecast - true is 1, false is 0, which means that if the condition is satisfied, the sum will increase. This way we're counting what' in the table with one pass through it.

Some notes for the query:

1) date_trunc can be used instead of the EXTRACT trick, but it can't round to stuff different than a minute or hour.
2) In the older versions of postgresql (before 8) by default there's not typecast from boolean to integer, but in the documentation there's an example how to create one.
3) Instead of the trick with SUM() a grouping by event_id can be used, but to be able to combine a few event_ids again some boolean trick has to be used. Also getting the whole count and solving the problem for 0 count of some event_id for some period will be harder.
4) Instead of SUM(1) in the end COUNT(1) can be used, but I don't see a big difference.
5) BETWEEN can be used in the WHERE clause, but I like this more :)

To get the data in format, useful for drawing, we need the following line:

psql -A -q -t -F ' ' $DBNAME -c "$QUERY" > data

(what the options do, you can see in the man page :) DBNAME is the database, QUERY is the query from above)

We'll have one file with the following type of lines:

1156748310 23 12 6 41
1156748400 28 21 5 54
1156748490 32 15 2 49
....

Here gnuplot comes into the game, with the following commands to make a nice drawing:

set title "Events through the day, quantised at 90 sec. (fig. 1)"
set ylabel "number of events"
set xlabel "time through the day"
plot "data" using 5 with lines title  "all", "data" using 4 with lines title  "rest", \
	"data" using 3 with lines title  "type_1", "data" using 2 with lines title  "type_1"

And with putting these two lines in the beginning it will write the thing to file:

set terminal png font VeraSe 11 size 800,500
set output "test.png"

Of course, it would be great to write the hour underneath, but I still haven't thought up a way to do it :)

2006-09-03 11:23

Sunday, September 3rd, 2006

Това са няколко дребни трика, които ползвам за вадене на статистики и да видя кое как изглежда…

(предварително да кажа – това се отнася за postgresql, но се пренася за каквато и да е база доста лесно).
Да кажем, че имаме една таблица в базата данни, която ни е като log файл, с две колони – timestamp и event_id, който е integer и е от 1 до 5. Задачката е да извадим в по X минутни интервали от кой тип event колко са се случили и да ги нарисуваме на една графика.

Първата стъпка е следната заявка:

SELECT  
	((EXTRACT(epoch FROM timestamp)::int/90)*90) AS period,
        SUM((event_id=1)::int) AS type_1,
	SUM((event_id=2)::int) AS type_2, 
	SUM((event_id=3 OR event_id=4 OR event_id=5)::int) AS type_rest,
	SUM(1) AS all
FROM
	log
WHERE 
	timestamp => '2006-08-28 00:00:00' AND timestamp < '2006-08-29 00:00:00'
GROUP BY
	period 
ORDER BY
	period ASC;

(благодарности на Aqua за тестването и забележките :) )

Кратко обяснение - period ни представлява timestamp, закръглен до 90 секунди (чрез целочисленото деление), по който групираме. За всеки такъв период броим от кой event_id колко имаме с дребния трик с typecast-а - true е 1, false е 0, което значи, че ако условието е изпълнено, самата сума ще се увеличи, ако не - няма. Така реално погледнато преброяваме какво се среща в таблицата с едно преминаване през нея.

Няколко забележки към заявката:
1) Може да се използва date_trunc вместо трика с EXTRACT, но не може да се закръгля на неща различни от минута или час.
2) В по-старите версии на postgresql (преди 8) няма по подразбиране typecast от boolean към integer, но в документацията има някъде един пример как може да се напише тоя typecast.
3) Вместо номера със SUM() може да се ползва и групиране по event_id, но за да се обединят няколко event_id-а пак трябва да се прибегне до някакъв boolean трик. Също така ще стане по-сложно взимането на общата бройка и решаването на проблема с 0 срещания на някой event_id за даден период.
4) Вместо SUM(1) накрая може да се ползва COUNT(1), но не вярвам да има особена разлика.
5) Може да се ползва BETWEEN в WHERE клаузата, но на мен така повече ми харесва :)

За да си докараме данните във вид, подходящ за рисуване, ни трябва следния ред:

psql -A -q -t -F ' ' $DBNAME -c "$QUERY" > data

(какво правят опциите може да видите в man-а:) DBNAME е базата, QUERY e заявката от по-горе)

Ще се озовем с един файл data, в който ще имаме следния тип редове:

1156748310 23 12 6 41
1156748400 28 21 5 54
1156748490 32 15 2 49
....

Тук влиза в действие gnuplot-а, който със следната команда ще ви направи една доста приятна рисунка:

set title "Events through the day, quantised at 90 sec. (fig. 1)"
set ylabel "number of events"
set xlabel "time through the day"
plot "data" using 5 with lines title  "all", "data" using 4 with lines title  "rest", \
	"data" using 3 with lines title  "type_1", "data" using 2 with lines title  "type_1"

А с добавката на тези два реда в началото ще ви напише графиката във файл:

set terminal png font VeraSe 11 size 800,500
set output "test.png"

Разбира се, би било хубаво да можеше да се напише и часът отдолу както си трябва, но още не съм измислил как :)

2006-09-02 16:29

Saturday, September 2nd, 2006

Another tiring week, in which one of the days got stretched until 12:30 in the evening…

Friday was a day for some drinking and eating at Halbite with Velin and chervarium, after which we went to Velin’s to hear his new audio system…

Here I can try getting out with the words ‘you have to hear it to understand it’. In short, it’s the first time I’m listening to something so clear (like in Carmina Burana in the beginning you can hear that one of the instruments is a big bell), the volume is ok (the wall vibrates a bit) and in the end I’m thinking about such system. There seems to be a difference between the transistor and lamp amps :) (his is right now 1.5W (no, that’s not a spelling mistake)).

I finished reading “The mortification of the mind…”, turned out really good. One of these days I’ll go to BAS to find “The court on the historians” at the bookstore of the publishers (I even believe myself, knowing how bad my schedule is).

I’m thinking about writing a small article here on some small tricks which I use almost constantly (like a sum of boolean expressions, typecast to integer), and some small stuff about gnyplot (which is a really useful tool to understand some data).

2006-09-02 16:10

Saturday, September 2nd, 2006

Поредната уморителна седмица, в която единия от дните се разпъна до 12:30 вечерта…

Петъкът беше отделен за прилично напиване и наяждане в Халбите с Велин и червото, след което отидохме до Велин да му чуем новата озвучителна система…

Е тук вече мога да пробвам да се измъкна с лафа ‘ами трябва да го чуете, за да го разберете’. Накратко, за пръв път слушам толкова ясна каквато и да е музика (например на Carmina Burana в началото може да се разпознае, че едно от нещата е камбана), силата е приятна (леко вибрира стената) и изобщо мисля и аз да си взема нещо такова. Имало то разлика между транзисторните и ламповите усилватели :) (неговия в момента е около 1.5W (не, няма правописна грешка)).

Изчетох “Усмиряването на разума…”, оказа се доста добра книга. Ще ходя тия дни до БАН да си потърся “Съдът над историците” в книжарницата на издателството (даже си вярвам, въпреки че се знам как съм със времето).

Мисля днес/утре да напиша и една малка статийка за тука на тема някои дребни номера, които прилагам почти постоянно (например сбор от boolean изрази, typecast-нати към integer), както и малко неща около gnuplot (който си е бая ценен инструмент за осъзнаване на разни данни).