Dienstag, 21. Oktober 2014

FFmpeg Build Script

After searching the whole internet for a Mac OSX binary built of ffmpeg with non free codecs included i finally gave up and wrote my own building script.

Since I wanted a statically compiled binary which also can be used on devices without Xcode installed, homebrew was not the perfect solution for me.

I started from scratch building a script that automatically downloads all dependencies and compiles all necessary libraries.

My final script can be found on github: https://github.com/markus-perl/ffmpeg-build-script

Samstag, 11. Oktober 2014

PHP CSV detect delimiter

/**
 * @param string $csvFile Path to CSV file
 * @return string
 */
public function detectDelimiter($csvFile)
{
        $delimiters = array(
            ';' => 0,
            ',' => 0,
            "\t" => 0,
            "|" => 0
        );

        $handle = fopen($csvFile, "r");
        $firstLine = fgets($handle);
        fclose($handle);

        foreach ($delimiters as $delimiter => &$count) {
            $count = count(str_getcsv($firstLine, $delimiter));
        }

        return array_search(max($delimiters), $delimiters);
}

Mittwoch, 23. April 2014

HowTo install ZendDebugger for PHP 5.4 or PHP 5.5 on Debian

Since the ZendDebugger is bundled with ZendStudio and ZendServer the PHP module cannot easily be downloaded standalone.

But with some simple steps the module can be extracted out of the official ZendStudio tarball which can be downloaded for free on http://www.zend.com/en/products/studio/downloads.

Prerequisites


Make sure, openssl0.9.8 is installed. Newer Versions like openssl1.0.0+ will not work.

on debian squeeze

$ sudo apt-get install libssl0.9.8

on debian wheezy

$ wget http://snapshot.debian.org/archive/debian/20110406T213352Z/pool/main/o/openssl098/libssl0.9.8_0.9.8o-7_amd64.deb
$ sudo dpkg -i libssl0.9.8_0.9.8o-7_amd64.deb

Extract the extension


Create a temporary working dir

$ mkdir /tmp/zend_debugger
$ cd /tmp/zend_debugger

Download Zend Studio 10.6

$ wget http://downloads.zend.com/studio-eclipse/10.6.0/ZendStudio-10.6.0-linux.gtk.x86_64.tar.gz

Find the extension in the archive

$ tar -tvf ZendStudio-10.6.0-linux.gtk.x86_64.tar.gz | grep ZendDebugger.so
This will give you the following output:
-rwxrwxr-x vagrant/nogroup   238153 2014-01-08 16:11 ZendStudio/plugins/com.zend.php.debug.debugger.linux.x86_64_10.6.0.v20140128-2127/resources/php53/ZendDebugger.so
-rwxrwxr-x vagrant/nogroup   238217 2014-01-08 15:56 ZendStudio/plugins/com.zend.php.debug.debugger.linux.x86_64_10.6.0.v20140128-2127/resources/php54/ZendDebugger.so
-rw-r--r-- vagrant/nogroup   238631 2014-01-08 15:22 ZendStudio/plugins/com.zend.php.debug.debugger.linux.x86_64_10.6.0.v20140128-2127/resources/php55/ZendDebugger.so

Extract the extension for PHP 5.3, 5.4 and 5.5

$ tar -xzvf ZendStudio-10.6.0-linux.gtk.x86_64.tar.gz --strip-components 4 --wildcards *ZendDebugger.so

Install the extension


Now copy the extension matching your PHP Version to the local extension dir

For PHP 5.5

$ sudo cp php55/ZendDebugger.so `php -i | grep extension_dir | awk '{print $NF}'`

For PHP 5.4

sudo cp php54/ZendDebugger.so `php -i | grep extension_dir | awk '{print $NF}'`

Update your php.ini

Add the following lines at the end of your php.ini file
[Zend Debugger]
zend_extension=ZendDebugger.so
zend_debugger.allow_hosts=127.0.0.1/24,192.0.0.1/32
zend_debugger.expose_remotely=allowed_hosts

Check the extension

$ php -v
PHP 5.5.11-1~dotdeb.1 (cli) (built: Apr  4 2014 02:15:16)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies
    with Zend Debugger v6.0.0, Copyright (c) 1999-2013, by Zend Technologies

That's it. If you can find the line "Zend Debugger v6.0.0" in the output the debugger extension is successfully installed.

Dienstag, 22. April 2014

NodeJs socket hang up

events.js:72

        throw er; // Unhandled 'error' event
              ^
Error: socket hang up
    at createHangUpError (http.js:1472:15)
    at Socket.socketOnEnd [as onend] (http.js:1568:23)
    at Socket.g (events.js:180:16)
    at Socket.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)


This error happens even with the latest nodejs version if you're using a ssl certificate whose domain cannot be resolved by your dns.

Let's say your SSL certificate is issued to www.your-domain.com make sure a dns lookup can resolve this domain.

Simply add your domain to your /etc/hosts file
127.0.0.1 www.your-domain.com

If your using a wildcard certificate *.your-domain.com you can simply add this domain to your /etc/hosts file:

127.0.0.1 *.your-domain.com

Mittwoch, 9. April 2014

socket.io.js, line 1641 character 7 Access denied

SCRIPT5: Access is denied.
socket.io.js, line 1641 character 7
This error happens under IE 10, if nodejs and you webpage runs on a different port. You should ensure that your webserver and your nodejs server are running on the same port with the same protocol.


Montag, 17. Februar 2014

Chrome Browser: How to emulate a touch screen

The Chrome Browser integrates a nice feature to simulate multiple mobile devices or a touch screen.

First of all you have to enable the "Emulation" view in the console drawer. Open the Developer Tools and click the settings icon:







Next, switch to the "General" panel and enable "Show emulation view in console drawer"

Now close the settings and press the ESC (Escape Key) and switch to the "Emulation" Panel (2). The "Sensors" menu (3) let's you enable the "Emulate touch screen" (4) checkbox. That's it!




Freitag, 7. Februar 2014

Git Dropbox Remote Repo


With git you can easily use any directory as an remote repo. Dropbox offers a lot of free space and automatically backups files so why not using dropbbox as a git remote repo :-)

This tutorial should also works with Google Drive and Microsoft SkyDrive. Please make sure that the paths provided below match your local Dropbox / Google Drive / Skydrive folder.

mkdir -p ~/Dropbox/git/my-project

Initialize Git:

git init --bare ~/Dropbox/git/my-project

Go to your project and add the new created dir as remote:

git remote add origin ~/Dropbox/git/my-project

That's it! Now you can push your repo to your dropbox folder:

git push origin master

Donnerstag, 6. Februar 2014

PHP Memcache list / get keys

/**
     * @param string $server
     * @param int $port
     * @param int $limit
     * @return array
     */
    public function getMemcacheKeys ($server, $port, $limit = 10000)
    {
        $keysFound = array();

        $options = $this->_options;
        $server = $options['servers'][0];
        $memcache = new Memcache;
        $memcache->connect($server, $port = 11211, 5);

        $slabs = $memcache->getExtendedStats('slabs');
        foreach ($slabs as $serverSlabs) {
            foreach ($serverSlabs as $slabId => $slabMeta) {
                try {
                    $cacheDump = $memcache->getExtendedStats('cachedump', (int) $slabId, 1000);
                } catch (Exception $e) {
                    continue;
                }

                if (!is_array($cacheDump)) {
                    continue;
                }

                foreach ($cacheDump as $dump) {
                    
                    if (!is_array($dump)) {
                        continue;
                    }

                    foreach ($dump as $key => $value) {
                        $keysFound[] = $key;

                        if (count($keysFound) == $limit) {
                            return $keysFound;
                        }
                    }
                }
            }
        }

        return $keysFound;
    }

Dienstag, 4. Februar 2014

Must Have Git Aliases

Git Shortcut

This is first thing you should do. Aliasing git as `g` will save you a lot of typing. After this symlink creation you can access git with only typing `g` in the command line.
$ sudo ln -s `which git` /usr/bin/g
I'm using git now for some years and over the time I came up with a long list of git aliases. Git is great and can give you a great coding experience with it's customizable shortcuts.

Your .gitconfig file is located in your home dir. All examples can be added to the [alias] section in this file.
$ nano ~/.gitconfig

Basic Aliases

  co = checkout
  cp = cherry-pick
  p  = pull
  squash = merge --squash
  st = status
  df = diff
  b = branch

Advanced Usage

Revert a file

  rv = checkout --

Merging

  ours = checkout --ours --
  theirs = checkout --theirs --

Stashing

  sl = stash list
  sa = stash apply
  ss = stash save

Danger! Cleanup working dir

This alias will reset all modified files!
cleanup = !git reset --hard && git clean -f 

List all aliases

alias = config --get-regexp 'alias.*'

Log One Line

logol = log --pretty=format:"%h\\ %s\\ [%cn]"

Search in files

search = "grep -Iin"

Vagrant

vup = !vagrant up
vsu = !vagrant suspend
vss = !vagrant ssh
vde = !vagrant destroy
vpr = !vagrant provision

Sonntag, 2. Februar 2014

PHP Segmentation fault

This is the worst case for every php developer when hacking some code - your script runs not as expected and you get a simple message saying "Segmentation fault".

Here are the steps you can do, to track down this error.


Some simple tips to start


- Use a debugger like ZendDebugger or XDebug to find the line of code causing the error.

- Disable PHP's internal garbage collector. The garbage collector is known to often cause segmentation faults. If disabling will help you are probably found an internal reference counting bug in the garbage collector
ini_set('zend.enable_gc', 0);
- Look for recursion in your code. PHP throws a segmentation fault if you have a infinite recursion in your code

- If you have apc installed sometimes it helps to empty the cache or disable the cache

Use strace

If php runs on Linux or Mac OS you can use strace/dtruss to hook into the process and see what's happening. Strace can be installed on Debian by running

apt-get install strace

Run phpunit with strace

$ strace phpunit

Attach strace to a already running process

$ sudo strace -s 256 -p <PID>

Run any php script with strace

$ strace php index.php

Attach strace to a running cgi process

$ ps axf | grep php5-cgi # lists all running processes
#If more than one process is found you can use the tool php-strace (see below) to trace all processes at the same time. If only one process is found you can use the following command to trace:
$ sudo strace -s 256 -p <PID>
#For debugging purposes I recommend to limit the cgi processes running to one, so you can be sure to hook into the right process which is serving your browser.
# The number of running cgi processes can be edited by editing the file /etc/php5/fpm/pool.d/www.conf .

Gdb

Also you can try to run the script inside of gdb. On Debian gdb can be installed using the command "apt-get install gdb"

gdb --args php /usr/bin/phpunit
#inside gdb enter:
set env MALLOC_CHECK_=3
#then enter:
r

php-strace

I wrote a tool for easy monitoring running cgi proccesses on a server or a developer box.

php-strace helps to track down segfaults in running php processes. It starts a new strace instance for every running php5-cgi or php-fpm process to monitor whether a segfault happened.


php-strace

To get started, visit my github page. https://github.com/markus-perl/php-strace

Update

php-strace V0.3 available:
https://dl.dropboxusercontent.com/u/32252351/github/php-strace-0.3.tar.gz


Samstag, 1. Februar 2014

How to change the terminal title with a script


Save the following lines in a file called title.sh:
    #!/bin/zsh -f
    echo -ne "\033]0;$@\007" 
and make it executable:
    $ chmod +x title.sh
To change the title simply call
    $ ./title.sh “New Title”

Donnerstag, 30. Januar 2014

Git Jira commit Message


It's easy to commit a jira task without entering the complete task title in the command line. Initially I wrote a simple script for my gender detection project that uses the jira api to fetch the required fields from the Jira server to generate a meaningful commit message but this script can simply be used for any other project.

Link to the script: https://github.com/markus-perl/git-jira-commit-message/blob/master/git-jira-commit-message

Edit the script and enter your credentials:
 #!/usr/bin/php
    <?php
    
    $username = 'Jira username';
    $password = 'jira password';
    $api = 'http://my.jira.url/rest/api/2/';

Now add the following line to the alias section in your .gitconfig file which is located in your home dir:

[alias]
  c = !sh -c 'git-jira-commit-message "$0"'


To commit a task just enter the task id. The script the title of the task to the commit message:

$ git c PR-1201

Mittwoch, 29. Januar 2014

PHP get class name without the namespace

This is the easiest way to get the name of the current class without the namespace:

public function getName() {
    $path = explode('\\', __CLASS__);
    return array_pop($path);
}

Dienstag, 28. Januar 2014

Donnerstag, 16. Januar 2014

Gender Detection API


To improve the conversions of our registration form we developed a gender detection api. The gender checker only requires a first name or an e-mail address containing a first name. 1000 requests to the gender api are free every month.

What if a name can be male as well as female?


If a country code is provided, the gender detection can be improved. For example: While Andrea is male in Italy, Andrea is a female name in the US and can even be both in Germany. With every query a accuracy value is provided how sure the api is to match the right gender. Here is a list of supported countries.




Is ssl supported?

Yes, to give you the best possible privacy protection ssl up to TLS 1.2 is supported

Which countries are supported?

The API supports currently 105 countries. If a name is not found in the given country the complete database will be crawled.

An accurate gender predictor needs to have multiple decision paths to determine the best gender. Therefore the api uses every data provided by the browser to fetch the best possible result. The API is under heavy development and we try to improve it's quality every month.