June 27, 2013

On template-like methods in PHP

Ok so, here is an interesting post about PHP! I am currently building a website with a famous framework in PHP, and I noticed that the CRUD methods (create/read/update/delete) for the models looked a lot alike between all my models. No surprise here.

However, it wasn't that easy to make it generic -- meaning that the field names and table names still change every time, and passing an array of field names at every call didn't seem that elegant... That plus the fact that I wanted these methods to be called from the public interface of my models. What to do?

I figured out a little trick I really like, and that I'm going to share with you today. This trick probably has a design pattern named after it, and it's a little twisted so hang on! For those who don't have time to read, here is the beast:


<?php

// Our base class
class A
{
 const _foo = 'foo_A';
 protected static $_bar = array( 'bar_A' );

 // Define static accessors using 'get_called_class'
 public static function foo()
  {
   $c = get_called_class();
   return $c::_foo;
  }
 public static function &bar()
  {
   $c = get_called_class();
   return $c::$_bar;
  }

 // Define methods using 'inherited' statics/constants
 public function print_foo()
  {
   echo self::foo() . PHP_EOL;
  }
 public function print_bar()
  {
   print_r(self::bar());
   echo PHP_EOL;
  }
}

// Let's make some magic
class B extends A
{
 const _foo = 'foo_B';
 protected static $_bar = array( 'bar_B' );
}

// Try it out!
$a = new A();
$b = new B();

$a->print_foo(); // foo_A
$a->print_bar(); // bar_A

$b->print_foo(); // foo_B
$b->print_bar(); // bar_B :)

You can see here that I'm defining "static accessors" to some constants/static variables defined in my base class. These constants/statics are not only overridden by children, but are also bound to them; that's why I use the get_called_class in these accessors. Now all there is to do is to write some methods using these accessors instead of instance properties. Override these constants/statics in children classes, and VoilĂ ! You get template-like methods in PHP that fit any situation where methods should be "parameterized" in addition to receiving public inputs :)

June 05, 2013

Prevent Screen from Turning Off While Playing Videos on Linux

If you're using Ubuntu with Gnome/Unity and your screen turns off (screensaver) while watching videos in your browser (YouTube or others), this might solve your problem.

#!/bin/bash -eu

# List your browsers here
browsers_list=( "firefox" "chrome" "chromium" "opera" )

# Cleanup bad state left behind if user exited while flash was running
gconftool-2 -s /apps/gnome-screensaver/idle_activation_enabled \
    --type bool true

idle_off=0

while true; do

    sleep 60

    for browser in "${browsers_list[@]}" ; do
    for pid in `pgrep $browser` ; do

        flash_on=0
        if [ -O /proc/$pid/maps ] && \
            grep libflashplayer /proc/$pid/maps > /dev/null ; then
            flash_on=1
        fi

        ss_on=`gconftool-2 -g /apps/gnome-screensaver/idle_activation_enabled`

        if [ "$flash_on" = "1" ] && [ "$ss_on" = "true" ]; then
            gconftool-2 -s /apps/gnome-screensaver/idle_activation_enabled \
                --type bool false
            idle_off=1
        elif [ "$flash_on" = "0" ] && [ "$ss_on" = "false" ] \
                && [ "$idle_off" = "1" ]; then
            gconftool-2 -s /apps/gnome-screensaver/idle_activation_enabled \
                --type bool true
            idle_off=0
        fi

    done
    done

done

Save this script somewhere, chmod +x it, and add it to the Startup Applications so it runs when you log in. Don't forget to add your browsers in the first array!

May 19, 2013

Fraction patterns like 987654321 / 123456789

I came across this funny problem and I wanted to share a very nice solution to explain the behavior of such fractions in any numerical basis (the fraction in the title is in base 10, obviously :). So here it is; beginning with the following definition: \[ S_n(a) = 1 + 2a + ... + na^{n-1} = \sum_{k=1}^n k a^{k-1} = \frac{ n a^{n+1} - (n+1) a^n + 1 }{ (a-1)^2 } \] Given this, it's easy to see that \[ \frac{ [\ (b-1), (b-2), ...\ , 1\ ]_b }{ [\ 1, 2, ...\ , (b-1)\ ]_b } = \frac{ S_{b-1}(b) }{ b^{b-2} S_{b-1}(1/b) } = \frac{ 1 + (b-2)\ b^b }{ b^b - b(b-1) -1 } \] In particular, the fraction in the title equals (with $b=10$): \[ \frac{ 1 + 8.10^{10} }{ 10^{10} - 91 } \approx \frac{ 1 + 8.10^{10} }{ 10^{10} } \approx 8 \]

April 30, 2013

Siglot: a concise C++ STL implementation of Signals and Slots

I just finished a small project on Github, it's called Siglot. I started this little project to prove that Signals and Slots could be implemented easily and efficiently in C++ without calling heavy libraries like Qt, Boost or complicated headers like FastDelegates. I think I reached a satisfactory result with a clean 300-lines header (with comments), which includes only one STL header. I hope you'll find it useful!

If you try any benchmarking, I would be really interested to see the results! I'm also not sure if this is thread-safe and would be extremely grateful for any insight in this regard. In any case, send me a short message if you liked it ;)

April 15, 2013

Listing all Permutations: The Recursive Way

Here is a general algorithm for listing all permutations of an array recursively. The code is given in C++, but can easily be ported to any language:

#ifndef __PERMUTE__
#define __PERMUTE__

template <class T>
void swap( T *a, T *b )
{
    T c = *a;
    *a  = *b;
    *b  = c;
}

template <class T>
void permute( T *array, const unsigned& size, unsigned current )
{
    if ( current == size-1 )
    {
        // Do what you want with the current permutation
    }
    else
    {
        for ( unsigned i = current; i < size; ++i )
        {
            swap( array+current, array+i );
            permute( array, size, current+1 );
            swap( array+current, array+i );
        }
    }
}

#endif

April 14, 2013

Pseudo-Random Numbers Generation with C++11

A short post on how to generate random variables with the new header "random" in the STL. I provide a header file that is useful to me whenever I use this new feature; maybe you'll find it useful too. Here is a usage example (assuming you put the header in the same directory):


#include "random_engine.h"
#include <iostream>

using namespace std;

int main()
{
      std::uniform_int_distribution<unsigned> U(1, 15);
      auto generator = RandomEngine::bind_to(U);

      cout << generator() << endl;
      cout << generator() << endl;
      cout << generator() << endl;
      cout << generator() << endl; 

      cout << "------------" << endl; 

      cout << U( *RandomEngine::get() ) << endl;
      cout << U( *RandomEngine::get() ) << endl;
      cout << U( *RandomEngine::get() ) << endl;
      cout << U( *RandomEngine::get() ) << endl;
}

April 13, 2013

Rank Values in C++: Enhancing std::sort

I'm providing a header file that defines two functions for ranking values stored either in an iterable container or simply in a plain array. If you want to rank N values, make sure your "rank" array is of size N too! The trick is merely to exploit the third input of std::sort :)