28
Jul 08

Delphi: Utils :: ChangeDropShadow

:: articles :: by Gilberto Saraiva

Folks,

With this procedure you can change the Drop Shadow effect provided by windows XP/Vista on all windows without need to reset the computer.

 Delphi |  copy code |? 
01
procedure ChangeDropShadow(AActive: boolean);
02
var
03
  Buff: Cardinal;
04
  Param: Pointer;
05
  DevMode: TDeviceMode;
06
begin
07
  with TRegistry.Create do
08
  begin
09
    RootKey := HKEY_CURRENT_USER;
10
    if OpenKey('\Control Panel\Desktop\', false) then
11
    begin
12
      ReadBinaryData('UserPreferencesMask', Buff, 4);
13
      if AActive then
14
        Buff := Buff or (1 shl 18)
15
      else
16
        Buff := Buff xor (Buff and (1 shl 18));
17
      WriteBinaryData('UserPreferencesMask', Buff, 4);
18
      Param := nil;
19
      if AActive then
20
        Param := @AActive;
21
 
22
      SystemParametersInfo(SPI_SETDROPSHADOW, 0,
23
        Param, SPIF_SENDWININICHANGE);
24
    end;
25
    Free;
26
  end;
27
end;

Hugs!



26
Jul 08

Benchmark: Como utilizar?

:: articles :: by Gilberto Saraiva

Camaradas,

Vou falar um pouco sobre o projeto Benchmark que está disponível no fórum da DevPartners.

Para que serve o projeto Benchmark?

O projeto começou de uma brincadeira entre amigos para desenvolver o algoritmo mais rápido de criação de arranjos, então surgiu a necessidade de termos um sistema de quantificação de tempo utilizado, um benchmark, foi ai que eu comecei a escrever o projeto Benchamark.

Um Benchmark serve para medir uma grandeza matemática que servirá para comparação ou avaliação.
Exemplo:
Frames por segundo em um jogo de computador, a grande maioria dos benchmarks são feitos para comparar o desempenho entre duas ou mais placas de vídeo.

O projeto Benchmark servirá no meu aplicativo?

Claro, o projeto Benchmark foi feito para não ser dependente de nada, é só colocar no seu projeto e utilizar quando necessário.

Como faço para fazer um Benchmark de uma processo dentro do meu aplicativo?

Primeiro você deve baixar o código-fonte do projeto Benchmark para sua máquina, acessando o fórum do projeto, http://devpartners.projects.pro.br/forum/?board=4.

Uma pequena ajuda foi escrita para você que não conhece bem o Subversion:
Como baixar um projeto pelo Subversion.

Logo que tiver o código do Benchmark na sua máquina, acesse a pasta do Benchmark e copie o arquivo pasBenchmark.pas ( Benchmark\source\ ) para o diretorio de Lib do seu Delphi ( essa dica é para facilitar a implementação em outros projetos também, se você entende um pouco mais do esquema de diretórios do Delphi você poderá adicionar a Unit como uma biblioteca ), o diretório Lib do Delphi 7 é o:
C:\Arquivos de programas\Borland\Delphi7\Lib

Feito isso, você deve editar seu projeto em apenas 2 partes:

  • Adicionar o Benchmark no Uses da Unit do processo:
    Exemplo:
     Delphi |  copy code |? 
    01
    02
    unit Unit1;
    03
    { ... }
    04
     
    05
    var
    06
      Form1: TForm1;
    07
     
    08
    implementation
    09
     
    10
    uses pasBenchmark;
    11
  • Antes de iniciar o processo que deseja fazer o Benchmark:
     Delphi |  copy code |? 
    01
    procedure TForm1.ConnectToServer;
    02
    begin
    03
      { ... processo que conecta em um servidor de dados ... }
    04
    end;
    05
     
    06
    procedure TForm1.btnRunClick(Sender: TObject);
    07
    begin
    08
      Benchmark.StartBenchmarking('Benchmark de conexão com o servidor');
    09
      try
    10
        ConnectToServer;
    11
      except
    12
      end;
    13
      Benchmark.EndBenchmarking;
    14
    end;
  • Ao executar o aplicativo e executar o processo, você verá que uma janela abrirá, exibindo as informações do Benchmark, com um resultado semelhante ao exemplificado abaixo:
    1º Benchmark de conexão com o servidor
    Benchmark start at : 26/07/2008 11:54:26
    \___ runned under 550.587,964276 ms

    O que nos informa que a conexão com o servidor de dados demorou 550.587 milisegundos, algo en torno de 0,5 segundos.

    Aonde posso obter mais exemplos de como usar?

    Logo que você copiar os arquivos do projeto para sua máquina atravez do Subversion, você poderá acessar as demonstrações que acompanham o projeto na pasta Benchmark\demos

    Espero que o projeto ajude mais gente como já me ajudou algumas vezes.

    Abraço a todos



    24
    Jul 08

    Caster: New version avaliable

    :: news :: by Gilberto Saraiva

    Folks,

    New version avaliable:
    Caster – Word Clouds

    Version improviments:

  • Ctrl+A select all the text on the editor.
  • Anti-aliase factor can be changed as needed.
  • Compression of JPEG can be modified for export.
  • Compression of PNG can be modified for export.
  • PNG alpha channel can be enabled of not.
  • Fixed Bugs:

  • RGB fields change the color on Color Selection Helper.
  • Lower case button will convert the text to Lower case.
  • Upper case button will convert the text to Upper case.
  • All HTML Tags:

    >_ Castered! _<



    23
    Jul 08

    MySQL: Database Dump tricks

    :: articles :: by Gilberto Saraiva

    Folks,

    Let me relate this:

    Sometimes when you are dumping a database to another host your connection can down, and you will lost all your job and start again? No, no, no, you can make some tricks to continue where you stopped.

    So let me enumarate the tricks:

    MySQLDump commands:

  • Use –add-drop-table
    For don’t lose what you already done, you can config dump to don’t drop the table you are transfering.
    Command:
     DOS |  copy code |? 
    1
    --add-drop-table=FALSE
  • Use –no-create-info
    To avoid the creation of the table, you need to set this option as true.
    Command:
     DOS |  copy code |? 
    1
    --no-create-info=TRUE
  • Use –where option
    the –where option will work as a SQL filter for you, so if you have a indexed table you can
    Command:
     DOS |  copy code |? 
    1
    --where="ID > 300"
  • MySQL commands:

  • Use –force
    To avoid a break on the processing if the dump post a SQL that can cause a error, you need to Force to MySQL continue even with a SQL error and it will keep the rest of the process working.
    Command:
     DOS |  copy code |? 
    1
    --force
  • So, now you know what the commands do and can create a full command line like this one:

     DOS |  copy code |? 
    1
    2
    C:\MySQL\Bin>mysqldump -h 10.0.0.1 -u root -p123456 --add-drop-table=FALSE --no-create-info=TRUE --where="ID > 300" MyDatabase MyTable | mysql -h www.mysite.com -u MyWebUser -p123456 --force MyWebDatabase
    3

    Piece of cake, uhm?



    22
    Jul 08

    MySQL: Database Dump to another Host

    :: articles :: by Gilberto Saraiva

    Folks,

    I’m not a big fan of database programming, but sometimes we need to use then and sometimes we need to manipulate HUGE databases.

    Today I’ve take a big problem, a MySQL database with ~4 GB of size to send to webserver on USA, I tryed to use SQLYog, but this one is to slow and don’t provide a way to retry o continue if some error raise. So 2 hours has pass, and I decided to learn a little about MySQL dump system, and for my luck the mysqldump executable make all the job for me, we need only pass the right command line.

    Lets take a look on the possibilities:

  • MySQLDump is a application that provide a easy way to backup your table(s) or full database(s), keep this idea on the mind!
  • When we create a dump we can output the structure as a SQL file, normal or compressed one.
  • And after reading a little about the dump, I founded the glory magic of create a output to another host
  • Let me show the glory magic of dump a database to another host:
    On a shell (DOS or other one):

     DOS |  copy code |? 
    1
    2
    C:\MySQL\Bin>mysqldump -h 10.0.0.1 -u root -p123456 MyDatabase MyTable | mysql -h www.mysite.com -u MyWebUser -p123456 MyWebDatabase
    3

    Where:
  • -h 10.0.0.1: -h param to indicate the host, the default is localhost, so if you are on the machine that have the database to copy, the use isn’t needed.
  • -u root: -u param to indicate the mysql user.
  • -p123456: -p param to indicate the mysql user password. Note: the password is together the -p param without space between.
  • MyDatabase MyTable: MyDatabase indicate the database name, and MyTable indicate the table name.
  • | mysql: This param makes mysqldump use mysql command line as the output place.
  • -h www.mysite.com: Indicate the host to mysql command line.
  • -u MyWebUser: indicate the mysql user to mysql command line.
  • -p123456: indicate the mysql user password to mysql command line.
  • MyWebDatabase: indicate the database to be used by mysql command line.
  • This is the simple way to get things working fast, you can advance with your knowlegdes by searching more on the web and reading the following pages:
    http://dev.mysql.com/doc/refman/5.0/en/upgrading-to-arch.html
    http://www.tutorialspoint.com/mysql/mysql-database-export.htm

    Very good uhm?

    Hugs for all



    21
    Jul 08

    Google CodeJam: Yuppp!

    :: news :: by Gilberto Saraiva

    Folks,

    I’m in! Now is wait for the first round and play with it on the right time…

    Congratz for all others that pass over the qualification.. ^^

    Hugs



    21
    Jul 08

    ParallelJobs no code.google

    :: articles :: by Gilberto Saraiva

    Camaradas,

    Adicionei hoje o ParallelJobs no code.google,
    Farei dele um espelho(mirror) do svn principal que é o:
    http://devpartners.ath.cx:11520/svn/DevPartners/ParallelJobs/

    E ainda criarei pra cada commit da library um snapshot, assim todos poderão ter o ParallelJobs, sem depender de um único servidor.

    Mas e então, o que é o ParallelJobs?
    O ParallelJobs é uma biblioteca que disponibiliza uma estrutura fácil para se criar processos paralelos em seu aplicativo Delphi. A forma mais conhecida de se fazer isso é utilizando extendendo a classe TThread, o que ainda torna o aplicativo dependente do gerênciamento principal de processos que a VCL dispoe. Com o ParallelJobs você podera criar os mesmos processos com apenas 1 linha de código além de poder fazer isso em qualquer lugar que precise, jogos, aplicativos matemáticos e vários outros modelos de aplicativos que não se utilize necessariamente a VCL.

    Você podera acompanhar a evolução e alguns exemplos de utilização do ParallelJobs aqui, nos artigos em inglês.

    Então vamos aos links do projeto:

  • Fórum:
    http://devpartners.projects.pro.br/forum/?board=8
  • SVN principal:
    http://devpartners.ath.cx:11520/svn/DevPartners/ParallelJobs/
  • TRAC:
    http://devpartners.ath.cx:11520/trac/DevPartners/ParallelJobs/
  • SVN mirror:
    http://paralleljobs.googlecode.com/svn/trunk/

  • Google code area:
    http://code.google.com/p/paralleljobs/
  • Baixe um exemplo de utilização do ParallelJobs:
    Download ele aqui:

    Abraços a todos



    19
    Jul 08

    ParallelJobs: Simple use

    :: articles :: by Gilberto Saraiva

    Folks,

    This is the first article about ParallelJobs and I’ll show you how to create a simple parallel process.

    Lets create a simple drawing system that display a follower effect on a bitmap:

     Delphi |  copy code |? 
    01
    function TfrmMain.UpdateFollower: integer;
    02
    const
    03
      FOLLOWERSIZE = 30;
    04
    var
    05
      Points: array [1..FOLLOWERSIZE] of TPoint;
    06
      i: Integer;
    07
    begin
    08
      while not CurrentJobTerminated do
    09
      begin
    10
        for i := 1 to FOLLOWERSIZE - 1 do
    11
          Points[i] := Points[i + 1];
    12
     
    13
        with Points[FOLLOWERSIZE], Mouse do
    14
        begin
    15
          X := CursorPos.X div 3;
    16
          Y := CursorPos.Y div 3;
    17
        end;
    18
     
    19
        Bmp.Canvas.Lock;
    20
        try
    21
          Bmp.Canvas.FillRect(Bmp.Canvas.ClipRect);
    22
          for i := 2 to FOLLOWERSIZE do
    23
          begin
    24
            with Points[i - 1] do
    25
              Bmp.Canvas.MoveTo(X, Y);
    26
            with Points[i] do
    27
              Bmp.Canvas.LineTo(X, Y);
    28
          end;
    29
        finally
    30
          Bmp.Canvas.Unlock;
    31
          Invalidate;
    32
        end;
    33
        Sleep(10);
    34
      end;
    35
     
    36
      Result := 0;
    37
    end;

    This code will hold the last 30 positions(X, Y) of the mouse and when we modify something on Bmp we have to lock the canvas to don’t let it be display by WM_PAINT message on the wrong time.

    Since we use the TBitmap Bmp we have to create it and setup as wish. After that its time to create the parallel job with ParallelJobs library.
    The code below show how I did it:

     Delphi |  copy code |? 
    01
    procedure TfrmMain.FormCreate(Sender: TObject);
    02
    begin
    03
      ControlStyle := [csOpaque];
    04
      Bmp := TBitmap.Create;
    05
      with Bmp do
    06
      begin
    07
        Width := Screen.Width div 3;
    08
        Height := Screen.Height div 3;
    09
     
    10
        Canvas.Brush.Color := clBlack;
    11
        Canvas.Pen.Color := RGB(255, 130, 0);
    12
      end;
    13
      ParallelJob(Self, @TfrmMain.UpdateFollower);
    14
    end;

    ParallelJobs provide two ways to create a parallel process with any function or method you want, this code use one that you need to specify the object ( Self ) that contain the method and the method to work on a parallel process.

    Now we have to create the display of the follower effect:

     Delphi |  copy code |? 
    01
    procedure TfrmMain.WMPaint(var Message: TWMPaint);
    02
    begin
    03
      Inherited;
    04
      Bmp.Canvas.Lock;
    05
      try
    06
        Canvas.Draw(0, 0, Bmp);
    07
      finally
    08
        Bmp.Canvas.Unlock;
    09
      end;
    10
    end;

    Take a look on the Canvas.Lock, that will create a basic switcher between modification and drawing processes.

    Finally, to don’t raise a exception we need to terminate the parallel process before closing the form and on it destruction we have to free the Bmp to avoid memory leak.

     Delphi |  copy code |? 
    1
    procedure TfrmMain.FormDestroy(Sender: TObject);
    2
    begin
    3
      Bmp.Free;
    4
    end;
    5
     
    6
    procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
    7
    begin
    8
      TerminateAllParallelJobs;
    9
    end;

    Full source without ParallelJobs library, Download it here: pj_example1 (1.27 KB) - 73 hits

    Very nice and easy, uhm?

    Hugs for all



    17
    Jul 08

    WP atualizado… :)

    :: news :: by Gilberto Saraiva

    Camaradas,

    Acabo de atualizar para a versão 2.6. Depois de ver a publicidade em cima da nova versão, vamos ver se realmente o produto divulgado é o que aparentou ser…

    Peço a todos que qualquer problema que venha a acontecer me informar por comentário.

    Adicionei também a dois dias atrás um sistema de votos, então agora quem gostou da matéria ou informação contida na página, pode votar e eu saberei que aquele assunto está sendo bem procurado e vou tentar passar mais informações sobre tal.

    Abraços a todos.



    17
    Jul 08

    Google CodeJam: am I Qualified?

    :: news :: by Gilberto Saraiva

    Folks,

    I still a little disapointed with myself, because I don’t get the needed time to play with CodeJam…
    About 4 hours of a intense harding code to post the results before the qualify round ends.

    3 tests of logical and basic formating output knowledges.

    2 of then I have complete, the last one, gones away… the time has expired… but I can be qualified to the 1º round, I need get only 25 points to that, 10 points I already have.

    Now its time to relax and wait the news…

    Hugs for all