>> Single Point of Failure >>


Recent Entries



Popular Tags

Art Blog Blogging Book Books C++ C/C++ Calvin Cartoon Complaints Daughter Definition Development Event Experiment Family Favorites Firefox Focus Fun Google Humor Introspection Life Linux Movie Movies Music Organization Photo Photography Programming Python Reading Software Tips Tools Travel TV Ubuntu Vacations Video Water White Work

I know the feeling…

Ξ March 23rd, 2014 | → 0 Comments |
Programming |, , , |


@xkcd

 


string_buffer utility class

Ξ August 25th, 2013 | → 0 Comments |
Programming |, , , , , |


Here is a small utility class, that allows you to create a string buffer in C++. The implementation uses a variadic template construtor to facilitate the initialization of the buffer.

#ifndef IRIS_STRING_BUFFER_HPP__
#define IRIS_STRING_BUFFER_HPP__

#include <string>
#include <sstream>

namespace iris
{

class string_buffer
{
private:
        typedef std::ostringstream buffer_t;

public:
        string_buffer() {};

        template<typename... Ts>
        string_buffer(const Ts& ...values)
        {
                fill(buffer_, values...);
        } 

        std::string str() const
        {
                return buffer_.str();
        }

private:
        void fill(buffer_t& buffer)
        {}

        template<typename T, typename... Ts>
        void fill(buffer_t& buffer, const T& value, Ts& ...values)
        {
                buffer << value;
                fill(buffer, values...);
        } 

private:

        buffer_t buffer_;
};

} // namespace iris

#endif // IRIS_STRING_BUFFER_HPP__

 

Using the above, you can easily “compose” a message to pass to a logger or a throwing exception.

int main(void)
{
  std::cout
    << iris::string_buffer("Message ", 42, ". Hello, World!").str()
    << std::endl;

  return 0;
}

 


Sound of Sorting

Ξ August 4th, 2013 | → 0 Comments |
Fun, Programming |, , , |


Found while randomly surfing the Internet. More information here.

 


Range

Ξ June 15th, 2013 | → 0 Comments |
Programming |, , , |


The following is the result of some basic experiments with the definition of a range for range-based for loops in C++.

#include <vector>
#include <iostream>

namespace abyss {

  template <typename ITERATOR>
  struct range
  {
    public:

    range(ITERATOR begin, ITERATOR end):
      begin_(begin),
      end_(end)
    {}

    ITERATOR begin() const { return begin_; }
    ITERATOR end() const { return end_; }

    private:

    ITERATOR begin_;
    ITERATOR end_;
  };

  template <typename CONTAINER>
  range<typename CONTAINER::iterator> make_range(CONTAINER& c)
  {
    return range<typename CONTAINER::iterator>(c.begin(), c.end());
  }

  template <typename CONTAINER>
  range<typename CONTAINER::const_iterator> make_range(const CONTAINER& c)
  {
    return range<typename CONTAINER::const_iterator>(c.begin(), c.end());
  }

  template <typename ITERATOR>
  range<ITERATOR> make_range(ITERATOR begin, ITERATOR end)
  {
    return range<ITERATOR>(begin, end);
  }
}

Using the above, you can easily iterate over part of a collection, as can be seen in the following example. The non-class member functions make_range allow the creation of the range without having knowledge of the underlying iterator type — template argument deduction makes all the work for you under the hood.

int main(void)
{
  typedef std::vector<int> container_t;

  const container_t v { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

  // 1. Defining a range over the entire collection... same as for( auto x : v )
  for( auto x : abyss::make_range(v) )
  {
    std::cout << x << " ";
  }
  std::cout << std::endl;

  // 2. Defining a range over the entire collection... same as for( auto x : v )
  //    ...using begin and end iterators
  for( auto x : abyss::make_range(v.begin(), v.end()) )
  {
    std::cout << x << " ";
  }
  std::cout << std::endl;

  // 3. Defining a range from 'a' to 'b'... same as for( auto x : v )
  auto a = v.cbegin();
  std::advance(a, 3);
  auto b = v.cbegin();
  std::advance(b, 8);

  for( auto x : abyss::make_range(a, b) )
  {
    std::cout << x << " ";
  }
  std::cout << std::endl;

  return 0;
}

I enjoy understanding how this stuff works and is implemented, even if a very robust implementation already exists (see iterator_range in Boost Range library). Experimenting allows me to think, investigate and sometimes find very interesting readings (for example, “On Iteration” by Andrei Alexandrescu, is a very interesting article).

 


Snippets…

Ξ March 3rd, 2013 | → 0 Comments |
Programming |, , , , |


Ever had a programming argument at the water cooler, one that couldn’t be solved without some coding to check what’s what? Or did you ever reached some dark corner of your favorite language that needed to be quickly enlightened by a few lines of code?

Most of the times, solving those technical difficulties would require an “environment” with an editor, with the right compiler and a sandbox for my experiments.

That is no longer the case since I discovered the help I could get from the several available online compilers. My favorite is the one provided by Live Work Space, that provides support for C, C++, Python, Ruby, D, Go, Fortran, and more… with several compilers for most of the supported languages.

There are others that also provide interesting features, such as Ideone. And if you need a more elaborate setup, Compilr provides the full development environment.

[edit on 2013-09-30]

gcc.godbolt.org is another excellent alternative when the above mentioned systems are offline.

 


How to check for endianess?

Ξ March 11th, 2012 | → 0 Comments |
Programming |, |


bool platform_is_big_endian()
{
   long one = 1;
   return !(*((char *)(&one)));
}

So, what’s going on?

A long takes more that 1 byte (usually 4 bytes).
In big-endian 1 is represented by {0×00, 0×00, 0×00, 0×01}, which is reversed for little-endian {0×01, 0×00, 0×00, 0×00}. The code above takes the address of the most significant byte of the long, and depending on the value of that byte returns true if big-endian, false if little endian.

 


Map

Ξ January 28th, 2012 | → 0 Comments |
Programming |, , |


 


Going Concurrent

Ξ December 23rd, 2011 | → 0 Comments |
Programming |, , , , |


I had to implement a progress bar for a GUI application, and in order to keep the application “live” my focus during last couple of weeks shifted to multi-threaded concurrent programming. The solution was simple and it basically implied implementing a background thread to update the progress bar while filling a data structure by reading a file. It was simple enough to be implemented in a couple of days, but it became clear that some of the topics related to concurrent programing just weren’t as consolidated I would like.

Since the I’ve been skimming over some interesting articles on the subject. Also began to read “Concurrent Programming in Java, 2nd Edition” by Doug Lea and “The Art of Concurrency” by Clay Breshears .

The following is my attempt to solve the brain-number problem (addressed initially by Ari Sundaram).

#include <cmath>
#include <iostream>
#include <limits>
#include <cassert>

#include "omp.h"

/* ***
 * Count the digits in the number 
 * ***/
int count_digits(int number)
{
	return log10(static_cast<double>(number)) + 1;
}

/* ***
 * Calculate the brain-value of the number
 * 
 * The brain-value is the sum of each digit in number to the power of the
 * number of digits.
 * BV(d1d2d3...dn) = d1^n + d2^n + d2^n + ...  + dn^n,
 *                                              where dn is the nth digit
 * ***/
int
brain_value(int number)
{
	int sum = 0;
	int digits = count_digits(number);
	
	while(number > 0)
	{
		sum += ::pow(number % 10, digits);
		number = number / 10;
	}

	return sum;
}

/* ***
 * Checks if number is a brain-number
 * 
 * A number is a brain-number when it's brain-value equals the number itself
 * ***/
bool
is_brain_number(int number)
{
	return brain_value(number) == number;
}

/* ***
 * Prints the brain-numbers in the lower/upper range
 *                                 (Serial Version)
 * ***/
void
print_brain_numbers_in_range(int lower, int upper)
{
	assert(lower >= 0);
	assert(lower <= upper);
	
	for(int i = lower; i <=upper; i++)
		if(is_brain_number(i))
			std::cout << i << std::endl;
}

/* ***
 * Prints the brain-numbers in the lower/upper range
 *                                 (Parallel Version, using OpenMP)
 * ***/
void
print_brain_numbers_in_range_parallel(int lower, int upper)
{
	assert(lower >= 0);
	assert(lower <= upper);

	#pragma omp parallel
	{
		#pragma omp for
		for(int i = lower; i <=upper; i++)
			if(is_brain_number(i))
				#pragma omp critical
				{
					// Critical section ensures correct output
					std::cout << i << std::endl;
				}
	}
}

/* ***
 * Helper function to test the 
 * ***/
template<typename Printer>
void execute_print_brain_numbers(Printer& printer, int lower, int upper) {
	
	std::cout << "The brain numbers between "
	          << lower << " and " << upper << " are:" << std::endl;
	double start = omp_get_wtime();
	printer(lower, upper);
	double end = omp_get_wtime();
	std::cout << "Listed in " << (end - start) << " seconds" << std::endl;
}

int main(void)
{
	execute_print_brain_numbers(
		print_brain_numbers_in_range,
			0,
			std::numeric_limits<int>::max() / 100);

	execute_print_brain_numbers(
		print_brain_numbers_in_range_parallel,
			0,
			std::numeric_limits<int>::max() / 100);

	return 0;
}

 


Just had a nice time with volatile!

Ξ December 17th, 2011 | → 0 Comments |
Programming |, , , |


I’ve never had the chance (or in fact the need) to investigate the use of the volatile keyword in C/C++. Today I found some very interesting articles about the subject.

 - Andrei Alexandrescu’s article “volatile: The Multithreaded Programmer’s Best Friend” at Dr. Doobs’s.
Explains that using volatile prevents compiler optimizations that might render code incorrect in the presence of certain asynchronous events. And presents a technical discussion on how to use the volatile qualifier to create critical sections and avoid race conditions.

 - Arch Robison’s “Volatile: Almost Useless for Multi-Threaded Programming” at Intel Software Blogs.
Provides an example where volatile does not work, and defends that volatile does not provide a sound base to create correct multi-threaded programs. The discussion that follows is very interesting, spawning comments for several years, and including several very interesting references to how the C++ communities discussed/evolved volatile understanding.

 - Nigel Jones’ “Introduction to the Volatile Keyword” (here) and San Saks’ “Use voatile Judiciosly” (here).
Show interesting examples of what is and how to use the
volatile qualifier, providing examples of use in the scope of embedded systems development.

         


        Once virtual, always virtual…

        Ξ October 23rd, 2011 | → 0 Comments |
        Programming |, , , |


        What will be the output of the code below?

        #include <iostream>
        #include <memory>
        
        using namespace std;
        
        namespace abyss {
        
        class A {
        public:
          virtual ~A() {}
          virtual void f() { cout << "A::f" << endl; } // base is virtual
        };
        
        class B: public A {
        public:
          virtual ~B() {}
          void f() { cout << "B::f" << endl; } // this is also virtual
        };
        
        class C: public B {
        public:
          virtual ~C() {}
          void f() { cout << "C::f" << endl; } // continues to be virtual
        };
        
        }
        
        int main() {
          auto_ptr<abyss::A> base(new abyss::C);
          base->f();
           // method called using pointer to base gets dispatched to C::F
        
          return 0;
        }
        

        Take notice of the “once virtual always virtual” rule that states that once a method is qualified as virtual there is no way to turn off the dispatching mechanism provided by the language for virtual functions. Unlike Java, C++ does not have the notion of final (which interrupts the dispatching). This means that, even though neither B or C classes qualify f() as virtual, the call to base->f() shall be dispatched as if it was.

        I like to follow the convention to place an explicit virtual qualifier to make clear the expected behaviour. It would be nice to have some kind of warning from the compiler, but no issue is raised (at least when using g++ 4.5.1).

         


        On the nightstand...


        «« Previous Entries