It is recommended to create an UTF-8 database named ‘sonar’ accessed by specific user ‘sonar’. Here is an example with MySQL:
mysql> CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci;
mysql> grant all privileges on sonar.\* to ‘sonar’@'localhost’ identified by ‘\[your password\]‘;
mysql> flush privileges;
Sonar Installations
Download and Unzip the distribution
Execute on windows
bin\windows-x86-32\StartSonar.bat
If you do not use the default embedded database, edit conf/sonar.properties to configure the database access. Templates are available for every supported database. Just uncomment them and comment the first four lines dedicated to derby.
* sonar.jdbc.url : the URL of the database
* sonar.jdbc.driver : the class of the driver
* sonar.jdbc.user : the username (default is ‘sonar’)
* sonar.jdbc.password : the password (default is ‘sonar’)
Click on Manage Hudson – Manage Plugins. Click now on the Available tab, you should see the Hudson Sonar Plugin. Check this plugin and click on the Install button at the far right hand corner.
Restart Hudson and you should be able to see the plugin in the Installed tab as shown below:
Next,configure the Sonar plugin from within Manage Hudson -> Configure System. I am using the default database, and so didn’t make any changes here. However, if you are using a different database server, you need to provide the database URL, username, password and so on as shown below.
Application that maintains (a large number of) strings in resources can be translated into new languages with minimum effort. Storing localized version of Label, Button, and other control Captions into a string table resource offers several advantages over placing all the strings directly into the exe file:
Character strings contained in a string table resource do not consume memory until specifically loaded by an application.
If using string table resources to create multilingual applications, adding a new language is trivial since Stringtables are easily edited. What’s more if the string table is stored in a resource-only DLL, you do not even have to recompile your application.
As with any other type of resources, string tables are compiled into a “.res” file that is attached to your application’s exe file at build time.
Creating a string table resource
Creating a string table resource to support a two (multi) language application:
Create a .RC text file containing your string resources in the applications build directory. Name the file “StringTableLocalization.rc” – you can name it whatever you like, but it must have the “.rc” extension.
Compile the RC file into a RES file with the BRCC32 resource compiler.
Note: the “StringTableLocalization.rc” CAN contain any additional number of resources of a different type (icons, images, data, etc.)
The string table starts with the key word stringtable. Enclosed in the curly braces are the strings. Each string is listed by its index identifier, followed by the actual string data in quotes. If you need to use a non-standard character, insert the character as a backslash character followed by the octal number of the character you wish to insert. The only exception is when you want to embed a backslash character, you will need to use two backslashes. For example:
1, “A two\012line string”
2, “c:\\Borland\\Delphi”
Using string tables
For the moment take a look at our string table. It is “broken” (only visually) into two regions: “English” and “Hrvatski” (“Croatian”). The Index numbers that you use are not important to the resource compiler. In order to load a particular string from the stringtable you’ll use the LoadString function. One of the parameters in a call to LoadString is the index of a string in a string table.
Linking to an applicaiton
As with any .RES file, you can link the resource file with your application simply by adding the next statement to your application’s code (inside the implementation section of a unit):
{$R StringTableLocalization.RES}
Once the .res file is linked to your program, you can load the resource from any module, even if you specified the $R directive in a different unit.
LoadString
Function to load a string from a stringtable:
function GetString(const Index: integer) : string;
var
buffer : array[0..255] of char;
ls : integer;
begin
Result := '';
ls := LoadString(hInstance,
Index,
buffer,
sizeof(buffer));
if ls <> 0 then Result := buffer;
end;
Once the application is started, the code gets all the languages defined in our string table. By “design” all the language specific strings start at 1 + (1000 * N) position (where N >= 1). The actual name of the language is located at the index for which the following is true: (1000 * N) DIV 1000 = 0.
Note: this “design” is specific to this sample application.
The application gets all the languages and presents them as items of a TRadioGroup component. Once a particular item is selected the strings defined for the selected language are loaded and used by the application.
Note: the sample application includes one “special” custom class TResourceLocalizer that actually loads the strings from the resource.
Adding additional languages to this application is a piece of cake – just edit the “StringTableLocalization.rc” by adding any new languages you want. Make sure the new language name starts with an index identifier of 3000 and all other language specific strings follow after it.
For example, to add the German language localized strings edit the RC file as follows:
Now, recompile it using the BRCC32 resource compiler, start the application and select the German language in the radio group:
That’s it, easy and simple. If you place all the stringtable resources into a separate DLL, you do not even have to recompile your application – only the DLL.
Note:
When you compile the rc-file to res-file (using standard Borland bcc), the current codepage in Windows must be a same as strings in rc-file. For example, you can’t compile the rc-file with Hebrew strings on English computer. Only when default codepage will be a Hebrew, bcc will compile the correct res-file. Unfortunatelly to add the LANGUAGE tag to rc-file will not solve a problem.
Some controls require additionally to change the Font.Charset property when language toggled.
Here i would like to explore, how we can intercept keyboard Input. Consider for a moment creation of some fast arcade game. All the graphics is displayed, let’s say, in a TPainBox. TPaintBox is unable to receive the input focus – no events are fired when the user presses a key; we cannot intercept cursor keys to move our battle ship. But it’s Possible with Delphi.
Intercept Keyboard Input
Most Delphi applications typically handle user input through specific event handlers, those that enable us to capture user keystrokes and process mouse movement.
We know that focus is the ability to receive user input through the mouse or keyboard. Only the object that has the focus can receive a keyboard event. Some controls, such as TImage, TPaintBox, TPanel and TLabel cannot receive focus. The primary purpose of most graphic controls is to display text or graphics.
If we want to intercept keyboard input for controls that cannot receive the input focus we’ll have to deal with Windows API, hooks, callbacks and messages.
Windows Hooks
Technically, a “hook” function is a callback function that can be inserted in the Windows message system so an application can access the message stream before other processing of the message takes place. Among many types of windows hooks, a keyboard hook is called whenever the application calls the GetMessage() or PeekMessage() function and there is a WM_KEYUP or WM_KEYDOWN keyboard message to process.
To create a keyboard hook that intercepts all keyboard input directed to a given thread, we need to call SetWindowsHookEx API function. The routines that receive the keyboard events are application-defined callback functions called hook functions (KeyboardHookProc). Windows calls your hook function for each keystroke message (key up and key down) before the message is placed in the application’s message queue. The hook function can process, change or discard keystrokes. Hooks can be local or global.
The return value of SetWindowsHookEx is a handle to the hook just installed. Before terminating, an application must call the UnhookWindowsHookEx function to free system resources associated with the hook.
Keyboard Hook Example
As a demonstration of keyboard hooks, we’ll create a project with graphical control that can receive key presses. TImage is derived from TGraphicControl, it can be used as a drawing surface for our hypothetical battle game. Since TImage is unable to receive keyboard presses through standard keyboard events we’ll create a hook function that intercepts all keyboard input directed to our drawing surface.
TImage Processing Keyboard Events
Start new Delphi Project and place one Image component on a form. Set Image1.Align property to alClient. That’s it for the visual part, now we have to do some coding. First we’ll need some global variables:
var
Form1: TForm1;
KBHook: HHook; {this intercepts keyboard input}
cx, cy : integer; {track battle ship's position}
{callback's declaration}
function KeyboardHookProc(Code: Integer; WordParam: Word; LongParam: LongInt): LongInt; stdcall;
implementation
...
To install a hook, we call SetWindowsHookEx in the OnCreate event of a form.
procedure TForm1.FormCreate(Sender: TObject) ;
begin
{Set the keyboard hook so we
can intercept keyboard input}
KBHook:=SetWindowsHookEx(WH_KEYBOARD,
{callback €€>} @KeyboardHookProc,
HInstance,
GetCurrentThreadId()) ;
{place the battle ship in
the middle of the screen}
cx := Image1.ClientWidth div 2;
cy := Image1.ClientHeight div 2;
Image1.Canvas.PenPos := Point(cx,cy) ;
end;
To free system resources associated with the hook, we must call the UnhookWindowsHookEx function in the OnDestroy event:
procedure TForm1.FormDestroy(Sender: TObject) ;
begin
{unhook the keyboard interception}
UnHookWindowsHookEx(KBHook) ;
end;
The most important part of this project is the KeyboardHookProc callback procedure used to process keystrokes.
function KeyboardHookProc(Code: Integer; WordParam: Word; LongParam: LongInt) : LongInt;
begin
case WordParam of
vk_Space: {erase battle ship's path}
begin
with Form1.Image1.Canvas do
begin
Brush.Color := clWhite;
Brush.Style := bsSolid;
Fillrect(Form1.Image1.ClientRect) ;
end;
end;
vk_Right: cx := cx+1;
vk_Left: cx := cx-1;
vk_Up: cy := cy-1;
vk_Down: cy := cy+1;
end; {case}
If cx < 2 then cx := Form1.Image1.ClientWidth-2;
If cx > Form1.Image1.ClientWidth -2 then cx := 2;
If cy < 2 then cy := Form1.Image1.ClientHeight -2 ;
If cy > Form1.Image1.ClientHeight-2 then cy := 2;
with Form1.Image1.Canvas do
begin
Pen.Color := clRed;
Brush.Color := clYellow;
TextOut(0,0,Format('%d, %d',[cx,cy])) ;
Rectangle(cx-2, cy-2, cx+2,cy+2) ;
end;
Result:=0;
{To prevent Windows from passing the keystrokes
to the target window, the Result value must
be a nonzero value.}
end;
That’s it. We now have the ultimate keyboard processing code.
Note just one thing: this code is in no way restricted to be used only with TImage.
The KeyboardHookProc function serves as a general KeyPreview & KeyProcess mechanism.
When we do programming in Delphi we don’t need to dynamically create a component. If we drop a component on a form, Delphi handles the component creation automatically when the form is created. But we can also create components at run-time. Here I would like to explain how we can programmatically create components at run-time.
Dynamic Component Creation
There are two ways to dynamically create components. One way is to make a form (or some other TComponent) the owner of the new component. This is a common practice when building composite components where a visual container creates and owns the subcomponents. Doing so will ensure that the newly-created component is destroyed when the owning component is destroyed.
To create an instance (object) of a class, you call its “Create” method. The Create constructor is a class method, as opposed to virtually all other methods you’ll encounter in Delphi programming, which are object methods.
For example, the TComponent declares the Create constructor as follows:
constructor Create(AOwner: TComponent) ; virtual;
Dynamic Creation with Owners
Here’s an example of dynamic creation, where Self is a TComponent or TComponent descendant (e.g., an instance of a TForm):
with TTimer.Create(Self) do
begin
Interval := 1000;
Enabled := False;
OnTimer := MyTimerEventHandler;
end;
Dynamic Creation with an Explicit Call to Free
The second way to create a component is to use nil as the owner. Note that if you do this, you must also explicitly free the object you create as soon as you no longer need it (or you’ll produce amemory leak). Here’s an example of using nil as the owner:
with TTable.Create(nil) do
try
DataBaseName := ‘MyAlias’;
TableName := ‘MyTable’;
Open;
Edit;
FieldByName(‘Busy’).AsBoolean := True;
Post;
finally
Free;
end;
Dynamic Creation and Object References
It is possible to enhance the two previous examples by assigning the result of the Create call to a variable local to the method or belonging to the class. This is often desirable when references to the component need to be used later, or when scoping problems potentially caused by “With” blocks need to be avoided. Here’s the TTimer creation code from above, using a field variable as a reference to the instantiated TTimer object:
FTimer := TTimer.Create(Self) ;
with FTimer do
begin
Interval := 1000;
Enabled := False;
OnTimer := MyInternalTimerEventHandler;
end;
In this example “FTimer” is a private field variable of the form or visual container (or whatever “Self” is). When accessing the FTimer variable from methods in this class, it is a very good idea to check to see if the reference is valid before using it. This is done using Delphi’s Assigned function:
if Assigned(FTimer) then FTimer.Enabled := True;
Dynamic Creation and Object References without Owners
A variation on this is to create the component with no owner, but maintain the reference for later destruction. The construction code for the TTimer would look like this:
FTimer := TTimer.Create(nil) ;
with FTimer do
begin
…
end;
And the destruction code (presumably in the form’s destructor) would look something like this:
FTimer.Free;
FTimer := nil;
(*
Or use FreeAndNil (FTimer) procedure, which frees an object reference and replaces the reference with nil.
*)
Setting the object reference to nil is critical when freeing objects. The call to Free first checks to see if the object reference is nil or not, and if it isn’t, it calls the object’s destructor Destroy.
Dynamic Creation and Local Object References without Owners
Here’s the TTable creation code from above, using a local variable as a reference to the instantiated TTable object:
localTable := TTable.Create(nil) ;
try
with localTable do
begin
DataBaseName := ‘MyAlias’;
TableName := ‘MyTable’;
end;
…
// Later, if we want to explicitly specify scope:
localTable.Open;
localTable.Edit;
localTable.FieldByName(‘Busy’).AsBoolean := True;
localTable.Post;
finally
localTable.Free;
localTable := nil;
end;
In the example above, “localTable” is a local variable declared in the same method containing this code. Note that after freeing any object, in general it is a very good idea to set the reference to nil.
Do not mix a call to Free with passing a valid owner to the constructor. All of the previous techniques will work and are valid, but the following should never occur in your code:
with TTable.Create(self) do
try
…
finally
Free;
end;
The code example above introduces unnecessary performance hits, impacts memory slightly, and has the potential to introduce hard to find bugs.
Note: If a dynamically created component has an owner (specified by the AOwner parameter of the Create constructor), then that owner is responsible for destroying the component. Otherwise, you must explicitly call Free when you no longer need the component.
A test program was created in Delphi to time the dynamic creation of 1000 components with varying initial component counts. The test program appears at the bottom of this page. The chart shows a set of results from the test program, comparing the time it takes to create components both with owners and without. Note that this is only a portion of the hit. A similar performance delay can be expected when destroying components. The time to dynamically create components with owners is 1200% to 107960% slower than that to create components without owners, depending on the number of components on the form and the component being created.
Analyzing the Results
Creating 1000 owned components requires less than a second if the form initially owns no components. However, the same operation takes roughly 10 seconds if the form initially owns 9000 components. In other words, creation time is dependant on the number of components on the form. It is equally interesting to note that creating 1000 components that are not owned takes only a few milliseconds, regardless of the number of components owned by the form. The chart serves to illustrate the impact of the iterative Notification method as the number of owned components increase. The absolute time required to create an instance of a single component whether owned or not, is negligible. Further analysis of the results is left to the reader.
The Test Program
You can perform the test on one of four components: TButton, TLabel, TSession, or TStringGrid (you can of course modify the source to test with other components). Times should vary for each. The chart above was from the TSession component, which showed the widest variance between creation times with owners and without.
Generics are sometimes called generic parameters, a name which allows to introduce them somewhat better. Unlike a function parameter (argument), which has a value, a generic parameter is a type. And it parameterize a class, an interface, a record, or, less frequently, a method.
Generics thus allow, somehow, to declare a set of (potential) classes with a single code, or -more formally- a class template, but with one (or several) parameterized types, which you may change at will. Each time a new actual type is instanciated, you kind of write an entire new class, following its template, and, thus, make real one of those potential classes.
Welcome to the first part of Delphi Image processing series… This article will focus on per pixel filters i.e filters that apply the same algorithm to each pixel ‘in place’ with no regard for the values in any other pixels.
Invert Filter
This one is the simplest filter of all since we are just inverting the image colors by subtracting 255 from them.
procedure InvertImage(const Image:TImage);
var
BytesPerScan: Integer;
iWidth, iHeight: Integer;
pScanLine: pByteArray;
begin
//This only works with images of 24 or 32 bits per pixel
For inverting an image just get the number of bytes per scan line and then loop through each pixel and subtract 255 from each of its color components.
Orginal Image Inverted Image
Gray Scale Filter
The next, obvious filter is a grayscale filter. You might think that this would involve simply summing the three color values and dividing by three, but this does not take into effect the degree to which our eyes are sensitive to different colors. The correct balance is used in the following code:
pScanLine^[iWidth + 2]:= Byte(Round(0.299 * R + 0.587 * G + 0.114 * B));
pScanLine^[iWidth + 1]:= Byte(Round(0.299 * R + 0.587 * G + 0.114 * B));
pScanLine^[iWidth + 0]:= Byte(Round(0.299 * R + 0.587 * G + 0.114 * B));
iWidth := iWidth + 3;
end;
end;
Image.Refresh;
end;
As you can see, we are now iterating through the row b.Width times, and stepping through the pointer in increments of 3, extracting the red, green and blue values individually. Recall that we are pulling out bgr values, not rgb. Then we apply our formula to turn them into the grey value, which obvious is the same for red, green and blue. The end result looks like this:
Orginal Image Grayscale Image
A note on the effects of filters
It’s worthwhile observing before we continue that the Invert filter is the only non-destructive filter we will look at. That is to say, the grayscale filter obviously discards information, so that the original bitmap cannot be reconstructed from the data that remains. The same is also true as we move into filters which take parameters. Doing a Brightness filter of 100, and then of -100 will not result in the original image – we will lose contrast. The reason for that is that the values are clamped – the Brightness filter adds a value to each pixel, and if we go over 255 or below 0 the value is adjusted accordingly and so the difference between pixels that have been moved to a boundary is discarded.
Brightness
Having said that, the actual filter is pretty simple, based on what we already know:
The two examples below use the values of 50 and -50 respectively, both on the original image
Contrast
The operation of contrast is certainly the most complex we have attempted. Instead of just moving all the pixels in the same direction, we must either increase or decrease the difference between groups of pixels. We accept values between -100 and 100, but we turn these into a double between the values of 0 and 4.
My policy has been to return false when invalid values are passed in, rather than clamp them, because they may be the result of a typo, and therefore clamping may not represent what is wanted, and also so users can find out what values are valid, and thus have a realistic expectation of what result a given value might give.
Our loop treats each color in the one iteration, although it’s not necessary in this case to do it that way.
We turn the pixel into a value between 0 and 1, and subtract .5. The net result is a negative value for pixels that should be darkened, and positive for values we want to lighten. We multiply this value by our contrast value, then reverse the process. Finally we clamp the result to make sure it is a valid color value. The following images use contrast values of 30 and -30 respectively.
References
This article is based on reference of a CodeProject article. You can find the orginal at http://www.codeproject.com/KB/GDI-plus/csharpgraphicfilters11.aspx
Delphi for PHP 2.0 is a rapid application development (RAD) – based integrated development environment (IDE) for developing pure PHP applications. Delphi for PHP 2.0 includes a powerful visual framework, the Visual Component Library for PHP (VCL for PHP), that provides developers with a drag-and-drop development environment. PHP developers can now enjoy the same productivity gains that Windows developers have come to expect using tools like Delphi and C++Builder. At the same time, Delphi for PHP 2.0 provides PHP developers a powerful and productive editing environment that PHP developers who like to €œhand-tweak€ their PHP code have come to expect. Delphi for PHP 2.0 aims to increase developers’ productivity with both a RAD environment and a robust code editor.
How to BUILD A VISUAL DEVELOPMENT
FORM DESIGNER
Delphi’s IDE provides a powerful Form Designer to do just that. Delphi for PHP 2.0’s Form Designer looks exactly like a web page, enabling What-You-See-Is-What-You-Get (WYSIWYG) layout of forms at design-time. You can drag-and-drop components from the fully configurable Tool Palette and place them on the form as desired. Components can be spaced and aligned easily using the Visual Guidelines €€œ colored lines that provide visual cues to spacing between components and alignment with other components as a component is dragged on a form.
Once components are placed on the form, their properties can be set using the Object Inspector
HTML DESIGNER
The HTML Designer enables graphical development of HTML documents with embedded PHP and templated forms. HTML pages can be designed in a WYSIWYG view or in pure code. PHP can be embedded in the HTML files and incorporated into a project. Code Insight also works in the HTML designer, providing support for PHP while writing both HTML and PHP code. This is a powerful new feature gives you complete control over your HTML while at the same time having the power of RAD development.
TEMPLATED FORMS
Templated Forms enables €œtagging€ similar to ASP.NET or Cold Fusion. For example, you can create a templated form and add tags like the following:
into HTML pages. Those HTML pages can be edited in the Visual Designer or with the text editor. This mode of development enables the decoupling of the PHP code from the HTML code so that developers can pass off their HTML files to external designers who can provide the styling of the HTML pages while working around the PHP tags in the HTML. This is a major advantage for PHP developers who might be hesitant to use a visual design solution.
THE VISUAL COMPONENT LIBRARY (VCL) FOR PHP
The VCL for PHP 2.0 leverages this extensibility by encapsulating the most popular libraries and scripts from the PHP community and marketplace, including:
Zend (http://framework.zend.com)
Oracle native component
MySQL native component
DATABASE AND VCL FOR PHP
Database development can be performed through the use of Data Access components. They are integrated to the ADOdb for PHP library, which is a set of components for database development and supports access to many different databases, including:
InterBase
MySQL
Access
ADO, ODBC and OLEDB provider
FoxPro
FrontBase
DB2
Informix
SQL Server
Firebird
Oracle
PostgreSQL
SAP DB
SQLite
SQL Anywhere
Sybase
POWERFUL PHP SOURCE CODE EDITOR
Delphi for PHP 2.0’s Code Editor provides extensive support for typing and numerous aids for code creation that greatly enhance your productivity. PHP developers require a powerful, productive code editor, and Delphi for PHP 2.0 provides it. Among its many features are:
The editor is hosted in a tabbed window, so it can open and edit any number of files at once.
Syntax highlighting of code makes it clear what each section of code is €€œ comments, strings, identifiers, keywords, and reserved words are all color coded for easy identification.
Code Completion provides hints to available identifier names as you type.
Code Insight produces pop-up windows that give insight into parameters needed for a given routine.
Error Insight provides immediate feedback by underlining code syntax errors.
Help Insight provides pop-up windows right in the editor giving basic documentation and declaration information about any identifier within code.
Parenthesis and Brace Matching provide visual clues as to what opening and closing identifiers match up with each other
Fast and easy code navigation via a Ctrl +Click mechanism. The declaration of identifiers can be easily located by selecting Ctrl + Click on any identifier. This feature is particularly useful given the disparate nature of PHP code.
The Source Code Formatter formats PHP code to a user-specified format on demand.
Code Templates allow you to create common coding constructs and quickly add them to code with a Ctrl +J keystroke.
THE DEBUGGER
Delphi for PHP 2.0 provides a debugger integrated into the IDE that provides deep access and insight into an application as it runs
With Delphi for PHP 2.0, just press F9 and you are running in Debug Mode, place breakpoints on your code and when that code is executed, the IDE allows you to set watches, check the call stack or even profile your application
You can also execute without debugging, which is faster and is the preferred method if you don’t need any debug capabilities.