Wednesday, December 28, 2011

Postgresql query in transaction

The following is short example of query in transaction. We will delete all records and will insert new one in single transaction those actions both fails or both succeeds:
BEGIN;
DELETE FROM hi_value;
INSERT INTO hi_value(next_value) VALUES(5308);
COMMIT;

Developing software is like building something fairly simple out of bricks (link)

Although very few managers ever express it directly this way, many behave as if developing a piece of software is like building something fairly simple out of bricks. It might be something large. But it’s still fairly simple. This is tempting. The inexperienced person thinks that bricks are easy to understand: they’re all the same: if you know how to work with one, you know how to work with them all. You can measure the progress of building something out of bricks by counting the bricks in place. And anyone can contribute, even if only by moving bricks from one place to another using brute force. Read here more...

Tuesday, December 27, 2011

Code evolution vs. Intelligent design (link)

You are feeling proud of yourself. You sit back after having just polished off another piece of masterful code and look down at the next item on your to-do list. You start to think through how you are going to tackle the next problem and then it dawns on you. To implement the next step you are going to have to go back and dig up all that perfect code you have just finished writing, hack it apart and bolt-on a whole new bunch of functionality. The perfect structure you have been building might not make it through through the carnage. Read here more...

Friday, December 23, 2011

HipHop for PHP at Hyves (link)

At Hyves, we use HipHop to run our web servers and our daemons, which are also written in in PHP. In this blog, I will detail some of our experiences and results. Read more...

Thursday, December 22, 2011

All Programmers Are Self-Taught (link)

A pitching coach teaches you how to pitch, but a CS professor doesn’t teach you how to code. Read more...

Tuesday, December 20, 2011

The Switch: Python to Node.js (link)

Cloudkick was primarily written in Python. Most backend services were written in Twisted Python. The API endpoints and web server were written in Django, and used mod_wsgi. We felt that while we greatly value the asynchronous abilities of Twisted Python, and they matched many of our needs well, we were unhappy with our ability to maintain Twisted Python based services. Specifically, the deferred programming model is difficult for developers to quickly grasp and debug. It tended to be ‘fail’ deadly, in that if a developer didn’t fully understand Twisted Python, they would make many innocent mistakes. Django was mostly successful for our needs as an API endpoint, however we were unhappy with our use of the Django ORM. It created many dependencies between components that were difficult to unwind later. Cloud Monitoring is primarily written in Node.js. Our team still loves Python, and much of our secondary tooling in Cloud Monitoring uses Python. Read here more...

Monday, December 19, 2011

Ideas and execution (link)

Some people regret the fact that they can come up with lots of great ideas, but cannot execute them. Others are frustrated that they can execute well, but cannot come up with an idea that is original or noteworthy... Read more here...

How big are PHP arrays (and values) really? (link)

Very interesting observations about PHP implementation

Tuesday, December 13, 2011

More shell, less egg (link)

Jon Bentley had a regular column called “Programming Pearls” in the Communications of the ACM (you may have come across this collection of some of his columns). In 1986 he got interested in literate programming, so he asked Donald Knuth to write a program in that style as a guest column and Doug McIlroy to write a literary-style critique of it. Read more here...

Tuesday, December 6, 2011

Example of Regex: validating GUID

Here is a simple example of Regex used to validate GUID.
using System;
using System.Text.RegularExpressions;

namespace Program
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string[] uuids = new string[]
            {
                Guid.NewGuid().ToString("D"), 
                Guid.NewGuid().ToString("D"),
                "some random string"
            };
   
            foreach(string uuid in uuids)
            {
                Console.WriteLine("uuid: '{0}' macth '{1}'", 
                    uuid, Regex.IsMatch(uuid, @"^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$"));
            }
        }
    }
}

Friday, December 2, 2011

Tyranny of the tools (link)

"When we create Agile teams, we create teams of real, live people. That means our control and communication systems must be built around the qualities and capabilities of people, not robots. We are doing much more in a team room than simply transferring abstract pieces of metadata around about a project. We are gaining a common emotional understanding of the problems and the players, getting a deep feeling for what might go wrong and what we need to worry about, adjusting our work patterns, our communication techniques, and our problem solving skills to this particular team, this particular problem, in this particular situation." ... "An Agile team isn't a team that moves stories across a wall. It's a team that looks each other in the eye and talks about things the Product Owner wants and how they're going to give it to them." Read more...

Tuesday, November 8, 2011

In managed code we trust, our recent battles with the .NET Garbage Collector (link)

Recently Marc blogged about some performance optimizations we implemented at Stack Overflow to work around some Garbage Collection (GC) issues. This post evoked many emotions and opinions both on his Blog and on Hacker News. In this post I would like to cover some of the history involved with this particular problem, explain how we found it and eventually fixed it.

Read more here...

Saturday, November 5, 2011

Quote of The Day - 2011-11-05

“Fashion is what seems beautiful now but looks ugly later; art can be ugly at first but it becomes beautiful later.” - Steve Jobs

Thursday, October 20, 2011

NHibernate FAQ: how to specify exact database type in mapping

So you have simple class mapping like this:


 

  
   
    hi_value
    next_value
    1
   
  

  

  

  

 

and want to specify exact database type to „Timing“ property. So what should you do? You need the following very simple change in your mapping file:
  
   
  
That's it! Happy hibernating!

Wednesday, October 12, 2011

ISO C++11 Published (link)

ISO has now published the new C++11 standard and issued a press release...

More here...

Friday, October 7, 2011

Why the Era of Free Stuff Is Ending (link)

Just a couple of years ago, writer Chris Anderson asserted that free was the new price of everything . But now, it's looking like time to say farewell to free.

Read more here...

Steve Jobs: A Few Memories (link)

I’m so sad this evening—as millions are—to hear of Steve Jobs’s death. Scattered over the last quarter century, I learned much from Steve Jobs, and was proud to consider him a friend. And indeed, he contributed in various ways to all three of my major life projects so far: Mathematica, A New Kind of Science and Wolfram|Alpha.

Read more here...

Wednesday, October 5, 2011

The Global Interpreters lock and Ruby/Python concurrency (link)

The Global Interpreter Lock has also been in a subject a lot of discussions in the Python community and it’s not surprising that the Ruby community experiences the same debates since the evolution of their implementations are somewhat similar.

Read more about GIL

Tuesday, October 4, 2011

When "clever" goes wrong: how Etsy overcame poor architectural choices (link)

Ross Snyder, a senior software engineer at craft e-commerce site Etsy, recounted the story of the evolution of his company's technical architecture to a roomful of fellow travelers at the Surge conference in Baltimore. It was a story that, by his admission, is not entirely his own—he's only been with Etsy for a year and a half, which accounts for the “after” phase of the company's architectural picture.

Read more here...

Monday, October 3, 2011

Asynchronous Programming with Async and Await (msdn link)

Visual Studio 11 Developer Preview introduces a simplified approach to asynchronous programming that makes code easier to write, understand, and maintain

The approach relies on two new keywords, the async (C#) modifier and the await (C#) operator.

MSDN article...

Friday, September 30, 2011

Xerox PARC, Apple, and the truth about innovation. (link)

In late 1979, a twenty-four-year-old entrepreneur paid a visit to a research center in Silicon Valley called Xerox PARC. He was the co-founder of a small computer startup down the road, in Cupertino. His name was Steve Jobs.

a href="http://www.gladwell.com/2011/2011_05_16_a_creationmyth.html">Read all article...

Thursday, September 29, 2011

Agile Scrum: Delivering Broken Software Since 1991 (link)

Agile Scrum: Delivering Broken Software Since 1991. The first third of this article describes Scrum; The second third describes how it gets subverted to produce broken software; The final third is where the practical advice for avoiding this is...

Read all article here...

It’s the end of the web as we know it (link)

When you own a domain you’re a first class citizen of the web. A householder and landowner. What you can do on your own website is only very broadly constrained by law and convention. You can post the content you like...

If you use a paid-for web service at someone else’s domain you’re a tenant. A second class citizen. You don’t have much control. You’ll probably have to live with your landlord’s furniture and decoration and a restrictive set of rules...

Read here full article...

Tuesday, September 27, 2011

I realize how ridiculous it sounds to say "Quake changed my life," but it honestly did.

Read full article here...

Monday, September 26, 2011

PostgreSQL Magazine: Issue #00 is out ! (link)

Launching a print magazine in 2011 may look like a weird idea… But PostgreSQL is now 25 years old and although it is one of the oldest open source projects alive, there are no print media for its large user base…

Go and read it now! :)

Graphics programming black book (link)

Michael Abrash's classic Graphics Programming Black Book is a compilation of Michael's previous writings on assembly language and graphics programming (including from his "Graphics Programming" column in Dr. Dobb's Journal). Much of the focus of this book is on profiling and code testing, as well as performance optimization. It also explores much of the technology behind the Doom and Quake 3-D games, and 3-D graphics problems such as texture mapping, hidden surface removal, and the like. Thanks to Michael for making this book available.

Grab book copy here...

Friday, September 23, 2011

How To Write Unmaintainable Code (link)

In the interests of creating employment opportunities in the Java programming field, I am passing on these tips from the masters on how to write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code. Then again, if you followed all these rules religiously, even you wouldn't be able to maintain the code!

Read here...

Quake 2 Source Code Review (link)

I spent about a month in my spare time reading the source code of Quake II. It was a wonderful learning experience since one major improvement in idTech3 engine was to unify Quake 1, Quake World and QuakeGL into one beautiful code architecture. The way modularity was achieved even though the C programming language doesn't feature polymorphism was especially interesting.

Read full article...

Thursday, September 22, 2011

Learn REST: A Tutorial (link)

REST is an architecture style for designing networked applications. The idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls between machines.

Learn more...

Wednesday, September 21, 2011

Stack-checking a program that will execute in orbit (link)

For those of us that were raised with Z80 CPUs, it is abundantly clear that we are living in "times of plenty"; most developers no longer have to think about things like "fitting into memory" or "having enough stack space". Moore's Law provided orders of magnitude of improvements in both CPU speeds and memory sizes; so big in fact, that resource-wasting virtual machines dominate our everyday software, and we don't even feel it.

Read full article...

Tuesday, September 20, 2011

Quote of The Day 2011-09-20

Those who stand for nothing fall for anything Read more...

Greedy Register Allocation in LLVM 3.0 (link)

LLVM has two new register allocators: Basic and Greedy. When LLVM 3.0 is released, the default optimizing register allocator will no longer be linear scan, but the new greedy register allocator.

With its global live range splitting, the greedy algorithm generates code that is 1-2% smaller, and up to 10% faster than code produced by linear scan.

Read more...

What’s wrong with this code, really? (link)

Here are five lines of code I found during a review not too long ago. This code had been tested and was ready for release.

Feel free to stare at this for a while and absorb the quality.

Monday, September 19, 2011

WinRT demystified (link)

Microsoft is using the launch of Windows 8 as an opportunity to fix long-standing problems with Windows, bring a new user interface, and enable a safe AppStore model for Windows. To do this, they have created a third implementation of the XAML-based UI system. Unlike WPF which was exposed only to the .NET world and Silverlight which was only exposed to the browser, this new implementation is available to C++ developers, HTML/Javascript developers and also .NET developers.

Read full article...

Friday, September 16, 2011

openshift by redhat (link)

OpenShift is a collection of cloud services forming a solid redefining Platform-as-a-Service for developers who build apps on open source technologies.

Go read...

defining IaaS, PaaS, and SaaS for cloud computing (link)

Looking through cloud literature, it seems we've run out of three letter acronyms (TLA), so we're now using four letter acronyms (FLA?). Chief among these are the "as a service" acronyms which describe what level of stuff is handled by the provider. Wikipidia has some sort of explanation buried in the cloud computing page, but I thought I'd give the abridged version.

Read full article...

Thursday, September 15, 2011

What's New in the .NET Framework 4.5 (MSDN link)

This article contains information about key features and improvements in the .NET Framework 4.5 Developer Preview.

Read at MSDN...

Ultimate Vim Config (GitHub link)

This is a distribution of vim plugins and tools intended to be run on top of VIM. It is a good starting point for anyone intending to use VIM for development.

here it is...

Wednesday, September 14, 2011

80% of People Quietly Despise Their Lives (link)

This isn’t a statistic, it’s a casual observation based on talking to way more people about their careers than any normal person should. I’m convinced that most people dislike their lives, not in any robust way but with the kind of casual contempt that can be easily ignored by a society that prizes movement and action above just about everything else.

Full article is here...

Tuesday, September 13, 2011

Cancer and Aging (link)

The main balance is between aging and cancer. Aging protects us from cancer, while staying "young" at older ages such as immortality predisposes you to cancer.

Read more here...
Only a part – howbeit a very important part – of our behavior is practical… The remainder serve simply to express ideas that the organism yearns to express, i.e. to act upon without practical purpose, without any view to satisfying other needs than the need of completing in overt action the brain’s symbolic process.

- Susanne K. Langer

PostgreSQL 9.1 released

"PostgreSQL 9.1 provides some of the most advanced enterprise capabilities of any open source database, and is backed by a vibrant and innovative community with proven customer success. PostgreSQL is well positioned for building and running applications in the cloud," said Charles Fan, Sr. VP R&D, VMware.

Read more...

Monday, September 12, 2011

Nancy - .NET Micro Web Frameworks (link)

Definition of Micro Web Frameworks:
  • Lean - provides only the bare essentials for serving web applications on the web
  • Simple setup - getting web pages up and running should not require a lot of infrastructure code
  • Extensible API - enhanced features should be provided by other libraries that extend the framework
  • "Close to the metal"
Link to video, presentation and code by nicholascloud.com

Saturday, September 10, 2011

Common mistakes and anti-patterns NHibernate user programmers make (link)

What are the most common mistakes and anti-patterns NHibernate user programmers make? Please explain why those are bad practices or give link to resource for further reading. Read answers here...

Friday, September 9, 2011

Java 8 lambda syntax decided - same as C# and Scala (link)

After considering a number of alternatives, we decided to essentially adopt the C# syntax. We may still deliberate further on the fine points (e.g., thin arrow vs fat arrow, special nilary form, etc), and have not yet come to a decision on method reference syntax. Read full article...

Deconstructing an ELF File (link)

A friend recently asked me to find the password for a little hard-to-hack program he had written and I agreed to it. The short journey of a few hours that led me to its password were extremely interesting and this article describes the process as well as some of the new techniques learnt along the way. Read article here...

Thursday, September 8, 2011

The Ten Minute Build (link)

Given a development environment any developer should be able to get hold of the source code, click a button or type a simple command and run a build. The build should compile and perform its unit tests within about ten minutes. Read full article...

Wednesday, September 7, 2011

How You Should Go About Learning NoSQL (link)

Three simple rules to learning NoSQL:
  • use MongoDB
  • take 20 minute to learn Redis
  • watch this video to understand Dynamo
Read full article here...

Saturday, September 3, 2011

Shocking photo created a hero, but not to his family (link)

The mob was already waiting for James Zwerg by the time the Greyhound bus eased into the station in Montgomery, Alabama.

Looking out the window, Zwerg could see men gripping baseball bats, chains and clubs. They had sealed off the streets leading to the bus station and chased away news photographers. They didn't want anyone to witness what they were about to do.

Zwerg accepted his worst fear: He was going to die today.

Read full story...

Friday, September 2, 2011

What would it be like walking around on a cube-shaped planet? (link)

If the earth was a perfect cube, what would the gravitational effect be at the edges? Could you casually step over the 90-degree bend onto an adjacent face?

Read full article...

Thursday, September 1, 2011

10 Reasons Why I’m Done With Windows (link)

The wife’s computer crashed last week. A big meaty crash, which is unusual for Windows XP, despite what the haters say. Apart from the execrable Windows Vista product, modern versions of the operating system have been extremely stable. Seriously.

But in this case the crash was one of those which results in an endless boot-up loop, lots of blue screen, very little computing. Windows XP wouldn’t reinstall for some reason, so now I had a choice - either plonk down some cash for Windows 7, which although a nice solid system is rather expensive, or take another look at Linux to see if that would work.

Read full article...

Wednesday, August 31, 2011

LHC results put supersymmetry theory 'on the spot' (link)

Results from the Large Hadron Collider (LHC) have all but killed the simplest version of an enticing theory of sub-atomic physics.

Researchers failed to find evidence of so-called "supersymmetric" particles, which many physicists had hoped would plug holes in the current theory.

Read full article...

Tuesday, August 30, 2011

Experiments Show Gravity Is Not an Emergent Phenomenon (link)

One of the most exciting ideas in modern physics is that gravity is not a traditional force, like electromagnetic or nuclear forces. Instead, it is an emergent phenomenon that merely looks like a traditional force.

Read full article here...

Monday, August 29, 2011

Regular expressions in lexing and parsing (link)

I should say something about regular expressions in lexing and
parsing. Regular expressions are hard to write, hard to write well,
and can be expensive relative to other technologies. (Even when they
are implemented correctly in N*M time, they have significant
overheads, especially if they must capture the output.)

Read full article...

Monday, August 22, 2011

Commentary on the Sixth Edition UNIX Operating System (link)

This directory contains a copy of John Lion's “A commentary on the Sixth Edition UNIX Operating System”. This form of the document was published on the USENET alt.folklore.computers newsgroup in May 1994.

Link to page...

Saturday, August 20, 2011

What is intelligence, anyway? By Isaac Asimov (link)

When I was in the army, I received the kind of aptitude test that all soldiers took and, against a normal of 100, scored 160. No one at the base had ever seen a figure like that, and for two hours they made a big fuss over me.

Read full story here...

Friday, August 19, 2011

A bit of Go language: type switch

Not a long time ago I discovered very useful Go language construct “type switch”.

switch t := someValue.(type) {
default:
    fmt.Printf("unexpected type %T", t)
case bool:
    fmt.Printf("boolean %t\n", t)
case int:
    fmt.Printf("integer %d\n", t)
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t)
case *int:
    fmt.Printf("pointer to integer %d\n", *t)
}

Description in Effective Go

A switch can also be used to discover the dynamic type of an interface variable. Such a type switch uses the syntax of a type assertion with the keyword type inside the parentheses. If the switch declares a variable in the expression, the variable will have the corresponding type in each clause.

My use case

I have started writing bindings of libcurl for go language (https://github.com/dkucinskas/gocurl).
In libcurl we have C function: curl_easy_setopt(CURL *curl, CURLoption option, ...);

I'm using cgo utility for binding generation and this utility doesn’t support varargs yet. So I wrote wrapper function in C for each type of arguments. And then I needed way to know then to invoke each specific type of wrapper function. Here we have prefect case for type switch. Here follows the code:

func (e *Easy)SetOption(option Option, param interface{}) {
    switch v := param.(type) { 
    default:
        fmt.Printf("unexpected type %T", v)
    case uint64:
        e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
    case string:
        e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
    } 
}

Thursday, August 18, 2011

"Avoid Premature Optimization" Does Not Mean "Write Dumb Code" (link)

First there's a flurry of blog entries citing a snippet of a Knuth quote: "premature optimization is the root of all evil." Then there's the backlash about how performance needs to be considered up front, that optimization isn't something that can be patched in at the end. Around and around it goes.

Read full article here...

Monday, August 15, 2011

How far do I have to ride my bike to pay back its carbon footprint? (link)

I'm thinking about switching my daily commute from four wheels to two. But I'm concerned about all the energy it takes to manufacture and ship a new bicycle. How many miles would I need to substitute a bike for my car before I've gone "carbon neutral"?

Read full article...

Understanding Linux CPU Load - when should you be worried? (link)

Most people have an inkling of what the load averages mean: the three numbers represent averages over progressively longer periods of time (one, five, and fifteen minute averages), and that lower numbers are better. Higher numbers represent a problem or an overloaded machine. But, what's the the threshold? What constitutes "good" and "bad" load average values? When should you be concerned over a load average value, and when should you scramble to fix it ASAP?

Read full article...

Sunday, August 14, 2011

Whatever happened to programming PART 2? (link)

We talk about ‘flow’ quite a lot in software and I just have to wonder what’s happening to us all in that respect. Just like a conversation becomes stilted if the speakers keep having to refer to their phrasebooks and dictionaries, I wonder how much longer it will be possible to retain any sort of flowful state when writing software. Might the idea of mastery disappear forever under a constant torrent of new tools and technologies?

Read full article here...

How Virtuous Is Your Code? (link)

Want to get in an argument with a developer? Tell them their code isn’t very good. The hackles rise, adrenaline kicks in, and then you get that “how dare you” look. But even though we may defend the quality of our code today in passionate arguments and reasoned apologetics, three years in the future—or even three weeks later—we may look back on it with embarrassment.

Read all article here...

Saturday, August 13, 2011

We have an international standard: C++0x is unanimously approved (link)

The final ISO ballot on C++0x closed on Wednesday, and we just received the results: Unanimous approval.

Read here...

Friday, August 12, 2011

Mono: A cure for Microsoft monotheism (link)

When Attachmate bought Novell, it seemed for a while as if the open-source version of .NET would be a casualty.

Laying off the Mono team turned out to be a blessing in disguise, according to Miguel de Icaza, who now runs Xamarin and develops the Mono project, with a perpetual licence from Novell to take care of IP worries.

Read full article...

.Net DI container speed test (link)

You probably don't care why I've done this, but if you don't even care about most of the details of this test, let me lay it on you short and sweet: Autofac, Castle.Windsor, and StructureMap put out some excellent, consistent numbers; Spring.Net is middle of the road; Ninject is consistently the slowest of the pack by several orders of magnitude; and finally Unity showed such a weird behavior that made me question both the validity of my approach and the sanity of its developers (mostly kidding, ctavares is awesome).

Read full article...

Thursday, August 11, 2011

NHibernate 3.2 and default proxyfactory

Now NHibernate comes with default proxyfactory pre-configured. So basically you don't need the following line in your configuration files any more:

<property name='proxyfactory.factory_class'>INSERT_YOUR_FACTORY_NAME_HERE</property>

unless you know what you are doing and why...

Monday, August 8, 2011

Saturday, August 6, 2011

Understanding the Git Workflow (link)

If you don’t understand the motivation behind Git’s design, you’re in for a world of hurt. With enough flags you can force Git to act the way you think it should instead of the way it wants to. But that’s like using a screwdriver like a hammer;

Read here...

Friday, August 5, 2011

Agile: The good, the bad and the ugly.

Most companies are adopting Agile as the “de facto” process for their new projects, while is clear that overall is better than waterfall, it still has its defects. This article does a brief overview of what is good, bad and ugly about agile.

Explicating the new C++ standard (C++0x), and its implementation in VC10 (link)

As you might be aware, the C++ language is being updated by the ISO standard. The codename for the new C++ language is C++0x, and many compilers have already introduced some of the features. This tutorial is an attempt to give you an introduction to the new changes in the C++ language.

Read here...

Thursday, August 4, 2011

Random number generation using C++ TR1 (link)

This article explains how to use the random number generation facilities in C++ using the TR1 (C++ Standards Committee Technical Report 1) extensions. We will cover basic uniform random number generation as well as generating samples from common probability distributions: Bernoulli, binomial, exponential, gamma, geometric, normal, and Poisson.

More here...

Getting started with C++ TR1 regular expressions (link)

This article is written for the benefit of someone familiar with regular expressions but not with the use of regular expressions in C++ via the TR1 (C++ Standards Committee Technical Report 1) extensions. Comparisons will be made with Perl for those familiar with Perl, though no knowledge of Perl is required. The focus is not on the syntax of regular expressions per se but rather how to use regular expressions to search for patterns and make replacements.

Read here...

The man you want to be does not matter (link)

“Ambition is the last refuge of the failure.” ~ Oscar Wilde
Read here

Wednesday, August 3, 2011

In 2500 years, we use up the Milky Way galaxy (link)

Since the beginning of the Industrial Revolution, we have seen an impressive and sustained growth in the scale of energy consumption by human civilization. Plotting data from the Energy Information Agency on U.S. energy use since 1650 (1635-1945, 1949-2009, including wood, biomass, fossil fuels, hydro, nuclear, etc.) shows a remarkably steady growth trajectory, characterized by an annual growth rate of 2.9%...
Read here more...

Firefox performance annihilate Chrome when you have many tabs open (link)

I like breaking stuff! Whenever I try a new feature it breaks. This used to be an annoying “skill” when I started programming but over the time I learned to appreciate it.

Currently I am testing various memory allocation strategies for Firefox. Read more...

Monday, August 1, 2011

Running log 2011-08-01

Just finished 1 lap ~2km...
While running I decide that I won't by ipod because there is something special about running in silence without all this noise... :)

Friday, July 29, 2011

Whatever happened to programming? (link)

I want to make things, not just glue things together. When people ask me what I like about my job, I always say the same thing: that its the thrill of starting with nothing and making something. That, for me, is the essence of programming, and it hurts that there isn’t as much of it about as there used to be.

Read a full article here...

Oracle released Java 7 today with hotspot compiler optimizations, which miscompile some loops

Oracle released Java 7 today. Unfortunately it contains hotspot compiler
optimizations, which miscompile some loops. This can affect code of several
Apache projects. Sometimes JVMs only crash, but in several cases, results
calculated can be incorrect, leading to bugs in applications (see Hotspot
bugs 7070134 [1], 7044738 [2], 7068051 [3]).

Read more...

The Secret Ingredient In Your Orange Juice (link)

Read here...

Thursday, July 28, 2011

GeoCoding with C# and Google Geocoding API V3 (using JSON this time)

In previous article I have shown how to use Google Geocoding API V3 from C#. We were using XML output format in that example. Now we will use JSON output format. For JSON parsing I will use Json.NET library.

Ok here is the code GeoCoding with C# and Google Geocoding API V3 using JSON output format:
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;

namespace GeoCoderJson
{
    class Program
    {
        public class GeoLocation
        {
            public decimal Lat { get; set; }
            public decimal Lng { get; set; }
        }

        public class GeoGeometry
        {
            public GeoLocation Location { get; set; }
        }

        public class GeoResult
        {
            public GeoGeometry Geometry { get; set; }
        }

        public class GeoResponse
        {
            public string Status { get; set; }
            public GeoResult[] Results { get; set; }
        }

        static void Main (string[] args)
        {
            string url = "http://maps.googleapis.com/maps/api/geocode/" +
                "json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";

            WebResponse response = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
                request.Method = "GET";
                response = request.GetResponse ();
                if (response != null)
                {
                    string str = null;
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(stream))
                        {
                            str = streamReader.ReadToEnd ();
                        }
                    }

                    GeoResponse geoResponse = JsonConvert.DeserializeObject&lt;GeoResponse&gt;(str);
                    if (geoResponse.Status == "OK")
                    {
                        int count = geoResponse.Results.Length;
                        for (int i = 0; i &lt; count; i++)
                        {
                            Console.WriteLine ("Lat: {0}", geoResponse.Results [i].Geometry.Location.Lat);
                            Console.WriteLine ("Lng: {0}", geoResponse.Results [i].Geometry.Location.Lng);
                        }
                    } 
                    else
                    {
                        Console.WriteLine ("JSON response failed, status is '{0}'", geoResponse.Status);
                    }
                }
            } 
            catch (Exception ex)
            {
                Console.WriteLine (ex.Message);
            } 
            finally
            {
                Console.WriteLine ("Clean up");
                if (response != null)
                {
                    response.Close ();
                    response = null;
                }
            }

            Console.WriteLine ("Done.");
            Console.ReadLine ();
        }
    }
}

And here is the output:
Lat: 37.4217420
Lng: -122.08416580
Clean up
Done.

Wednesday, July 27, 2011

Steve Yegge let's solve real problems!

Steve Yegge quits Google in the middle of his speech [OSCON Data 2011]video is here. He encourages all hacker to learn some math, statistics and bioinformatics for good. Let's stop making social crap like Facebook (include clones). Let's help solve some long standing hard problem like this one!

Running log 2011-07-27

Just finished 1 lap ~2km... My mind is clear again :)

Ten Ways to Check if an Integer Is a Power Of Two in C (link)

read here...

How to get started with functional programming (link)

A good advice read here...

Tuesday, July 26, 2011

The Higgs Boson - A one page explanation! (link)

a fine reading for coffee break...

Five Popular Web Strategies That Don't Work (link)

Very good summary...

Stand-alone code for numerical computing (link)

Go here...

FTPS also known as FTP over SSL example with C++ and libCURL


In this post I showed how to use C# and libcurl.NET to connect to FTPS. Now I will use C++ so you could compare both implementations.

Read the following Wikipedia article for background about FTPS.

And here follows the code...
#include <string>
#include <iostream>
#include "CURLWrapper.h"

using std::cout;
using std::endl;
using std::string;

static string buffer;

static int writer(char *data, size_t size, size_t nmemb, string *buffer)
{
    int result = 0;
    if (buffer != NULL)
    {
        buffer->append(data, size * nmemb);
        result = size * nmemb;
    }

    return result;
}

int main()
{
    string url = "ftp://user:thepassword@ftp.somesite.com/dir/";

    cout << "Will retrive from url: '" << url << "'" << endl;

    CURLcode code = CURLWrapper::GlobalInit(CURL_GLOBAL_ALL);
    if (code != CURLE_OK)
    {
        cout << "CURL init failed" << endl;
        return 0;
    }

    CURLWrapper::Easy easy;
    easy.SetOption(CURLOPT_URL, url.c_str());
    easy.SetOption(CURLOPT_SSL_VERIFYPEER, 0);
    easy.SetOption(CURLOPT_SSL_VERIFYHOST, 0);
    easy.SetOption(CURLOPT_FTP_SSL, CURLFTPSSL_TRY);

    easy.SetOption(CURLOPT_FTPLISTONLY, 1);

    easy.SetOption(CURLOPT_WRITEFUNCTION, writer);
    easy.SetOption(CURLOPT_WRITEDATA, &buffer);
    easy.Perform();

    if (easy.IsOK())
    {
        cout << "CURL: response is OK " << endl;
 
        if (!buffer.empty())
        {
            cout << buffer << endl;
        }
        else
        {
            cout << "CURL: respose is empty! " << endl;
        }
    }
    else
    {
        cout << "CURL Error: [ " << easy.GetError() <<  ] - " 
            << easy.GetErrorMessage() << endl;
    }

    CURLWrapper::GlobalCleanup();
}

And here is code for CURLWrapper class (I have added GlobalInit and GlobalCleanup procedures from the previous libCURL post here)...

"CURLWrapper.h"
#ifndef CURL_WRAPPER_H
#define CURL_WRAPPER_H

#include <string>
#include "curl/curl.h"

namespace CURLWrapper 
{
    CURLcode GlobalInit(int flags);
    void GlobalCleanup();
    
    class Easy
    {
    public:
        Easy();
        ~Easy();

        void Init();
        void Cleanup();
        void Reset();

        template <typename T, typename V>
        void SetOption(T option, V parameter)
        {
            curl_easy_setopt(mCurl, option, parameter);
        }

        void Perform();
        bool IsOK();
        CURLcode GetError();
        std::string GetErrorMessage();
    
    private:
        void ErrorBuffer(char* buffer); 
    
    private:
        CURL* mCurl;
        char mErrorBuffer[CURL_ERROR_SIZE + 1];
        CURLcode mCode;
    };
}
#endif //#ifndef CURL_WRAPPER_H

"CURLWrapper.cpp"
#include <memory>
#include <algorithm>
#include "CURLWrapper.h"
#include "curl/curl.h"

CURLcode CURLWrapper::GlobalInit(int flags)
{
    return curl_global_init(flags);
}

void CURLWrapper::GlobalCleanup()
{
    curl_global_cleanup();
}

CURLWrapper::Easy::Easy()
    : mCurl(curl_easy_init()),
    mCode(CURLE_OK)
{
}

CURLWrapper::Easy::~Easy()
{
    curl_easy_cleanup(mCurl);
}

void CURLWrapper::Easy::Init()
{
}

void CURLWrapper::Easy::Cleanup()
{
    curl_easy_cleanup(mCurl);
}

void CURLWrapper::Easy::Reset()
{
    curl_easy_reset(mCurl);
    std::fill(mErrorBuffer, mErrorBuffer + CURL_ERROR_SIZE + 1, 0);
    ErrorBuffer(mErrorBuffer);
    mCode = CURLE_OK;
}

void CURLWrapper::Easy::ErrorBuffer(char* buffer)
{
    SetOption(CURLOPT_ERRORBUFFER, (void*)buffer);
}

void CURLWrapper::Easy::Perform()
{
    mCode = curl_easy_perform(mCurl);
}

bool CURLWrapper::Easy::IsOK()
{
    return mCode == CURLE_OK;
}

CURLcode CURLWrapper::Easy::GetError()
{
    return mCode;
}

std::string CURLWrapper::Easy::GetErrorMessage()
{
    return std::string(mErrorBuffer);
}

And as always the magic command:
g++ -g -Wall -o prog prog.cpp CURLWrapper.cpp -lcurl


So this is it, I hope that this post will help you to discover this wonderful libCURL library ;)

Monday, July 25, 2011

Smart pointers in Boost, TR1, and C++x0 (link)

This post is an overview of the smart pointers available in Boost, TR1, and C++x0. It also touches on the availability and portability of the last two options when it comes to various C++ compilers. Read full article here...

Sunday, July 24, 2011

Get there slower and enjoy the ride!

The Acceleration of Addictiveness (link)

I used to think running was a better form of exercise than hiking because it took less time. Now the slowness of hiking seems an advantage, because the longer I spend on the trail, the longer I have to think without interruption.

- Paul Graham (The Acceleration of Addictiveness)

Friday, July 22, 2011

C# IDbConnection && IDbCommand && IDataReader: where is my abstraction?

Way every ado.net example I spot on internet is still coded against concrete implementation of Connection && Command && DataReader instead of Interfaces?

It is so simple to use provider factory here follows a code example:
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;

namespace Utils
{
  public static class DBUtils
  {
    public static IList ExecuteQuery(string query, string connectionString, string providerName)
    {
      if (string.IsNullOrEmpty(query))
        throw new ArgumentNullException("Query text is null or empty!");

      if (string.IsNullOrEmpty(connectionString))
        throw new ArgumentNullException("ConnectionString is null or empty!");

      if (string.IsNullOrEmpty(providerName))
        throw new ArgumentNullException("ProviderName is null or empty!");

      IList results = null;

      DbProviderFactory providerFactory = DbProviderFactories.GetFactory(providerName);
      if (providerFactory == null)
        throw new Exception("Failed to get DbProviderFactory instnce!");

      using (IDbConnection con = providerFactory.CreateConnection())
      {
        con.ConnectionString = connectionString;

        if (con.State != ConnectionState.Open)
          con.Open();

        using (IDbCommand cmd = providerFactory.CreateCommand())
        {
          cmd.CommandText = query;
          cmd.Connection = con;

          using (IDataReader reader = cmd.ExecuteReader())
          {
            results = new List();
            while (reader.Read())
            {
              object[] values = new object[reader.FieldCount];
              int count = reader.GetValues(values);
              results.Add(values);
              values = null;
            }
          }
        }
      }

      return results;
    }
  }
}

NHibernate FAQ: is bathcing supported in MSSQL only?

ado_batchsize is using a feature of ADO.Net which allows to send multiple commands without waiting for the first response to come back. The actual DB shouldn't be aware of that whatsoever.

Why I Hate Frameworks (link)

A very funny analogy about Frameworks. Go read here...

Thursday, July 21, 2011

A bit of linux: recursive creation of directorie

Here follows example:
mkdir -p cpp/google_code_jam/EuroPython2011/A

Wednesday, July 20, 2011

A bit of C++0x Support in GCC

Here is a good link if you want to check what C++0x features are supported in specific GCC version.

A bit of C++ The typeid operator

In C++ typeid operator is used to determine actual derived type of an object at run time. This operator is provided for runtime type identification (RTTI) support in C++.

Here follows an example of typeid operator in action:
#include <typeinfo>
#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::string;
using std::vector;

int main()
{
    string v1 = "";
    cout << "v1: " << typeid(v1).name() << endl;
    vector<int> v2();
    cout << "v2: " << typeid(v2).name() << endl;

    return 0;
}

results:
v1: Ss
v2: FSt6vectorIiSaIiEEvE

std::type_info::name() returns an implementation specific name. As you can see GCC just gives you the internal, mangled name.

In GCC you can use abi::__cxa_demangle() to get nice name.

Here is example
#include <typeinfo>
#include <iostream>
#include <vector>
#include <cxxabi.h>

using std::cout;
using std::endl;
using std::vector;

int main()
{
    vector<int> v2();

    int success;
    char *realname = abi::__cxa_demangle(typeid(v2).name(), 0, 0, &success);
    cout << "v2: " << typeid(v2).name() 
        << " nice name: " << realname << endl;
    free(realname);

    return 0;
}

Results:
v2: FSt6vectorIiSaIiEEvE nice name: std::vector<int, std::allocator<int> > ()()

C++ capitalize each word in string

(Go here for C# implementation)

So here it is: source code for capitalizing first letter of each word in string
#include <iostream>
#include <string>
#include <algorithm>
#include <locale>

using std::string;
using std::locale;
using std::endl;
using std::cout;

int main()
{
    locale loc;

    string text = "How to capitalize the first character of each word?"
        " Other characters should be lower case.";

    cout << text << endl;

    int count = text.size();
    if (count > 0)   
    {
        text[0] = toupper(text[0], loc);
    }

    for(int i = 1; i < count; i++)
    {
        if (isspace(text[i - 1], loc))
            text[i] = toupper(text[i], loc);
        else
            text[i] = tolower(text[i]);
    }

    cout << text << endl;

    return 0;
}

Tuesday, July 19, 2011

Linux 3.0 not ready for today or why do we always find the subtle bugs just before a release?


Read more here...

ILSpy 1.0 Has Landed

ILSpy is the open-source .NET assembly browser and decompiler.

Features
  • Assembly browsing
  • IL Disassembly
  • Decompilation to C# (Supports lambdas and 'yield return', shows XML documentation)
  • Saving of resources
  • Search for types/methods/properties (substring)
  • Hyperlink-based type/method/property navigation
  • Base/Derived types navigation
  • Navigation history
  • BAML to XAML decompiler
  • Save Assembly as C# Project
  • Find usage of field/method
  • Extensible via plugins (MEF)

Monday, July 18, 2011

Google: The Beginning

Read here...

VirtualBox 4.0.12 released!


This is a maintenance release. The following items were fixed and/or added:
  • Mac OS X hosts: Lion fixes
  • Solaris hosts: fixed preemption issue with Solaris 11 hosts (builds 166 and above)
  • VBoxManage: more convenient configuration of storage controller attachments by automatically determining the port or device parameter when a storage controller has only one port or device per port (bug #9188)
  • Storage: fixed possible data corruption under certain circumstances whith VHD and Parallels images (bug #9150)
  • Storage: fixed access to CD/DVD images beyond 4GB when using the SATA controller (bug #8592)
  • Floppy: make it possible to unmount a host floppy disk (bug #6651)
  • Networking: fixed the problem with segmentation offloading when several VMs were transmitting at once
  • 3D support: fixed GL_VERSION string for different locales (bug #8916)
  • Sources: fixed USB 2.0 support using extension packs for non-official builds
  • Solaris Additions: fixed automounting of shared folders (bug #8014)

Maybe C++ hasn’t jumped the shark after all (link)

The new standard is out now, and I find it more interesting that I thought I would have. I’d still rather not use C++ for tasks that are easier in another language I know, but sometimes I don’t have that option.

Read here...

Sunday, July 17, 2011

Debian GNU/Hurd by end of 2012? (link)

According to the most recent progress report from the project, there is now a "real plan" to release a Hurd variant of Debian with the release of Debian 7.0 Wheezy.

Read more here...

Saturday, July 16, 2011

Passion has a funny way of trumping logic

The theory of evolution claims only the strong shall survive. Maybe so, maybe so. But the theory of competition says just because they're the strong, doesn't mean they can't get their asses kicked.

PuTTY version 0.61 is released

Official home site and detailed change log for 0.61 version

Friday, July 15, 2011

BTRFS: The Good, The Bad and The Ugly (link)

Read about BTRFS and performance problems

Libraries vs Frameworks (link)

The word to focus on here is change. As your app grows, you will have to change your mind about what is a good idea, and what doesn't work for you. The first solution that you come up with for a problem is almost never good enough. Limiting your choice to the confines of a framework means limiting your choice in how you can solve a problem. Limiting your choice very often ends up being a bad thing for the software.
read more...

There is no quick way to learn programming (link)

There is no quick way to learn programming - no tool will help.

Your brain is a zillion times better than the best IDE. programs
form in you brain not in an IDE.
...

Have fun - if it's not fun it is pointless - don't fight the tools
all you need is a text editor and the erlang shell to start with.

- Joe Armstrong

Read all text here...

Thursday, July 14, 2011

FTPS also known as FTP over SSL example with C# and libCURL (libcurl.NET)


Background

Two separate methods were developed to invoke client security for use with FTP clients: Explicit or Implicit. The explicit method is a legacy compatible implementation where FTPS aware clients can invoke security with an FTPS aware server without breaking overall FTP functionality with non-FTPS aware clients. The implicit method requires that all clients of the FTPS server be aware that SSL is to be used on the session, and thus is incompatible with non-FTPS-aware clients.

- Wikipedia (link to Wikipedia FTPS article)

Download libcurl.NET

Go to libcurl.NET home page and download library (link to file download).

Create and setup new solution

Your solution should look like this:


Extract and copy libcurl.NET files to your solution libs directory should get something like this:


Add LibCurlNet refernce from libcurl.NET files bin directory to your project.

Copy libcurl.dll, LibCurlShim.dll and ca-bundle.crt files from libcurl.NET files bin directory to your project root directory. Add libcurl.dll, LibCurlShim.dll and ca-bundle.crt files to project tree and set their properties to 'Copy if newer' value.

Add the following source code to your Program.cs file Main method:

Source code

using System;
using System.Collections.Generic;
using SeasideResearch.LibCurlNet;

namespace libcurlFtpsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("libcurlFtpsExample...");

            const string url = "ftp://user:thepassword@ftp.somesite.com/dir/";

            try
            {
                Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);

                Easy easy = new Easy();
                if (easy != null)
                {
                    easy.SetOpt(CURLoption.CURLOPT_URL, url);
                    easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, false);
                    easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, false);
                    easy.SetOpt(CURLoption.CURLOPT_FTP_SSL, CURLftpSSL.CURLFTPSSL_TRY);

                    // For debugging will print headers to console.
                    Easy.HeaderFunction hf = new Easy.HeaderFunction(OnHeaderData);
                    easy.SetOpt(CURLoption.CURLOPT_HEADERFUNCTION, hf);
                    
                    // For debugging will print received data to console.
                    Easy.DebugFunction df = new Easy.DebugFunction(OnDebug);
                    easy.SetOpt(CURLoption.CURLOPT_DEBUGFUNCTION, df);
                    easy.SetOpt(CURLoption.CURLOPT_VERBOSE, true);
     
                    // List directory only
                    easy.SetOpt(CURLoption.CURLOPT_FTPLISTONLY, true);
         
                    CURLcode code = easy.Perform();
                    if (code != CURLcode.CURLE_OK)
                    {
                        Console.WriteLine("Request failed!");
                    }

                    easy.Cleanup();
                }
                else
                {
                    Console.WriteLine("Failed to get Easy libcurl handle!");
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp);
            }
            finally
            {
                Curl.GlobalCleanup();
            }
        }

        public static void OnDebug(CURLINFOTYPE infoType, String msg, Object extraData)
        {
            // print out received data only
            if (infoType == CURLINFOTYPE.CURLINFO_DATA_IN)
                Console.WriteLine(msg);
        }

        public static Int32 OnHeaderData(Byte[] buf, Int32 size, Int32 nmemb, Object extraData)
        {
            Console.Write(System.Text.Encoding.UTF8.GetString(buf));
                return size * nmemb;
        }
    }
}


And here is output from program:


Excercise
What about file download instead of directory listing?

Well comment out line no. 37

easy.SetOpt(CURLoption.CURLOPT_FTPLISTONLY, true);

and replace it with this code:

Easy.WriteFunction wf = new Easy.WriteFunction(OnWriteData);
easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);

and add implementation of OnWriteData static method in 'Program' class like this:

// only prints file context to console
public static Int32 OnWriteData(Byte[] buf, Int32 size, Int32 nmemb, Object extraData)
{
    Console.Write(System.Text.Encoding.UTF8.GetString(buf));
    return size * nmemb;
}

Also add your file at the end of url like this:

const string url = "ftp://user:thepassword@ftp.somesite.com/dir/yourfile.txt";

Done ;)

Wednesday, July 13, 2011

Tuesday, July 12, 2011

Firefox 8 is 20% faster than Firefox 5, matches Chrome 14 (link)

read here...

Quote of The Day - 2011-07-12

There’s a subtle reason that programmers always want to throw away the code and start over. The reason is that they think the old code is a mess. … The reason that they think the old code is a mess is because of a cardinal, fundamental law of programming: It’s harder to read code than to write it.

- Joel Spolsky

Go Rocks - How Can We Avoid Something This Bad In The Future? (link)

An explanation for the ambivalent reactions to the Go language

Saturday, July 9, 2011

Quote of The Day - 2011-07-09

The formulation of a problem is often more essential than its solution, which may be merely a matter of mathematical or experimental skill.

- Albert Einstein

Friday, July 8, 2011

Quote of The Day - 2011-07-08

The basic need, which certainly is obvious only in man, is the need of symbolization. The symbol-making function is one of man’s primary activities, like eating, looking, or moving about. It is the fundamental process of his mind, and goes on all the time.

- Susanne K. Langer

Thursday, July 7, 2011

GeoCoding with C++ and Google Geocoding API V3 (using libCURL and JsonCpp)

Geocoding is the process of finding associated geographic coordinates (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes). (read more in wikipedia)

Today I'll give a short example of C++ application in which we will use the newest version of Google Geocoding API V3. You can compare it with similar C# geocoding example.

When you perform a geocoder request, you can specify which output type to use. The available options are JSON, XML, KML and CSV. We will be requesting and handling JSON data.

For example, if you wanted to find the coordinates of house located at 1600 Amphitheatre Parkway, Mountain View, CA, you would request the following URL: (http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false).

We will use cURL libcurl library for requests.

The response will be processed by using JsonCpp library and coordinates will be printed to console.

OK, here is the code of my geocoder example:
#include <string>
#include <iostream>
#include "json/json.h"
#include "CURLWrapper.h"

static std::string buffer;

static int writer(char *data, size_t size, size_t nmemb, std::string *buffer)
{
    int result = 0;
    if (buffer != NULL)
    {
        buffer->append(data, size * nmemb);
        result = size * nmemb;
    }

    return result;
}

int main()
{
    std::string url = "http://maps.googleapis.com/maps/api/geocode/json?"
   "address=1600+Amphitheatre+Parkway,+Mountain+View,"
   "+CA&sensor=false";

    std::cout << "Will retrive from url: '" << url << "'" << std::endl;

    CURLWrapper::Easy easy;
    easy.SetOption(CURLOPT_URL, url.c_str());
    easy.SetOption(CURLOPT_HEADER, 0);
    easy.SetOption(CURLOPT_FOLLOWLOCATION, 1);
    easy.SetOption(CURLOPT_WRITEFUNCTION, writer);
    easy.SetOption(CURLOPT_WRITEDATA, &buffer);
    easy.Perform();

    if (easy.IsOK())
    {
        std::cout << "CURL: response is OK " << std::endl;
        //std::cout << buffer << std::endl;
 
        if (!buffer.empty())
        {
            Json::Value root;
            Json::Reader reader;
     
            if (reader.parse(buffer, root))
            {
                std::cout << "JSON response is OK!" << std::endl;
  
                const Json::Value status = root["status"];
                std::cout << "JSON response status: '" 
                    << status.asString() << "'" 
                    << std::endl;

                if (status.asString() == "OK")
                {
                    const Json::Value results = root["results"];
      
                    std::cout << "JSON response results.size = " 
                        << results.size() << std::endl;

                    for(unsigned int i = 0; i < results.size(); i++)
                    {
                        const Json::Value geometry = results[i]["geometry"];
   
                        std::cout << "Coordinates: " 
                            << "lat=" << geometry["location"]["lat"].asString()
                            << " "
                            << "lng=" << geometry["location"]["lng"].asString()
                            << std::endl;
                    }
                }
                else
                {
                    std::cout << "JSON response contains no results" 
                        << std::endl;
                }
            }
            else
            {
                std::cout << "JSON response Error: "  
                    << reader.getFormattedErrorMessages() 
                    << std::endl;
            }
        }
        else
        {
            std::cout << "CURL: respose is empty! " << std::endl;
        }
    }
    else
    {
        std::cout << "CURL Error: [ " << easy.GetError() << " ] - " 
            << easy.GetErrorMessage() << std::endl;
    }
}


In order to compile this example you would also need my libcurl wrapper class: CURLWrapper (which is heavily inspired by cURLpp project). Here is the code for it:
"CURLWrapper.h" file
#ifndef CURL_WRAPPER_H
#define CURL_WRAPPER_H

#include <string>
#include "curl/curl.h"

namespace CURLWrapper 
{
    class Easy
    {
    public:
        Easy();
        ~Easy();

        void Init();
        void Cleanup();
        void Reset();

        template <typename T, typename V>
        void SetOption(T option, V parameter)
        {
            curl_easy_setopt(mCurl, option, parameter);
        }

        void Perform();
        bool IsOK();
        CURLcode GetError();
        std::string GetErrorMessage();
    
    private:
        void ErrorBuffer(char* buffer); 
    
    private:
        CURL* mCurl;
        char mErrorBuffer[CURL_ERROR_SIZE + 1];
        CURLcode mCode;
    };

}

#endif //#ifndef CURL_WRAPPER_H


"CURLWrapper.cpp" file
#include <memory>
#include <algorithm>
#include "CURLWrapper.h"
#include "curl/curl.h"

CURLWrapper::Easy::Easy()
    : mCurl(curl_easy_init()),
    mCode(CURLE_OK)
{
}

CURLWrapper::Easy::~Easy()
{
    curl_easy_cleanup(mCurl);
}

void CURLWrapper::Easy::Init()
{
}

void CURLWrapper::Easy::Cleanup()
{
    curl_easy_cleanup(mCurl);
}

void CURLWrapper::Easy::Reset()
{
    curl_easy_reset(mCurl);
    std::fill(mErrorBuffer, mErrorBuffer + CURL_ERROR_SIZE + 1, 0);
    ErrorBuffer(mErrorBuffer);
    mCode = CURLE_OK;
}

void CURLWrapper::Easy::ErrorBuffer(char* buffer)
{
    SetOption(CURLOPT_ERRORBUFFER, (void*)buffer);
}

void CURLWrapper::Easy::Perform()
{
    mCode = curl_easy_perform(mCurl);
}

bool CURLWrapper::Easy::IsOK()
{
    return mCode == CURLE_OK;
}

CURLcode CURLWrapper::Easy::GetError()
{
    return mCode;
}

std::string CURLWrapper::Easy::GetErrorMessage()
{
    return std::string(mErrorBuffer);
}


You can compile example like this:
g++ -g -Wall -Ilibs/include -Llibs/lib -o prog prog.cpp CURLWrapper.cpp -lcurl -ljson_linux-gcc-4.5.2_libmt

And here is result screenshot:

Quote of The Day - 2011-07-07

Man can be destroyed, but not defeated.

- Ernest Hemingway

Tuesday, July 5, 2011

Friday, June 24, 2011

Returning a reference to a local/temprorary object without causing a memory leak?(link)

How can it be? Isn't the memory of a local variable inaccessible outside its function?

Read here...

Thursday, June 23, 2011

A bit of C++0x new raw and unicode string literals

C++x0 introduced new string literals: starting with 'u8', 'u', 'U' and 'R'.
'u8' is for utf-8
'u' is for utf-16
'U' is for utf-32
'R' is for raw strings
(Also you can combine those: u8R, uR and UR
#include 
#include 

int main()
{
    std::string old = "c:\\test\\test";
    std::string raw = R"(c:\test\test)";
    std::string utf8 = u8"This is a Unicode Character: \u0160."; 

    std::cout << "old literal: " << old << std::endl;
    std::cout << "new raw literal: " << raw << std::endl;
    std::cout << "new utf-8 literal: " << utf8 << std::endl;

    return 0;
}
Output:
old literal: c:\test\test
new raw literal: c:\test\test
new utf-8 literal: This is a Unicode Character: Š.
Read more here...

Wednesday, June 22, 2011

Performance is a Feature (link)

Read on Coding horror

A bit of C++0x auto keyword

Other cool shortcut in c++x0 is auto keyword it is wrist saver, but don't abuse it. If abused auto could make code unreadable like c# var.

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec = { 10, 20, 30, 40 };

    // Compare with pre c++x0 version
    //for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
    for(auto it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << std::endl;
    }

    return 0;
}

Tuesday, June 21, 2011

A bit of C++0x std::thread get recommended number of threads for your system

In c++x0 we have this cool function that will tell you recommended number of concurrent threads for your system:

#include <thread>
#include <iostream>

int main()
{
    std::cout << "Recommended number of concurrent threads for your system (hint): "                      
        << std::thread::hardware_concurrency()
        << std::endl;

    return 0;
}

Unfortunately it returns zero for my home computer :)

P.S. Here is more info about std::thread...

Monday, June 20, 2011

Examples of using libcurl from C++ (links)

1. Using libcurl from C++
2. Download file using libcurl in C/C++ (StackOverflow)
3. Simplify Network Programming with libCURL
4. Using LIBCurl with C++ Simple OOP Static Class Example

A bit of C++0x lambda and vector of user defined type sorting

Here is a short example how to using lambdas for sorting vector of user defined types.

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

class Person
{
public:
  Person();
  Person(int a, std::string n);
  Person(const Person& src);

  int age;
  std::string name;
};

Person::Person()
: age(0)
, name("")
{};

Person::Person(int a, std::string n)
: age(a)
, name(n)
{};

Person::Person(const Person& src) 
{ 
  age = src.age; 
  name = src.name; 
}; 
 
int main() 
{ 
    std::vector<Person> a = 
    {
        Person(10, "Person1"), 
        Person(12, "Person2"), 
        Person(12, "Person3") 
    }; 
     
    std::cout << "Before revers sort" << std::endl; 
    std::for_each(a.begin(), a.end(),  
        [](const Person& p) 
        { 
            std::cout << " Person age: " << p.age << " name: " << p.name << std::endl; 
        }); 
 
    std::sort(a.begin(), a.end(),  
        [](const Person& p1, const Person& p2) 
        { 
            if (p1.age > p2.age) return true; 
            if (p1.name.compare(p2.name) > 0) return true; 
            return false; 
        }); 
 
    std::cout << "After revers sort" << std::endl; 
    std::for_each(a.begin(), a.end(),  
        [](const Person& p) 
        { 
            std::cout << " Person age: " << p.age << " name: " << p.name << std::endl; 
        }); 
}  

Friday, June 17, 2011

A bit of C++0x lambda and vector sort (reverse sort)

Here is example how to sort vector by using lambdas (You can compare it with old post where used std::greater() for this, in my opinion lambdas are cleaner).

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    std::vector<int> a = { 10, 90, 50, 20, 30, 5 };
    std::vector<int> b = { 10, 90, 50, 20, 30, 5 };

    std::sort(a.begin(), a.end(),
        [](const int& a, const int& b)
        {
            return a < b;
        });

    std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;

    std::sort(b.begin(), b.end(),
        [](const int& a, const int& b)
        {
            return a > b;
        });

    std::copy(b.begin(), b.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}

SleepSort implementation with c++0x std::thread

Here it is the Sleep Sort

#include <thread>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

void sleep_sort(int n)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(n));
    std::cout << n << " ";
}

int main()
{
    std::vector<int> a = {1500, 200, 100, 300, 400, 300};

    std::vector<std::thread> threads;
    for(std::vector<int>::iterator it = a.begin(); it != a.end(); it++)
    {
        threads.push_back(std::thread(sleep_sort, *it));
    }

    std::for_each(threads.begin(), threads.end(),
        std::mem_fn(&std::thread::join));

    std::cout << std::endl;

    return 0;
}

Thursday, June 16, 2011

A bit of C++0x std::thread and passing parameters

One small bit from C++0x I want to share with you today is:

you can't use std::thread constructor to pass parameters by reference, all parameters will be passed by value!

Here is a source to demonstrate this:
#include 
#include 

void inc(int& number)
{
    std::cout << "In thread before increment: " << number << std::endl;

    number = number + 1;

    std::cout << "In thread after increment: " << number << std::endl;
}

int main()
{
    int n = 10;

    std::cout << "Before inc: " << n << std::endl;

    std::thread worker(inc, n);
    worker.join();

    std::cout << "After inc: " << n << std::endl;

    return 0;
}
Small note about compiling: I use GNU Compiler Collection (GCC) version 4.5 on Linux (mingw port don't support std::thread yet).
g++ -std=c++0x -lpthread test.cpp -o test
./test
And here is output:
Before inc: 10
In thread before increment: 10
In thread after increment: 11
After inc: 10
UPDATED!!! solution is simple: use the std::ref, Luke!
#include 
#include 

void inc(int& number)
{
    std::cout << "In thread before increment: " << number << std::endl;

    number = number + 1;

    std::cout << "In thread after increment: " << number << std::endl;
}

int main()
{
    int n = 10;

    std::cout << "Before inc: " << n << std::endl;

    std::thread worker(inc, std::ref(n));
    worker.join();

    std::cout << "After inc: " << n << std::endl;

    return 0;
}
and the output is:
Before inc: 10
In thread before increment: 10
In thread after increment: 11
After inc: 11

Wednesday, June 15, 2011

Monday, June 13, 2011

Facebook Make Me Sad (link)

read here...

Quote of The Day - 2011-06-13

Watch your thoughts, for they become words.
Watch your words, for they become actions.
Watch your actions, for they become habits.
Watch your habits, for they become your character.
Watch your character, for it becomes your destiny.

read here...

Tuesday, June 7, 2011

C# capitalize each word in string

One day I stumbled on this problem in my work so I have done some thinking and searched for simple solution. I have collected all implementation I could find created benchmark and measured performance.

Let take look at source code
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

namespace ToTitleCase
{
 class MainClass
 {
  const string test = "How to capitalize the first character of each word? Other characters should be lower case.";
  const int N = 100000;
  
  public static string BadToTitleCase (string str)
  {
   StringBuilder result = new StringBuilder ();
   str = str.ToLower ();
   string [] names = str.Split (' ');

   for (int name_index = 0; name_index < names.Length; name_index++) {
    int i = 0;
    while (char.IsWhiteSpace(names[name_index][i]) && i < names[name_index].Length) {
     i++;
    }
    StringBuilder sb = new StringBuilder (names [name_index]);
    sb [i] = names [name_index].ToUpper () [i];
    result.Append (sb.ToString ());
    if (name_index < names.Length - 1)
     result.Append (" ");
   }
   return result.ToString ();
  }
  
  public static String BadToTitleCase2 (string str)
  {
   String[] split;

   split = str.Split (' ');
   str = String.Empty;
   foreach (String part in split) {
    Char[] chars;

    chars = part.ToCharArray ();
    if (chars.Length > 0) {
     chars [0] = ((new String (chars [0], 1)).ToUpper ().ToCharArray ()) [0];
    }
    str += new string (chars) + ' ';
   }
   str = str.Substring (0, str.Length - 1);
   return (str);
  }

  public static string SimpleToTitleCase (string str)
  {
   string result = null;
         
   if (!string.IsNullOrEmpty (str)) {
    string[] words = str.Split (' ');
    for (int i = 0; i < words.Length; i++) {
     var s = words [i];
     if (s.Length > 0) {
      words [i] = s [0].ToString ().ToUpper () + s.Substring (1);
     }     
    }
    result = string.Join (" ", words);
   }
   
   return result;
  }

  public static string NetToTitleCase (string str)
  {
   return CultureInfo.CurrentCulture.TextInfo.ToTitleCase (str.ToLower ());
  }
  
  public static string BufferToTitleCase (string str)
  {
   char[] array = str.ToCharArray ();

   int count = array.Length;
   if (count > 0)
    array [0] = char.ToUpper (array [0]);

   for (int i = 1; i < count; i++) {
    if (char.IsWhiteSpace (array [i - 1]))
     array [i] = char.ToUpper (array [i]);
    else
     array [i] = char.ToLower (array [i]);
   }

   return new string (array);
  }
  
  public static string StringBuilderToTitleCase (string str)
  {
   if (str == null)
    throw new ArgumentNullException ("value");   
   
   if (str.Length == 0)
    return str;
   
   StringBuilder sb = new StringBuilder (str.Length);
   // Upper the first char.
   sb.Append (char.ToUpper (str [0]));
   for (int i = 1; i < str.Length; i++) {
    // Get the current char.
    char c = str [i];
    
    // Upper if after a space.
    if (char.IsWhiteSpace (str [i - 1]))
     c = char.ToUpper (c);
    else
     c = char.ToLower (c);
    
    sb.Append (c);
   }
   
   return sb.ToString ();
  }
  
  public static string StringBuilderToTitleCase2 (string str)
  {
   if (str == null)
    throw new ArgumentNullException ("value");
  
   if (str.Length == 0)
    return str;
  
   StringBuilder result = new StringBuilder (str);
   result [0] = char.ToUpper (result [0]);
   for (int i = 1; i < result.Length; ++i) {
    if (char.IsWhiteSpace (result [i - 1]))
     result [i] = char.ToUpper (result [i]);
    else
     result [i] = char.ToLower (result [i]);
   }
   return result.ToString ();
  }
  
  static string CapitalizeString (Match str)
  {
   string strTemp = str.ToString ();
   strTemp = char.ToUpper (strTemp [0]) + strTemp.Substring (1, strTemp.Length - 1).ToLower ();
   return strTemp;
  }
  
  public static string RegexToTitleCase (string str)
  {
   return Regex.Replace (str, @"\w+", new MatchEvaluator (CapitalizeString));
  }
  
  public static void Main (string[] args)
  {
   Stopwatch watch = new Stopwatch ();
   watch.Start ();
   
   long tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = BufferToTitleCase (test);
   }
   Console.WriteLine ("BufferToTitleCase time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = BadToTitleCase (test);
   }
   Console.WriteLine ("BadToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = BadToTitleCase2 (test);
   }
   Console.WriteLine ("BadToTitleCase2 Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = NetToTitleCase (test);
   }
   Console.WriteLine ("NetToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = StringBuilderToTitleCase (test);
   }
   Console.WriteLine ("StringBuilderToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));

   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = StringBuilderToTitleCase2 (test);
   }
   Console.WriteLine ("StringBuilderToTitleCase2 Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = SimpleToTitleCase (test);
   }
   Console.WriteLine ("SimpleToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = RegexToTitleCase (test);
   }
   Console.WriteLine ("RegexToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   watch.Stop ();
   watch = null;
   
   Console.WriteLine ("Done. Press any key...");
   Console.ReadLine ();
  }
 }
}
Benchmark results
My Conclusions
  • RegexToTitleCase: for such simple text processing task regular expressions is overkill also it is clear that calling delegate function negatively effects performance;
  • BadToTitleCase and BadToTitleCase2: those implementation allocates new temporary objects for string processing and the source code is not elegant;
  • SimpleToTitleCase: wisely used string.Join no need to allocate new temporary objects for string processing this improves performance;
  • NetToTitleCase: uses CultureInfo.CurrentCulture.TextInfo.ToTitleCase which is native implementation so no comments here;
  • BufferToTitleCase: is my favorite because of simplicity of code and performance (avoids allocation of new temporary objects for string processing by using string.ToCharArray method).


P.S. If you have some better or worse implementations, please contact me, I would be very interesting to include those in my benchmark.

Quote of The Day - 2011-06-07

Google's plan, for example, was simply to create a search site that didn't suck. They had three new ideas: index more of the Web, use links to rank search results, and have clean, simple web pages with unintrusive keyword-based ads. Above all, they were determined to make a site that was good to use. No doubt there are great technical tricks within Google, but the overall plan was straightforward.

- Paul Graham

A brief Sony password analysis (link)

We know passwords are too short, too simple, too predictable and too much like the other ones the individual has created in other locations. Read here...

Friday, June 3, 2011

Wednesday, May 25, 2011

Example of project structure for Go (on windows)

Hi,
I am learning Go language. I decided to share my experience in doing so on windows.

In previous post I described in short how you could install and setup Go compiler.

In this post I'll try to show my typical setup for new Go project. This will cover things like package, testing, Makefile and batch script I use. I will use BizzFuzz example.

Here goes the problem definition:
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz.” For numbers which are multiples of both three and five print “FizzBuzz.”


1. "pkg" directory is for source and test files of your package
2. "buid.bat" is batch script for building and testing
3. "main.go" is source file for trying your package in interactive mode


Now in our example in "pkg" directory we have the following stuff:
1. "fizzbuzz.go" is source file of package
2. "fizzbuzz_test.go" test file of package
3. "Makefile" instruction for make program how to build our project.

Now we will dive into each source code.

"fizzbuzz.go"
package fizzbuzz

import (
 "strconv" 
)

func SwitchImp(i int) string {
 switch i % 15 {
  case 3, 6, 9, 12: return "Fizz"
  case 5, 10: return "Buzz"
  case 0: return "FizzBuzz"
  default:
 }

 return strconv.Itoa(i)
}

"fizzbuzz_test.go"
package fizzbuzz

import (
 "testing"
)

type fizzbuzzTest struct {
 in int
 out string
}

var fizzbuzzTests = []fizzbuzzTest {
 fizzbuzzTest{1, "1"},
 fizzbuzzTest{3, "Fizz"},
 fizzbuzzTest{5, "Buzz"},
 fizzbuzzTest{15, "FizzBuzz"},
}

func TestFizzBuzz(t *testing.T) {
 for _, dt := range fizzbuzzTests {
  v := SwitchImp(dt.in)
  if v != dt.out {
   t.Errorf("SwitchImp(%d) = %s, want %s.", dt.in, v, dt.out)
  }
 }
}

"Makefile"
include $(GOROOT)/src/Make.inc

TARG=fizzbuzz

GOFILES=\
 fizzbuzz.go\

include $(GOROOT)/src/Make.pkg

"main.go"
package main

import (
 "fmt"
 "fizzbuzz"
)

func main(){
 fmt.Println("test...")

 for i := 1; i <= 100; i++ {
  fmt.Printf("%d => %s", i, fizzbuzz.SwitchImp(i))
  fmt.Println()
 }

 fmt.Println("done!")
}

"buid.bat"
@echo off

echo CLEAN
cd pkg
sh gomake clean
cd ..
del main.exe
del main.8

echo MAKE package & test
cd pkg
gotest
cd ..

echo MAKE pckage install
cd pkg
sh gomake install
cd ..

echo BUILD MAIN
8g -o main.8 main.go
8l -o main.exe main.8

Now then everything is set and done open your console (cmd.exe) and go to project directory. Execute build.bat and then main.exe.


P.S.
I would love to here from you if you have the similar setup or something complete different.

As I mentioned earlier I am learning Go language so I may done some errors, so let me know if made mistake.

Thanks and see you next time ;)