Monday, November 25, 2013

PHP - Data structures - Tree - Chained processing units


<?php

/**
 * Chained processing units (tree structure)
 * @author Ionut Bodea
 */


/*
 * Tree Nodes (adiacent list)
 */
$aNodes = array(
    1 => array(2, 3),
    3 => array(4, 5, 6),
    5 => array(7, 8)
);


$oTree = new Core_DataStructure_Tree($aNodes);

echo 'Tree (recursive, multi level array):';
print_r($oTree->getTree());

echo 'Tree (horizontal representation):';
print_r($oTree->getTreeHorizontal());


class Core_DataStructure_Tree
{
    private $adiacentList;
    private $tree   = array();
    ## private $isTree = false;

    public function __construct($adiacentList)
    {
        $this->adiacentList = $adiacentList;
        $this->computeTree();
    }

    private function computeTree()
    {
        $this->tree = array();
        foreach($this->adiacentList as $sParent => $aChildren)
        {
            if(empty($aChildren))
            {
                $this->addNode($sParent);
            }
            else
            {
                foreach($aChildren as $sChild)
                {
                    $this->addNode($sParent, $sChild);
                }
            }
        }
    }

    private function addNode($sParent, $sChild = null)
    {
        ## echo 'Add node - parent: '.$sParent.', child: '.$sChild.'<br/>';

        if(!$this->nodeExists($sParent))
        {
            $this->tree[] = array(
            'node'       => $sParent,
            'children'   => array()
            );
        }

        if(null === $sChild)
        {
            return;
        }

        if($this->nodeExists($sChild))
        {
            ## move existing child under a new parent (move an entire branch under a new parent)
            ## echo 'node exists: [[[[' . $sChild . ']]]]';
            $aXpathResult = $this->getNodeXPath($sParent);
            $aXPathParent = $aXpathResult['xPath'];
            $aXpathResult = $this->getNodeXPath($sChild);
            $aXPathChild  = $aXpathResult['xPath'];

            $sVarParent   = "\$this->tree[".implode('][\'children\'][', $aXPathParent)."]";
            $sVarChild    = "\$this->tree[".implode('][\'children\'][', $aXPathChild)."]";

            $sStringEval = "$sVarParent" . "['children'][] = $sVarChild;";
            eval($sStringEval);
            $sStringEval = "unset($sVarChild);";
            eval($sStringEval);
        }
        else
        {
            $aXpathResult = $this->getNodeXPath($sParent);
            $aXPath = $aXpathResult['xPath'];
            $aEntry = array('node' => $sChild, 'children' => array());
            ## printr($aEntry);
            $sStringEval = "\$this->tree[".implode('][\'children\'][', $aXPath)."]['children'][] = \$aEntry;";
            eval($sStringEval);
        }

        ## printr($this->tree);
        ## echo '<hr/>';
    }

    private function nodeExists($sNode, $aNodes = null)
    {
        $aNodes = null === $aNodes ? $this->tree : $aNodes;
        foreach($aNodes as $aNode)
        {
            if(isset($aNode['node']) && $aNode['node'] == $sNode)
            {
                return true;
            }
            if(isset($aNode['children']) && !empty($aNode['children']))
            {
                return $this->nodeExists($sNode, $aNode['children']);
            }
        }
        return false;
    }

    private function getNodeXPath($sNode, $aNodes = null, $aXPath = array())
    {
        ## printr($this->tree);
        $aNodes = null === $aNodes ? $this->tree : $aNodes;
        foreach($aNodes as $k => $aNode)
        {
            if(isset($aNode['node']) && $aNode['node'] == $sNode)
            {
                $aXPath[] = $k;
                return array('nodeFound' => true, 'xPath' => $aXPath);
                ## return $aXPath;
            }
            if(isset($aNode['children']) && !empty($aNode['children']))
            {
                ## $aXPath[] = $k;
                ## $aResult = $this->getNodeXPath($sNode, $aNode['children'], $aXPath);
                $aResult = $this->getNodeXPath($sNode, $aNode['children'], array_merge($aXPath, array($k)));
                if(isset($aResult['nodeFound']) && $aResult['nodeFound'])
                {
                    return $aResult;
                }
                ## return $this->getNodeXPath($sNode, $aNode['children'], array_merge($aXPath, array($k)));
            }
        }
        return array('nodeFound' => false, 'xPath' => $aXPath);
    }

    /* public function isTree()
     {
    return $this->isTree;
    } */

    /**
     * @return array
     */
    public function getTree()
    {
        return $this->tree;
    }

    /**
     * Get a horizontal representation of the tree
     * Array
     *     [] -> level 0 nodes
     *     [] -> level 1 nodes
     *     ....
     * @return array
     */
    public function getTreeHorizontal($aNodes = null, $nLevel = null, &$aResults = array())
    {
        $aNodes = null === $aNodes ? $this->tree : $aNodes;
        $nLevel = null === $nLevel ? 0 : $nLevel + 1;
        foreach($aNodes as $aNode)
        {
            !isset($aResults[$nLevel]) ? $aResults[$nLevel] = array() : '';
            $aResults[$nLevel][] = $aNode['node'];
            $this->getTreeHorizontal($aNode['children'], $nLevel, $aResults);
        }
        return $aResults;
    }

}

Sunday, November 24, 2013

Global stats: Mobile vs Desktop

Mobile vs Desktop
Mobile OS

Stats are based on aggregate data collected by StatCounter from more than 3 million websites, having over 15 billion pageviews / month - http://gs.statcounter.com/about

Saturday, November 23, 2013

Linux/Ubuntu - Video editing - video/audio merging, soundtrack replacing

1) Merge multiple mp3 files into one
sudo apt-get install mp3wrap
mp3wrap onemp3.mp3 file1.mp3 file2.mp3 file3.mp3 ...
mp3wrap onemp3.mp3 -a file1-append.mp3 file1-append.mp3 ...


2) Change video file soundtrack
mencoder -ovc copy -nosound video.avi -o video_nosound.avi
mencoder -ovc copy -audiofile soundtrack.mp3 -oac copy video_nosound.avi -o video_new.avi


3) Merge multiple video files into one
sudo apt-get install mencoder
mencoder -oac copy -ovc copy -idx -o megavideo.avi *.avi


4) Resize video
mencoder input.avi -o output.avi -ovc xvid -xvidencopts bitrate=3000 -oac mp3lame

5) Speed up video (with Avidemux)
sudo apt-get install avidemux
Avidemux - Menu: Video -> Frame rate (set it to 100 for example) -> Save video  

Observation: Speeding up the video should be performed on a video file with the soundtrack removed (see above how to achieve this).

Saturday, November 9, 2013

Ubuntu (>12.04) - install ADT, Eclipse, Android SDK

$ sudo apt-get install eclipse-jdt
$ sudo apt-get install ia32-libs
Download Android SDK from http://developer.android.com/sdk/index.html
$ cd tools/
$ ./android
Install the Eclipse ADT Plugin: http://developer.android.com/sdk/installing/installing-adt.html

Wednesday, October 9, 2013

Linux: create SVN project - branches, trunk and tags - first commit

Create a new SVN project

svnadmin create /var/svn-repos/{$project-name}
chown -R svn-user:svn-group /var/svn-repos/{$project-name}

Create branches and trunk, make first commit

cd ~
rm -rf svn-project
svn co file:///var/svn-repos/{$project-name} svn-project
cd svn-project
mkdir trunk
mkdir branches
mkdir tags
svn add *
svn ci -m "init deploy" *

Saturday, August 17, 2013

Ubuntu/Debian antivirus quick install and folder scan

Install antivirus:
$ sudo apt-get install clamav

Update virus database:
$ sudo freshclam

Scan directory:
$ clamscan -irv /directory-to-scan

Scan and move infected files to a custom location:
$ clamscan -irv /directory-to-scan --move=/tmp/virus

Sunday, July 14, 2013

Ubuntu laptop - set start-up brightness level

Best fix for setting the desired brightness level when the computer first starts (for laptops & notebooks).

Adjust brightness to the desired level.

1) View maximum brightness level:
cat /sys/class/backlight/acpi_video0/max_brightness

2) View current brightness level:
cat /sys/class/backlight/acpi_video0/brightness

3) Set the brightness level to apply on the next restart. Edit /etc/rc.local and add the following line before exit 0:
echo VALUE > /sys/class/backlight/acpi_video0/brightness

Fix: Ubuntu 12.04 - Gnome Classic - Alt + Tab not working

1) Install Compiz Config Settings Manager: sudo apt-get install compizconfig-settings-manager

2) Run ccsm (Alt + F2 or terminal)

3) Go to "Window Management"

4) Check "Application Switcher"

Sunday, April 28, 2013

Linux optipng : Optimize PNG image

$ cp my-image.png my-image-opt.png
$ optipng my-image-opt.png

Friday, March 29, 2013

Telnet SMTP test email address exists

telnet server.com 25
helo hi
mail from: mail@some-other-server.com
rcpt to: address-to-test@server.com

Tuesday, March 5, 2013

CORS: Cross-domain AJAX requests

CORS - Cross-Origin Resource Sharing

Server response header:

Access-Control-Allow-Origin: http://www.external-domain.com

Direct AJAX calls to http://www.external-domain.com will not be restricted by the browser.

Monday, January 21, 2013

Toshiba Tecra A11-1DT battery

Toshiba Tecra A11-1DT battery

Original battery number/type: PA3788U-1BRS

6 cells, DC 10.8v, 55Wh.

Thursday, January 10, 2013

PHP: Escape HTML output and allow custom html tags

Escape HTML output using htmlentities and allow at the same time a custom list of HTML tags.

/**
 * Escape HTML output
 * Allow custom HTML tag list
 * @param string $sText
 * @return string
 */
private function escapeHtml($sText)
{
    $sText = htmlentities($sText, ENT_QUOTES, 'UTF-8');
    $aAllowedTags = array('b', 'strong', 'i', 'em', 'br');
    foreach($aAllowedTags as $sTag)
    {
        $sText = preg_replace('`&lt;(/?'.$sTag.'.*)&gt;`Ums', '<$1>', $sText);
    }
    return $sText;
}

Saturday, January 5, 2013

MySQL: Fix error "Lock wait timeout exceeded; try restarting transaction"

MySQL error message: "Lock wait timeout exceeded; try restarting transaction"
MySQL error code: 1205

The MySQL variable innodb_lock_wait_timeout specifies the lock timeout in seconds.

See the current value of innodb_lock_wait_timeout:
SHOW VARIABLES LIKE 'innodb_lock_wait_timeout';

For MySQL versions greater than 5.5: use SET GLOBAL or SET SESSION syntax to change the value of innodb_lock_wait_timeout at runtime.

For all MySQL versions and earlier versions set this value in my.cnf:
# example:
innodb_lock_wait_timeout=120