Older blog entries for acs (starting at number 41)

The Practice of Perl II


Upon requesting made and continuing my posts about perl practicality, show here a very elaborated code, extract from classic book that I have reading again, Pike & Kerninghan Practice of Programming.

Yes, this book have a very interesting example of Markov Chains in perl.

For those that dont knowing about Markov Chains, this is a particular case in stochastic process, where previous states are irrelevant for prediction of following states, since that actual state is knowing. This technique is very used for generate random text, as in the book example, but, the author uses only cases that envolve two-word prefixes, for test effects.

The code used in the example, written in perl language:

$MAXGEN = 10000;
$NONWORD = “\n”;
$wl = $w2 = $NONWORD;
while (<>) {
foreach (split) {
push(@{$statetab{$w1}{$w2}}, $_);
($w1, $w2) = ($w2, $_);
}
}
push(@($statetab{$w1}{$w2}}, $NONWORD);
$w1 = $w2 = $NONWORD;
for ($i = 0; $i < $MAXGEN; $i++) {
$suf = $statetab{$w1}{$w2};
$r = int(rand @$suf);
exit if(($t = $suf->[$r]) eq $NONWORD);
print “$t\n”;
($w1, $w2) = ($w2, $t);
}

And more impressive is what the result is make of simple and rapid form, very rapid, in the final of chapter has a performance table where perl losing only for C implementation, other implementations are written in Java, C++/STL/Deque, C++/STL/List and AWK, being that have 150 lines of code in C versus only 18 in perl.

Well, I dont make apologies to perl, because I love C too, but, as the author says and define in the final of paragraph, scripting languages (perl, in this case) are a good choice for experimental programming and making prototypes, and I conclude, for rapid tasks and tests, perl is again language of my choice.

Syndicated 2008-01-06 20:43:18 from Jumpi's Notepad

Exemplo didatico sobre tratamento de exceção

Um dos exemplos mais didáticos que eu ja vi sobre tratamento de exceções foi dado hoje aqui na empresa onde trabalho, estávamos na cozinha, no coffee time, quando começamos a discutir sobre tratamento de exceções e eis que o meu colega de trabalho, Marcio Andrey a.k.a. tio nos faz a demonstração de como ele explicou tratamento de exceções a outro colega aqui da empresa que estava com duvidas no entendimento do tratamento de exceções e precisava de ajuda para fazer a sua prova.

Segue abaixo o exemplo de código (com permissão do autor, e algumas correções para nao divulgar nomes, of course…):

Pessoa individuo = new Pessoa(”individuo”);

Pessoa gostosa = new Pessoa(”uma gbr gostosa”);

Cerveja cerveja = new Cerveja(”Skol”); //variável antes do try que precisei

individuo.tomaBreja(cerveja);

try {

individuo.pegaNaCintura(gostosa);

individuo.pegaNoPeitinho(gostosa);

individuo.chupaPeitinho(gostosa);

Camisinha johnson = new Camisinha(”Lubrificada”); // precisei de uma variável local aqui.

individuo.poeCamisinha(johnson); // usei a variável local aqui.

individuo.comeASafada(gostosa);

}
catch(TapaNaCaraException e) {
System.out.println(”a gbr tentou te dar um tapa na cara e te deu uma escroteada”);
}
catch(TeEmpurrouException e) {
System.out.println(”a gbr te empurrou e te deu uma escroteada”);
}

catch(TeEmpurrouException e) {
System.out.println(”a gbr te deu uma escroteada”);
}
finally {
individuo.vaiEmbora();
}

Quer exemplo mais didático que esse??? Depois dessa o individuo nunca mais vai se esquecer como fazer uso correto do try/catch…. :D

Meus sinceros agradecimentos ao tio por contribuir com esse post tao instrutivo e ao mesmo tempo engraçado!!! :D

Sorry for Advogato’s people by wrote this in portuguese, I need wrote this and any questions about I wrote, send me a message and I explain :D

Syndicated 2007-12-11 19:35:13 from Jumpi's Notepad

The Excel 2007 Bug

About the bug that affected Excel 2007, I think that is very hard to work with floating point calculations and approximation is very complex and find a problem in logic of this is a true nightmare!!!!

The summary of problem: Excel 2007 store six floating point numbers using binary representation between 65534.99999999995 and 65535, and dont store six between 65535.99999999995 and 65536 and this numbers are the cause of this problem.

I work with arbitrary precision in my scientific intiation and using libraries for care of this part for me, because of difficulties that involve the manipulation of calculate numbers that need arbitrary precision. IMHO, working with type of development demands very attention and very pacience.

The two links have a good explanation of this problem… Its a good lecture!!!

The Excel Bug Explanation by Good Math, Bad Math Blog
The Excel Bug Explanation for Mathematica Developers Blog

See ya people and have a good fun!!!

In play: Emerson, Lake and Palmer - Works (Black) Vol. 1 - 07: The Enemy God

Syndicated 2007-10-03 20:54:32 from Jumpi's Notepad

Really, Code::Blocks Rocks!!!

Really, Code::Blocks Rocks!!!

Well… after a long time I post here again, because of this IDE… yeah… a many time that I try to test it and after tests of my friend Marcio that use and talk about the tool I decided test too. I’m very surprise with this IDE, the installation is very easy and work with this IDE is very easy too… I install it in my VM with WinXP and I testing the OpenGL app and it works very fine… The OpenGL app works fine in my VM too, in considerable time… I decided now use the Code::Blocks for developing my personal project at this time!!! Its convinced me!!! :D

Today, after reading some pages of the Programming Challenges Book I’m trying applying some memoization and dynamic programming techniques for solve some problems in SPOJs and UVA’s online-judge of life. Its a very utility tool for solving many problems. But I need more training for good application of this. I like this… :D

In play: Bruce Dickinson - The Very Best Of (CD 1) - 02: Tattooed Millionarie

Syndicated 2007-09-15 23:13:35 from Jumpi's Notepad

The Practice of Perl

Well.. a sugestive title for an post, but I decide for this title because of Perl is one of my prefer programming languages, my “swiss army knife”… and dont first time that I using perl for solving my problem… ehehehhehehehhee…

But why I talking about perl here??? Because of one problem, for more exactly, the problem 5 of Project Euler (http://projecteuler.net/), a site with mathematical problems that resolve with the use of algorithms. The problem 5 it follows below:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

I trying resolve this using C, but I dont have an simple compiler in my work machine,because in my opinion, Visual C is much complex for this task… (some of my friends dont think it…)

But I think… I have perl interpretor in my machine and write this program in perl dont much harder and I starting the port of C for Perl and write this piece of code for solving my problem:

for ( my $n = 20; 1; $n++ ) {
for ( 1..20 ) {
if ( $n % $_ ) {
last;
}
if ( $_ == 20 ) {
die $n;
}
}
}
Well… is an idiot program, extremaly simple but I have the answer of problem with this… dont consider the execution time, “only” 20 min of the pure brute force for answering the problem… ehehhehehehehehhehe…

And perl with your practical syntax save my world one more time!!!! :D

In Play: Gorguts - The Erosion of Sanity - 04: Orphans of Sickness

Syndicated 2007-08-09 04:22:42 from Jumpi's Notepad

Tutorial Basico de GDB

O post de hoje sera dedicado a esse famoso debugger do mundo UNIX e que pode ser utilizado em ambiente windows tambem, sim… vamos tratar do GNU Debugger ou GDB, software muito util para fazer analises e encontrar erros decorrentes em nossos programas.

Claro que a intenção desse post é ser bem basico, passando apenas informações necessarias para a iniciação, caso alguem queira saber mais, existe uma documentacao excelente, um exemplo disso e o livro Debugging with GDB

Entao chega de conversa e vamos ao que interessa..

Primeiro caso: Compilando para debugar

Iremos utilizar como exemplo, um programa que conta de 0 a 10, como queremos debugar esse programa, para isso utilizamos o seguinte comando

[jumpi@painkiller testes]$ gcc -g contador.c

Com esse comando geramos um arquivo de saida (a.out), que vai conter as informações necessarias para o debugging

Agora e hora de debugar, na linha de comando digitamos:

[jumpi@painkiller testes]$ gdb a.out
GNU gdb Red Hat Linux (6.5-15.fc6rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type “show copying” to see the conditions.
There is absolutely no warranty for GDB. Type “show warranty” for details.
This GDB was configured as “i386-redhat-linux-gnu”…Using host libthread_db library “/lib/libthread_db.so.1″.

(gdb)

Com esse comando, entramos em modo de debugging e o gdb nos apresenta o prompt onde entramos com os comandos necessarios para o debugging.

Hora de definir o breakpoint: no gdb, podemos utilizar numero de linha ou ate mesmo o nome da funcao na qual se deseja inserir o breakpoint, no nosso caso vamos definir um breakpoint na funcao main com o seguinte comando

(gdb) break main
Breakpoint 1 at 0×8048395: file contador.c, line 7.
(gdb)

E agora rodamos o programa dentro do debugger com o seguinte comando

(gdb) run
Starting program: /home/jumpi/testes/a.out

Breakpoint 1, main () at contador.c:7
7 for (i=0; i<=10; i++) {
(gdb)

E ele para exatamente na linha onde foi inserido o breakpoint, no caso como definimos por funcao, entao ele para na primeira linha da funcao, numericamente falando, na linha 7

Agora temos 2 comandos que podemos utilizar para verificar as informacoes, step e next, no caso, step vai fazendo passo a passo, ou seja, linha por linha e o next é utilizado quando desejo passar por subrotinas, no nosso caso vamos utilizar o step e ver o que acontece

(gdb) step
8 printf(”Numero :%d\n”,i);
(gdb) step
Numero :0
7 for (i=0; i<=10; i++) {
(gdb) step
8 printf(”Numero :%d\n”,i);
(gdb) step
Numero :1

Ele vai executando cada passo da funcao solicitada, como estamos dentro de um laco, ele executa o laco ate o seu termino.

Suponha que eu quero verificar o valor da variavel no momento, nesse caso como eu possuo apenas a variavel i, vamos imprimir o seu valor, eu posso utilizar o comando print ou display da seguinte maneira

(gdb) print i
$1 = 4
(gdb) display i
1: i = 4
(gdb)

No caso, com print ele mostra a variavel temporaria que armazena o resultado e com display ele mostra a variavel definida pelo usuario no codigo.

Podemos setar tambem o valor das variaveis com o comando set variable da seguinte maneira

(gdb) set variable i=20
(gdb) display i
2: i = 20
(gdb)

Segundo caso: Utilizando o gdb para analisar coredumps

Coredumps sao arquivos que contem a informacao sobre um determinado erro gerado quando um programa e executado e utilizando o gdb podemos descobrir qual a anomalia do nosso programa

[jumpi@painkiller testes]$ gcc -g contador.c

[jumpi@painkiller testes]$ ./a.out
Numero :(null)
Segmentation fault (core dumped)
[jumpi@painkiller testes]$

Isso significa que o programa gerou um erro e um coredump foi criado, quando verificamos o conteudo do diretorio procurando por core

[jumpi@painkiller testes]$ ls core*
core.6180
[jumpi@painkiller testes]$

Verificamos que o core foi criado, agora vamos utiliza-lo para servir como base de informacao para o nosso debugging no gdb

[jumpi@painkiller testes]$ gdb a.out core.6180
GNU gdb Red Hat Linux (6.5-15.fc6rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type “show copying” to see the conditions.
There is absolutely no warranty for GDB. Type “show warranty” for details.
This GDB was configured as “i386-redhat-linux-gnu”…Using host libthread_db library “/lib/libthread_db.so.1″.

warning: Can’t read pathname for load map: Input/output error.
Reading symbols from /lib/libc.so.6…done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2…done.
Loaded symbols for /lib/ld-linux.so.2
Core was generated by `./a.out’.
Program terminated with signal 11, Segmentation fault.
#0 0×0077bf9b in strlen () from /lib/libc.so.6
(gdb)

Carregado o gdb com o arquivo de core, podemos utilizar o comando backtrace ou bt, para verificarmos as chamadas de funções e separarmos por frames

(gdb) bt
#0 0×0077bf9b in strlen () from /lib/libc.so.6
#1 0×0074e1ff in vfprintf () from /lib/libc.so.6
#2 0×007539c3 in printf () from /lib/libc.so.6
#3 0×080483b1 in main () at contador.c:7
(gdb)

Bem, no nosso caso eu verifico que tem um problema no frame 3, na linha 7, entao o comando frame seguido do numero do frame para verificar o que ocorre

(gdb) frame 3
#3 0×080483b1 in main () at contador.c:7
7 printf(”Numero :%s\n”,i);
(gdb)

E assim verifico que por descuido, coloquei um %s, onde era um %i… :)

Bem, utilizei apenas uma pequena fração para demonstrar do que o GDB é capaz, ele pode ser muito util para uma serie de outras coisas, sem contar que existem muitos outros detalhes mais especificos que nao foram abordados aqui nesse post, porem espero que seja util a vocês tambem… Ate a proxima!!! :)

No play: Cacophony - Speed Metal Symphony - 06: Desert Island

Syndicated 2007-07-24 04:19:59 from Jumpi's Notepad

Yes, nos tambem temos int 3!!!! (tecnicas antidebugging no linux)

Well, seguindo o embalo do meu amigo de trabalho, a.k.a. Vandeco, tambem tentarei mostrar aqui uma tecnica antidebugging, so que em um S.O. diferente… no nosso caso vamos fazer o teste no linux e vamos verificar que int 3 e usual, sim… nao tenho duvidas, porem nao basta para livrar o nosso codigo do debugging alheio…

Tentarei demonstrar de forma resumida um exemplo de como burlar o debug do gdb

Primeiro exemplo de codigo, introduzir um breakpoint falso

#include <signal.h>

void handler (int signo) {
}

int main() {

signal(handler, SIGTRAP);
__asm__(”int3″);
printf(”Ola!!”);
}

[jumpi@painkiller testes]$ gcc -g debug-teste.c
[jumpi@painkiller testes]$

[jumpi@painkiller testes]$ gdb
GNU gdb Red Hat Linux (6.5-15.fc6rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type “show copying” to see the conditions.
There is absolutely no warranty for GDB. Type “show warranty” for details.
This GDB was configured as “i386-redhat-linux-gnu”.
(gdb) file a.out
Reading symbols from /home/jumpi/testes/a.out…done.
Using host libthread_db library “/lib/libthread_db.so.1″.
(gdb) run
Starting program: /home/jumpi/testes/a.out

Program received signal SIGTRAP, Trace/breakpoint trap.
main () at debug-teste.c:11
11 printf(”Ola!!”);
(gdb) c
Continuing.
Ola!!
Program exited with code 05.
(gdb) quit

Ou seja, com isso forçamos um int 3 no codigo como se fosse um breakpoint e com o SIGTRAP capturamos o sinal, que faz com que ele pense que havia um breakpoint onde na verdade nao havia, simples e interessante… :)

Enfim, existem diversas outras tecnicas de debugging e antidebugging, como fazer controle da ptrace(), usando file descriptor ou ate mesmo por identificacao de processos. Porem fica para uma proxima ocasiao… :)

No play: Arsis - United in Regret - 04: I Speak Through Shadows

Syndicated 2007-07-21 14:43:59 from Jumpi's Notepad

“f(problemas(ciência da computação(matemática)))”

Enfim… vai entender o que se passa na cabeça de um cara que me escreve um livro que para ser Cientista da Computação, você nao precisa saber de matematica??? Juro que eu queria entende-lo… porem, em minha humilde opiniao, isso se torna incompreensivel… Classificaria isto como uma blasfemia… Penso eu que a Ciencia da Computação esta amarrada a matematica assim como a fisica, ou talvez ate mais, devido ao fato de Ciencia da Computação na minha opiniao, ser uma ramificação da matematica, pois ela engloba grande parte dos conceitos matematicos, como a logica matematica (utilizada na logica booleana), teoria dos numeros (utilizada no campo da criptografia e na inteligencia artificial), teoria dos grafos (utilizada em estruturas de dados e nos algoritimos de busca), enfim, tudo na ciencia da computação engloba matematica, ou seja, por tras dos trabalhos computacionais existem modelos e metodos matematicos. Bem, sempre tive em mente que na verdade ser um cientista da computação é ser um matematico tambem, pois o mesmo utiliza-se de matematica para dar enfase aos seus trabalhos, o que na minha visao sempre entendi como matematica aplicada. E devido a essa visão, foi que escolhi ser Bacharel em Matematica, pois sempre pensei que a matematica me ajudaria a abrir os olhos para a area da Ciencia Computacional, e não me arrependo, pois tem sido bem util para o meu entendimento do funcionamento das coisas, afinal de contas eu consigo entender como funciona um SGBD gracas a teoria dos conjuntos ou um processo de raytracing gracas aos vetores. e não acaba por aqui… eu poderia dar n-exemplos aqui sobre a aplicacao da matematica na ciencia da computação… mas enfim… para quem estiver curioso em ler sobre a materia na qual gerou esse post e que me trouxe tanta revolta… segue o link…

http://www.itwire.com.au/content/view/13339/53/

Abraços e ate a proxima!!!!

No play: Symphony X - Paradise Lost - 09: The Sacrifice

Syndicated 2007-07-20 03:02:02 from Jumpi's Notepad

mudanças mode on

Well… well… muito tempo ja se passou desde a ultima vez que escrevi aqui nesse local.. enfim… vamos aproveitar e dar uma revisada nas mudanças que ocorreram na minha vida… enquanto compilo o kernel do NetBSD em uma imagem aqui que criei para meus testes e enquanto ouco no player Queensryche… :)

Enfim… muita coisa mudou na minha vida, arrumei novo emprego (isso ja fazem 3 meses… ate mudei o about), sim… sim… agora eu sou Engenheiro de Software de uma empresa (http://www.opencs.com.br) que desenvolve softwares de seguranca… bem interessante o trampo la, a convivencia, os amigos… estou aprendendo varias coisas novas sobre o mundo microsoft… mundo antes desconhecido por minha pessoa… afinal de contas tive muito pouco contato com esse mundo… esta sendo divertido esse mundo de windbg, visual studio, C++ o dia inteiro, isso sem contar nas risadas, piadas e situacoes engracadas do dia-a-dia, sem contar que a equipe e muito competente e todos sao muito receptivos… o que torna o ambiente super agradavel para se desenvolver as tarefas… tanto que eles me motivaram a continuar… e hoje para inaugurar a nova fase desse blog… ja que ninguem le aqui… ele vai se tornar um pouquinho mais tecnico, tentarei dar mais enfase a assuntos tecnicos que ocorrem no meu dia-a-dia, curiosidades, enfim… um blog beeeeeeeeeem mais informativo e agradavel principalmente para nerds… :)

Sim… outra mudanca foi no layout… achei esse layout bem mais bonitinho… enfim… e ele que eu vou usar daqui pra frente…

Well… hora de esperar o ./build.sh -O ../obj -T ../tools -u -U distribution terminar para dar continuidade ao meu trabalho… como diria um amigo meu do trampo… “Poder fazer um update fresquinho no sistema” e coisa linda de deus!!! :)

Ate a proxima… :)

No play: Queensryche - Greatest Hits - 04: Take Hold of the Flame

Syndicated 2007-07-19 04:34:50 from Jumpi's Notepad

You’re Perl

After long time that dont post here… I’m posting here again the result of language test that I see and answering… :D

Ohhhhhhh… This test is very funny!!!! Perl is my favorite language for write scripts… I like this…

You’re Perl

“You are Perl. People have a hard time understanding you, but you are always able to help them with almost all of their problems.”

For all that answering the questions too, the phrase above contains the link!!!

Thanks for all that see this blog… :D

Syndicated 2007-04-30 17:07:27 from Jumpi's Notepad

32 older entries...

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!