Friday, December 26, 2008

C# Parallel Foreach using Thread Pool

public void Foreach(T[] array, Action action)
int cpus = 2 * Environment.ProcessorCount;
int nitems = array.Length;
int chunk = nitems / cpus;
int counter = cpus;

using (AutoResetEvent signal = new AutoResetEvent(false))
for (int i = 1; i <= cpus; i++)
ThreadPool.QueueUserWorkItem(delegate(object o)
int unit = (int)o;

for (int j = (unit - 1) * chunk;
j < (unit == cpus ? nitems : unit * chunk);

if (Interlocked.Decrement(ref counter) == 0)
}, i);


public void ForeachWithResults(T[] array, T1[] results, Action action)
int cpus = 2 * Environment.ProcessorCount;
int nitems = array.Length;
int chunk = nitems / cpus;
int counter = cpus;

using (AutoResetEvent signal = new AutoResetEvent(false))
for (int i = 1; i <= cpus; i++)
ThreadPool.QueueUserWorkItem(delegate(object o)
int unit = (int)o;

for (int j = (unit - 1) * chunk;
j < (unit == cpus ? nitems : unit * chunk);
action(j, array[j], results);

if (Interlocked.Decrement(ref counter) == 0)
}, i);


Saturday, December 20, 2008

C#: Evaluating Infix Expression

This morning I've written a simple Infix Notation Evaluator in C, and this afternoon I've rewritten it in C#. I Think that C# is more easy to understand than C, so I've posted the C# Example. (If you want the C example, ask me).
In few words, I take the Input in "Infix Notation" and I convert it in Reverse Polish Notation (RPN), and then the RPN string is evaluated.

First Example: Evaluating a simple Math Expression.

string expr = "10 + 5 - (2 + (3 * 4) + (5 * 3)) - 4 ^ 2 << 8";
Operation operation = new MyTokener().Parser(expr);
Console.WriteLine("{0} = {1}", expr, operation.Evaluate());

Second Example: Evaluating a simple Math Expression with variables.

Dictionary vars = new Dictionary();
vars.Add("A", "1"); vars.Add("B", "2");
vars.Add("C", "3"); vars.Add("D", "4");
vars.Add("K", "5"); vars.Add("L", "6");

string expr = "(A + B) + C + (D * (K + (L - 1)))";
Operation operation = new MyTokener().Parser(expr);
Console.WriteLine("{0} = {1}", expr, operation.Evaluate());

Third example: Evaluating simple String expression.

string expr = "'Hello' + ' ' * 3 + \"World\"";
Operation operation = new MyTokener().Parser(expr);
Console.WriteLine("{0} = {1}", expr, operation.Evaluate());

After the Example you can find the Source Code Here (You can compile it under Linux with gmcs).

That's all folks! I'm really busy with the Real Work, I'm waiting the 25th for taking a break.

Saturday, December 6, 2008

WebKit: Dynamic Content

Today I've played a bit with WebKit. I Want do something like Cocoa VBox View and NSScrollView but with more flexibility. Below you can see the example result.
The interesting part of this example is How to manage WebKit content, and how to add something dynamically.

I use webView:decidePolicyForNavigationAction:request:frame:decisionListener: of WebPolicyDelegate Protocol to handle my custom requests, in this way...

- (void)webView:(WebView *)sender 
         decidePolicyForNavigationAction:(NSDictionary *)actionInformation
         request:(NSURLRequest *)request frame:(WebFrame *)frame
  if ([[[request URL] path] isEqualToString:@"PATH to Handle"]) {
    [listener ignore];
    // Handle Request
  } else {
    [listener use];

...Then with a little bit of JavaScript I'll set my dynamic content loaded from Database or somewhere else.

NSArray *args = [NSArray arrayWithObjects:@"Item1Content", 
@"Hi, I'm Test 1 Content", nil];
[[webKit windowScriptObject] callWebScriptMethod:@"fillElement" 

The fillElement method is a simple JS function like this document.getElementById(elem).innerHTML = data;

Here you can find the Source Code.

Friday, November 28, 2008

Objective-C: SQLite Wrapper

I've written a simple SQLite Wrapper with two Examples one for Mac and one for the iPhone. The Wrapper class has the same source code for both platforms.

Here you can find the Mac Example Source Code and the iPhone Example Source Code.

This is a simple usage example:

Sqlite *sqlite = [[Sqlite alloc] init];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory
if (![sqlite open:writableDBPath])

[sqlite executeNonQuery:@"CREATE TABLE test (key TEXT NOT NULL, value TEXT);"];
[sqlite executeNonQuery:@"DELETE FROM test;"];
[sqlite executeNonQuery:@"INSERT INTO test VALUES (?, ?);",
[Sqlite createUuid], @"PROVA"];
[sqlite executeNonQuery:@"INSERT INTO test VALUES (?, ?);",
[Sqlite createUuid], @"PROVA 2"];
[sqlite executeNonQuery:@"INSERT INTO test VALUES (?, ?);",
[Sqlite createUuid], @"PROVA 3"];

NSArray *results = [sqlite executeQuery:@"SELECT * FROM test;"];
for (NSDictionary *dictionary in results) {
  for (NSString *key in [dictionary keyEnumerator])
    NSLog(@" - %@ %@", key, [dictionary objectForKey:key]);

[results release];
[sqlite release];

Wednesday, November 26, 2008

OpenSSL: License Key with RSA

In the last days I've played a bit with C libraries like OpenSSL and SQLite. The first post after Site downtime is dedicated to OpenSSL.
how do can you create your own license system for your application? With OpenSSL and less than 10 lines of code, you can do it. Take a look at the code below.

unsigned char checkDigest[SHA_DIGEST_LENGTH];
unsigned char shaDigest[SHA_DIGEST_LENGTH];
const char *userKey = "Matteo License";
unsigned char *signature = NULL;
unsigned int signatureLength = 0;

/* Generate Your RSA Key Pair */
RSA *rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);

/* Generate SHA1 of User Key */
SHA1(userKey, strlen(userKey), shaDigest);

/* Create License Key for the User Key */
signature = OPENSSL_malloc(RSA_size(rsa));
signatureLength = RSA_private_encrypt(SHA_DIGEST_LENGTH, shaDigest,
signature, rsa, RSA_PKCS1_PADDING);

/* Check if User Signature is a valid License Key */
if (RSA_public_decrypt(signatureLength, signature, checkDigest,
/* Valid License Key */
} else {
/* Invalid License Key */


You need to store the RSA Public Key in your app and then give to each user a generated signature, and it's all.
Ok, this is a really base example (less than 10 lines of code) if you don't want reinvent a License Key system, take a look at AquaticPrime Framework (

Sunday, November 16, 2008

Cocoa: VBox View and NSScrollView

Following the post of yesterday, today I've implemented a simple VBoxView (Vertical Box Layout) that allow you to lines up NSViews vertically.
Here you can find the example Source Code.

Saturday, November 15, 2008

Cocoa: Drawing Images, Texts and Shadows

Today I'm playing a bit with Quartz and Cocoa Drawing system (that is based on Quartz).

I've made a simple example that you can see below where I've used custom NSView that draws an Image and a Bezier Path with some text inside, and around the Bezier Path there's a Shadow.
...And this is the drawRect method source code of the custom NSView.

- (void)drawRect:(NSRect)frameRect {
  [NSGraphicsContext saveGraphicsState];

  [[NSColor colorWithCalibratedRed:0.64 green:0.66 blue:0.71 alpha:1.0] set];

  /* Draw Shadow */
  NSShadow *shadow = [[NSShadow alloc] init];
  [shadow setShadowColor:[[NSColor blackColor] colorWithAlphaComponent:0.5]];
  [shadow setShadowOffset:NSMakeSize(4.0, -4.0)];
  [shadow setShadowBlurRadius:3.0];
  [shadow set];

  /* Draw Control */
  NSRect myRect = NSMakeRect(80, 50, frameRect.size.width - 120, 60);
  NSBezierPath *path = [NSBezierPath bezierPath];
  [path setLineJoinStyle:NSRoundLineJoinStyle];
  [path appendBezierPathWithRoundedRect:myRect xRadius:8.0 yRadius:8.0];    

  [path moveToPoint:NSMakePoint(80, 75)];
  [path lineToPoint:NSMakePoint(65, 85)];
  [path lineToPoint:NSMakePoint(80, 95)];

  NSColor *startingColor = [NSColor colorWithCalibratedRed:0.90
  green:0.92 blue:0.85 alpha:1.0];
  NSColor *endingColor = [NSColor colorWithCalibratedRed:0.81
                               green:0.83 blue:0.76 alpha:1.0];
  NSGradient *gradient = [[[NSGradient alloc] initWithStartingColor:startingColor
                              endingColor:endingColor] autorelease];
  [path fill];
  [gradient drawInBezierPath:path angle:90];

  [NSGraphicsContext restoreGraphicsState];

  [shadow release];

  NSImage *image = [NSImage imageNamed:NSImageNameUser];
  [image drawInRect:NSMakeRect(15, 50, 50, 50) fromRect:NSZeroRect
                operation:NSCompositeSourceOver fraction:1.0];

  NSString *string = [NSString stringWithString:@"Text\nMore Text"];
  [string drawInRect:NSMakeRect(90, 60, frameRect.size.width - 140, 45)

Sunday, November 9, 2008

Cocoa: Filterbar Control

This morning I've created this FilterBar (take a look at the picture below). You can add custom NSView and you can manage you groups with delegates.
so here is the link of Cocoa Filterbar Demo. And here you can find the Cocoa Filterbar Souce.

Saturday, November 8, 2008

Cocoa: Horizontal Box

It's a couple of days that I'm searching for something like QHBoxLayout (Qt Horizonal Box Layout) in Cocoa. There's NSMatrix that do something like this... but it uses NSCell and it sets the same size for all the cells, so this is not what I want. My solution is a simple NSView subclass...

And This is a simple "Main" to test the HBox.
- (NSTextField *)createTextField:(NSString *)text {
  NSTextField *field = [[NSTextField alloc] init];
  [field setStringValue:text];
  return [field retain];

- (NSButton *)createButton:(NSString *)caption {
  NSButton *button = [[NSButton alloc] init];
  [button setBezelStyle:NSRecessedBezelStyle];
  [button setButtonType:NSPushOnPushOffButton];
  [[button cell] setHighlightsBy:(NSCellIsBordered | NSCellIsInsetButton)];
  [button setShowsBorderOnlyWhileMouseInside:YES];
  [button setButtonType:NSOnOffButton];
  [button setTitle:caption];

  return [button retain];

- (void)awakeFromNib {
  [box addItem:[self createTextField:@"Label 1"]];
  [box addItem:[self createButton:@"Button 1"]];
  [box removeItemAtIndex:0];
  [box addItem:[self createTextField:@"Label 2"]];
  [box addItem:[self createButton:@"Say"]];

Download Here the Test Cocoa HBox Source.

Sunday, November 2, 2008

Quick Look: Look before you launch

Quick Look is a technology introduced in Mac OS X version 10.5 that enables client applications, such as Spotlight and the Finder, to display thumbnail images and full-size previews of documents.
Here you can Find the source code example:

Sunday, October 26, 2008

Qt Centre Programming Contest 2008 - Finalists

W00t Quartica is one of the Six finalist projects at Qt Centre Programming Contest 2008.

It's already a great success for me to be in the finalists list! I've learned so much from the Quartica Development and many new features and ideas are already in development to have (not so soon... due to expansive "Real" Work) in the next First (non alpha) release of the Project.

Thanks Trolls!

Cocoa: System StatusBar Item (Aka TrayBar)

Today's example is "How to add your own Item inside System Status Bar". It's really easy but the Apple OS X Human Interface Guidelines discourage it, at the end of the post you can find the Apple HIG notes.

Something about Names... Apple HIG call this MenuBar part "MenuBar Extra" (See Apple HIG Part III - The Menu Bar and Its Menus) using Cocoa you can get it from NSStatusBar systemStatusBar.

Saturday, October 25, 2008

Cocoa: Image Pattern as NSView Background

I Really like Apple Mail Note Editor, and today I've tried to do something like notes of

Mail uses html and css loaded into a WebView (WebKit) to render the background of the window. I've used a simple NSView, I've Inherited from it and I've added a couple of feature to render an image as background pattern. Below you can see the result and here you can Download the Source.

Saturday, October 11, 2008

Cocoa: Notification Badge

I Really like iPhone notifications... a little badge appears on the application's icon and displays something. For example in Apple Mail it displays the number of the unread mails.

Now the Code! a simple method that take an argument that is the number to show on the badge. (IMPORTANT: Take a look at the code, there're appIcon.tiff and starIcon.tiff that you should have in your Project's Resources).
-(void)showNotifyCountOnApplicationIcon: (int) currentCountOfUnread
  NSImage *originalIcon = [NSImage imageNamed:@"appIcon.tiff"];
  NSString *countdown = [NSString stringWithFormat:@"%i", currentCountOfUnread];
  NSImage *iconImageBuffer = [originalIcon copy];
  NSSize iconSize = [originalIcon size];

  // Create attributes for drawing the count.
  NSDictionary * attributes = [[NSDictionary alloc]
  initWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica-Bold" size:32],
  NSFontAttributeName, [NSColor whiteColor],
  NSForegroundColorAttributeName, nil];
  NSSize numSize = [countdown sizeWithAttributes:attributes];

  // Create a red circle in the icon large enough to hold the count.
  [iconImageBuffer lockFocus];
  [originalIcon drawAtPoint:NSMakePoint(0, 0)
          fromRect:NSMakeRect(0, 0, iconSize.width, iconSize.height)

  float max = (numSize.width > numSize.height) ? numSize.width : numSize.height;
  max += 28;
  NSRect circleRect = NSMakeRect(iconSize.width - max,
  iconSize.height - max, max, max);

  // Draw the star image and scale it so the unread count will fit inside.
  NSImage * starImage = [NSImage imageNamed:@"starIcon.tiff"];
  [starImage setScalesWhenResized:YES];
  [starImage setSize:circleRect.size];
  [starImage compositeToPoint:circleRect.origin operation:NSCompositeSourceOver];

  // Draw the count in the red circle
  NSPoint point = NSMakePoint(NSMidX(circleRect) - numSize.width / 2.0f + 2.0f,
  NSMidY(circleRect) - numSize.height / 2.0f + 2.0f);
  [countdown drawAtPoint:point withAttributes:attributes];

  // Now set the new app icon and clean up.
  [iconImageBuffer unlockFocus];
  [NSApp setApplicationIconImage:iconImageBuffer];
  [iconImageBuffer release];
  [attributes release];

With Mac OS X Leopard was introduced NSDockTile class that lets you customize the visual representation for your application’s miniaturized windows and application icon as they appear in the dock. So with this class you can easily add Notification Badge in this way.
NSDockTile *dockTile = [NSApp dockTile];

// setup our image view for the dock tile
NSRect frame = NSMakeRect(0, 0, dockTile.size.width, dockTile.size.height);
NSImageView *dockImageView = [[NSImageView alloc] initWithFrame: frame];
[dockImageView setImage: [NSImage imageNamed:@"appIcon.tiff"]];

// by default, add it to the NSDockTile
[dockTile setContentView: dockImageView];
[dockTile display];

// Show Notification Badge '45'
[dockTile setShowsApplicationBadge:YES];
[dockTile setBadgeLabel:@"45"];

Friday, September 26, 2008

[TIP] Test TCP Port with PHP

I need to test if specified TCP Port on specified Host is opened or Not, and i need to do it from a Web Service... This is my Solution a simple "ping" method written in PHP.

function qPing ($host, $port, $timeout = 5) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) return(1);

if (!socket_set_nonblock($socket))

$time = time();
while (!@socket_connect($socket, $host, $port)) {
$err = socket_last_error($socket);
if ($err == 115 || $err == 114) {
if ((time() - $time) >= $timeout) {
return(3); # Connection timed out.
echo $err . ' ' . socket_strerror($err) . "\n";


Sunday, September 7, 2008

Quartica Image Theater

I Really need a blackboard to fill with images, lines, rectangles and texts when i talk with someone. I think that is very useful when you're trying to explain something something to someone.

This is the current status of Quartica Image Theater. Nice, But it could be more nicer. Suggestions are always accepted!

Saturday, August 30, 2008

Qt4 TreeView - Items Filtering

In a few words, I've a QTreeView that displays folder items. I Need to filter items, showing empty folders.

QSortFilterProxyModel: For hierarchical models, the filter is applied recursively to all children. If a parent item doesn't match the filter, none of its children will be shown.

Using QSortFilterProxyModel the result is that the filter is applied on the foldes, so we've something like a root only filter. The solution is simple.. Inherits QSortFilterProxyModel and...
class QfTreeProxyModel : public QSortFilterProxyModel {
    QfTreeProxyModel (QObject *parent = 0)
      : QSortFilterProxyModel(parent)

    bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
      QModelIndex idx = sourceModel()->index(source_row, 0, source_parent);
      if (sourceModel()->hasChildren(idx))
      return(QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent));

Here you can find the example source code:

Monday, August 11, 2008

Qt4 Mac Dock Icon Click

When you click the "close button" of an application's window, on Mac OS X the window will be hidden but the application continue running. When you click on the Dock Icon, the application's window will be showed. This is the default behaviour for Mac Apps but Qt Apps doesn't the same. So, how we could implement this behaviour?

// Qt4 Headers
include <QApplication>
include <QWidget>

// Carbon Headers
#ifdef Q_WS_MAC
#include <Carbon/Carbon.h>

class Application : public QApplication {

Application (int& argc, char **argv);

QWidget *mainWindow (void) const;

QWidget *m_mainWindow;

#ifdef Q_WS_MAC
AEEventHandlerUPP m_appleEventProcessorUPP;

#endif // !_APPLICATION_H_

Here, we've implemented an Application class that Inherits from QApplication. This class contains a reference to the App's Main Window.
#ifdef Q_WS_MAC
static OSStatus appleEventProcessor(const AppleEvent *ae,
AppleEvent *event,
long handlerRefCon)
Application *app = (Application *) handlerRefCon;

OSType aeID = typeWildCard;
OSType aeClass = typeWildCard;

AEGetAttributePtr(ae, keyEventClassAttr, typeType, 0,
&aeClass, sizeof(aeClass), 0);
AEGetAttributePtr(ae, keyEventIDAttr, typeType, 0,
&aeID, sizeof(aeID), 0);

if (aeClass == kCoreEventClass) {
if (aeID == kAEReopenApplication) {
return noErr;

return eventNotHandledErr;

Application::Application (int& argc, char **argv)
: QApplication(argc, argv)
// Don't Quit the App on Window Close

// Initialize Main Window
m_mainWindow = new QLabel("Test Main Window");

#ifdef Q_WS_MAC
// Install Reopen Application Event (Dock Clicked)
m_appleEventProcessorUPP = AEEventHandlerUPP(appleEventProcessor);
AEInstallEventHandler(kCoreEventClass, kAEReopenApplication,
m_appleEventProcessorUPP, (long) this, true);

QWidget *Application::mainWindow (void) const {

Thats all folks! Run the app, Click on close button and then click on the dock icon to see the result.

Just for Fun - Qt4 DeviantArt

Just for Fun, I've developed a "Ten Minutes App" to demonstrate how to retrieve images from DeviantArt Feed. (This will be a Quartica Plugin).

You can find the source here: deviantart-sample.tar.bz2

Qt4 "Freedesktop" MIME Type

A couple of weeks ago, i've released at Qt Apps a Qt Component called QFreeDesktopMime that is a simple class for determining the MIME type of files using FreeDesktop Specification.

How to use this class? it's really simple.

Example 1: Get Information about specified MIME Type
QFreeDesktopMime mime;
QString description = mime.description("application/epub+zip");
QString expandedAcronym = mime.expandedAcronym("text/x-xslfo");
QString acronym = mime.acronym("text/x-xslfo");

Example 2: Extract MIME Type and information from File Name (Results based on File Extension)
QFreeDesktopMime mime;
QString mimeType = mime.fromFileName("test.png");
QString mimeDescription = mime.description();

Example 3: Extract MIME Type and information from File (Data)
QFreeDesktopMime mime;
QString mimeType = mime.fromFile("/home/oz/myUnknownFile");
QString mimeDescription = mime.description();

If fromFile() method doesn't find the matching data it tries to use fromFileName() method to get the MIME Type. In all cases if file's MIME Type wasn't found it returns an empty QString.

Saturday, August 9, 2008

Qt4 Image Transfers Viewer

Today a new Qt4 Effect developed for Quartica File Transfers View. The main idea is to remove the unuseful progressbar from Downloading Images and replace it with something more intuitive.

In this way, you can see the full image and the current completed part. And now a Very Low quality video that demonstrate how it works (please, wait 7 seconds before going away).

Wednesday, August 6, 2008

Qt4 ThumbViewer

It's only a Work in Progress class, but this screenshot will be the Album Viewer Widget of Quartica.
All the images are behind a shadow effect and so it looks all darker. What do you think about it?