16 October 2012

Cat

Jelita
Jelita

15 May 2012

RabbitMQ PHP in Ubuntu 12.04

Testing RabbitMQ PHP in Ubuntu 12.04
Examples for AMQP in official PHP site (last check 2012/05/15) not sync with API for PECL 1.0.1.
This is my version to test simple php amqp

emit_log.php:

// Create a connection
$cnn = new AMQPConnection(array('login'=>'guest', 'password'=>'abc123'));
$cnn->connect();

// Create a channel
$ch = new AMQPChannel($cnn);

// Declare a new exchange
$ex = new AMQPExchange($ch);
$ex->setName('logs');
$ex->setType(AMQP_EX_TYPE_FANOUT);
$ex->declare();

// Publish a message to the exchange with a routing key
$message = isset($argv[1]) ? $argv[1] : 'hello world message';
$ex->publish($message, 'routing.key');

receive_log.php:

// Create a connection
$cnn = new AMQPConnection(array('login'=>'guest', 'password'=>'abc123'));
$cnn->connect();


// Create a channel
$ch = new AMQPChannel($cnn);


// Declare a new exchange
$ex = new AMQPExchange($ch);
$ex->setName('logs');
$ex->setType(AMQP_EX_TYPE_FANOUT);


// Create a new queue
$q = new AMQPQueue($ch);
$q->declare();
$q->bind('logs', 'routing.key');


function cb($env, $q) {
    print $env->getBody()."\n";
}
// Read from the queue
$msg = $q->consume('cb');


Easier to manage rabbitmsq server with the rabbitmq_management than the rabbitmqctl
Example based on rabbitmq Publish/Subscribe tutorial

30 October 2010

Custom Street View panorama using Google Maps v3

Notes and command line script to run when create custom Street View.
Demo

Create initial panorama
* using point and shoot camera take enough pictures to cover all around (8-12 is good enough)
* use stitching software to create equirectangular projection of the panorama
* panorama must be aspect ratio 2:1

Streetview tiles
* if initial panorama size 8192x4096, then for tile size 512x512, we need to create:
convert ${FN}_5.jpg -resize 8192x4096  ${FN}_4.jpg
convert ${FN}_4.jpg -resize 4096x2048  ${FN}_3.jpg
convert ${FN}_3.jpg -resize 2048x1024  ${FN}_2.jpg
convert ${FN}_2.jpg -resize 1024x512   ${FN}_1.jpg
convert ${FN}_1.jpg -resize 512x256    ${FN}_0.jpg

* The panorama with a single tile is zoom = 0, then 1,2,3,4
* Name each tile according to its zoom level and position.
* The top left tile is always tile (0,0).
* tile name format = "panorama_z_x_y.jpg".
 
convert ${FN}_5.jpg -crop ${SIZE}x${SIZE} -set filename:tile "%[fx:page.x/${SIZE}]_%[fx:page.y/${SIZE}]" +repage +adjoin "${FN}_5_%[filename:tile].jpg"
convert ${FN}_4.jpg -crop ${SIZE}x${SIZE} -set filename:tile "%[fx:page.x/${SIZE}]_%[fx:page.y/${SIZE}]" +repage +adjoin "${FN}_4_%[filename:tile].jpg"
convert ${FN}_3.jpg -crop ${SIZE}x${SIZE} -set filename:tile "%[fx:page.x/${SIZE}]_%[fx:page.y/${SIZE}]" +repage +adjoin "${FN}_3_%[filename:tile].jpg"
convert ${FN}_2.jpg -crop ${SIZE}x${SIZE} -set filename:tile "%[fx:page.x/${SIZE}]_%[fx:page.y/${SIZE}]" +repage +adjoin "${FN}_2_%[filename:tile].jpg"
convert ${FN}_1.jpg -crop ${SIZE}x${SIZE} -set filename:tile "%[fx:page.x/${SIZE}]_%[fx:page.y/${SIZE}]" +repage +adjoin "${FN}_1_%[filename:tile].jpg"
# resize to tile size and fill neutral color
convert ${FN}_0.jpg -resize 512x512\> -size 512x512 xc:black +swap -composite ${FN}_0_0_0.jpg 


Javascript code for streetview
function initialize() {
  var panorama = new google.maps.StreetViewPanorama(
    document.getElementById('streetview'),
    {
      panoProvider: function(pano) {
        return {
          location: {
            pano: pano
          },
          copyright: 'helmi03',
          links: [],
          tiles: {
            tileSize: new google.maps.Size(512, 512),
            worldSize: new google.maps.Size(8192, 4096),
            originHeading: 0,
            getTileUrl: function(room, zoom, x, y) {
              return 'tt_' +
                  zoom + '_' + x + '_' + y + '.jpg';
            }
          }
        };
      },
      pano: 'tt'
    }
  );
}

Demo
Panorama view of playground at Tasik Titiwangsa, Kuala Lumpur

Note that Google Maps v3 use html5 canvas instead of flash in v2.

Credits
Other blogger already give great explanation to create custom streetview and Google Maps had excellent documentation about this feature. Credits to them.
Before this, I display panorama view using java plugin.

07 September 2010

21 April 2010

Ubuntu in ThinkPad X100e

ThinkPad X100e

Few notes while install Ubuntu Lucid:
  1. I install Lucid after upgrade from Karmic. Downloaded the Karmic AMD64 ISO, and run usb-creator to copy to my USB stick.
  2. Make sure wireless enabled in BIOS, there is no hardware button to enable wireless! My lappy disabled it by default (I bought it without OS from Digital Mall, Petaling Jaya )
  3. Get latest wireless driver and install it (wireless driver from Lucid not working for me). You also might want to configure TrackPoint "scroll button".
  4. Update to the latest X100e BIOS and the latest 10.04 packages and the fglrx driver.This fix issue "pressing function key to adjust brightness hard-lock the machine", "hard-locks if you switch to battery power"
Have issue after install fglrx: most of time CPU usage for Xorg very high.

Love the design. Chose red since big fan of Arsenal FC (even my daughter named Humaira). Keyboard is very nice, that's why prefer this over U series/other brand.

This lappy use AMD Processor, so known quite hot.There is no CD/DVD driver! luckily I rarely use it and have an external USB one (useful to update BIOS). Don't like the 'Delete' key position.

Issues above might not valid anymore after Ubuntu Lucid release (within fortnight)

14 April 2010

Optimize P1 W1MAX Signal

Position is the key. There is difference when P1 modem inside and outside (balcony) of my house.

Inside

Outside


I been using P1 since Aug 2009, and the signal mostly strong when placing the modem inside house. The signal is significantly difference this couple of days, might be due to P1 Network Upgrade Exercise (9-12 March 2010). Anyway hope better signal while streaming Arsenal games tonight :-)

02 February 2010

Tilecache TMS fixes

Error message when working with tilecache TMS:

An error occurred: The requested layer (1.0.0) does not exist. Available layers are:

To fix it, only add one line as below:

helmi@gandalf:~/Packages/tilecache-2.10/TileCache/Services$ diff -C3 TMS.py TMS_fix.py 
*** TMS.py      2010-02-02 16:12:32.000000000 +0800
--- TMS_fix.py  2010-02-02 16:13:06.000000000 +0800
***************
*** 13,18 ****
--- 13,19 ----
          elif len(parts) < 2:
              return self.serviceCapabilities(host, self.service.layers)
          else:
+             parts = parts[-5:]
              layer = self.getLayer(parts[1])
              if len(parts) < 3:
                  return self.layerCapabilities(host, layer)
http://twitter.com/helmi03/status/8534440936

28 October 2009

gearman php problem on jaunty

Get this error on my ubuntu jaunty, works perfectly on hardy. I don't have the solution (hope expert out there post solution in comment)
helmi@gandalf:/tmp> php reverse_client.php 
Sending job
ALERT - canary mismatch on efree() - heap overflow detected (attacker 'REMOTE_ADDR not set', file '/tmp/reverse_client.php', line 10)

How I install:
helmi@gandalf:~/Packages/php> sudo pecl install gearman-0.6.0

some info:
helmi@gandalf:~/Packages/php/gearman-0.6.0> phpize
Configuring for:
PHP Api Version:         20041225
Zend Module Api No:      20060613
Zend Extension Api No:   220060519
helmi@gandalf:~/Packages/php/gearman-0.6.0> echo '<?php phpinfo();' | php| head 
phpinfo()
PHP Version => 5.2.6-3ubuntu4.2

System => Linux gandalf 2.6.28-15-server #52-Ubuntu SMP Wed Sep 9 11:50:50 UTC 2009 i686
Build Date => Aug 21 2009 19:12:00
Server API => Command Line Interface
Virtual Directory Support => disabled
Configuration File (php.ini) Path => /etc/php5/cli
Loaded Configuration File => /etc/php5/cli/php.ini
Scan this dir for additional .ini files => /etc/php5/cli/conf.d

helmi@gandalf:~/Packages/php/gearman-0.6.0> gearmand -V
gearmand 0.10 - https://launchpad.net/gearmand

16 October 2009

Fix IE6 png transparency

Don't know who use IE6 these days (already 2009 lah), but one of my friend need to fix his website. So here the css (modified from a google result)

<!--[if lt IE 7]>
<style>
img {
  position: relative;
  behavior: expression((this.runtimeStyle.behavior="none")&&(this.pngSet?this.pngSet=true:(this.nodeName == "IMG" && this.src.toLowerCase().indexOf('.png')>-1?(this.runtimeStyle.backgroundImage = "none",
  this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='image')",
  this.src = "http://imgur.com/ZOqET.gif"):(this.origBg = this.origBg? this.origBg :this.currentStyle.backgroundImage.toString().replace('url("','').replace('")',''),                                                                                                                                                     
  this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.origBg + "', sizingMethod='crop')",
  this.runtimeStyle.backgroundImage = "none")),this.pngSet=true));
}
</style>
<![endif]-->

09 October 2009

Inconsistent PHP - I'm sick of it

PHP is inconsistent, sick of it. $needle or $haystack? Which one first? List of php function that inconsistent needle/haystack

helmi@gandalf:/usr/share/doc/php-doc/html> grep -l needle *| grep ^function | sed 's/^function.//'| sed 's/.html$//'| sed 's/-/_/'
array_search
grapheme_stripos
grapheme_stristr
grapheme_strpos
grapheme_strripos
grapheme_strrpos
grapheme_strstr
iconv_strpos
iconv_strrpos
in_array
mb_stripos
mb_stristr
mb_strpos
mb_strrchr
mb_strrichr
mb_strripos
mb_strrpos
mb_strstr
mb_substr-count
stripos
str_ireplace
stristr
strpos
strrchr
str_replace
strripos
strrpos
strstr
substr_count


So I refer to php manual everytime use these functions, grrr. For vim, i override key binding for 'K' (:help K) - "Run a program to lookup the keyword under the cursor". In .vimrc
autocmd FileType php set keywordprg=~/bin/php_doc

and my ~/bin/php_doc

#!/bin/sh
FN=`echo $1 | sed 's/_/-/g'`
echo ********************** $FN **********************

echo $FN
w3m file:///usr/share/doc/php-doc/html/function.$FN.html

02 October 2009

OpenStreetMap data for Malaysia = impressive progress!


Version 17 Apr 09

Version 24 Sept 09


OpenStreetMap data for Malaysia = impressive progress!
Quite a lot of new road added at Kuala Lumpur for 5 months work.
Map above viewed using udig.
Google Map Maker is available for Malaysia, but don't think it easy for offline usage/internal use (hint:shapefile).

28 August 2009

Which location column more trusted?

You have database from your client with fields state, district (description of locations), and the_geom (latitude/longitude) column. Example of the db

| state | district | the_geom |
| Selangor | Petaling | POINT(101.497838106615 3.27468487066054) |


Anyone doing GIS should know that, the state, district fields is duplicate with the_geom since once we know the latitude/longitude we will know the state, district.
The problem is the_geom is not within Selangor, Petaling. Then when do group by st_intersects, the value is wrong since the_geom is refer to other place!

So, need to decide, which location column more trusted?
The latitude/longitude or description of locations.

26 June 2009

Mapnik need to know postgis column type

Mapnik need to know postgis column type to render properly. This mapnik xml for style not working for me.


<Style name="jalan_casing2">
<Rule>
<Filter>[jenis] = 'lebuhraya'</Filter>
<MaxScaleDenominator>&maxscale_zoom7;</MaxScaleDenominator>
<MinScaleDenominator>&minscale_zoom7;</MinScaleDenominator>
<LineSymbolizer>
<CssParameter name="stroke">#808080</CssParameter>
<CssParameter name="stroke-width">6</CssParameter>
<CssParameter name="stroke-linejoin">round</CssParameter>
<CssParameter name="stroke-linecap">round</CssParameter>
</LineSymbolizer>
</Rule>
</Style>
<Layer name="jalan_lebuhraya" srs="+proj=latlong +datum=WGS84" status="on">
<StyleName>jalan_casing2</StyleName>
<StyleName>jalan_fill</StyleName>
<StyleName>jalan_text</StyleName>
<Datasource>
<Parameter name="type">postgis</Parameter>
<Parameter name="password"></Parameter>
<Parameter name="host">localhost</Parameter>
<Parameter name="port">5432</Parameter>
<Parameter name="user">helmi</Parameter>
<Parameter name="dbname">road</Parameter>
<Parameter name="table">(select * no_jalan, 'lebuhraya' as jenis, the_geom from jalanraya.lebuhraya) as jalan</Parameter>
<Parameter name="estimate_extent">false</Parameter>
<Parameter name="extent">-180,-90,180,89.99</Parameter>
</Datasource>
</Layer>


My workaround (only tested on Ubuntu Jaunty) is cast the new column as varchar.

(select * no_jalan, 'lebuhraya'::varchar as jenis, the_geom from jalanraya.lebuhraya) as jalan


Mapnik is better than MapGuide when rendering road labels

OptimizeRenderingWithPostGIS

27 May 2009

MapGuide 2.1beta

Eager to try beta version, here I log the problem I face and how I solve.

Error msg:

httpd.exe: Syntax error on line 127 of C:/Program Files/OSGeo/MapGuide/Web/Apache2/conf/httpd.conf: Cannot load ../Php/MgHttpHandler.dll into server: The specified procedure could not be found.

Fix by move directive 'MgHttpHandler.dll' up

LoadFile ../Php/php5ts.dll
LoadFile ../Php/ACE.dll
LoadFile ../Php/MgHttpHandler.dll # put this directive here, the first one and restart apache service
LoadFile ../Php/MgFoundation.dll
LoadFile ../Php/MgGeometry.dll
LoadFile ../Php/MgMapGuideCommon.dll
LoadFile ../Php/MgMdfModel.dll
LoadFile ../Php/MgMdfParser.dll
LoadFile ../Php/MgPlatformBase.dll
LoadFile ../Php/MgWebApp.dll

http://n2.nabble.com/MGOS-2.0.0-Beta-2-loadfile-error-td1816710.html

26 May 2009

13 May 2009

schema.table to "schema"."table"

PHP

<?php
$st = 'schema.table';
print join('.', array_map(create_function('$a', 'return \'"\'.$a.\'"\';'), explode('.', $st)));

Selected 3 of 3 Lines; 11 of 11 Words; 124 of 124 Bytes

Python

st = 'schema.table'
print '.'.join('"'+i+'"' for i in st.split('.'))

Selected 2 of 2 Lines; 9 of 9 Words; 69 of 69 Bytes

Python=PHP/2

05 May 2009

Trac error - database disk image is malformed

One of my trac page got the error message "database disk image is malformed"

"underlying Trac DB is in serious trouble, may corrupted" - Ticket #6347

How I fix:
sqlite3 trac.db .dump | sqlite3 trac2.db
cp trac.db trac.broken.db
cp trac2.db trac.db

04 May 2009

Find files, php5 way

Find files, implemented using iterator.

class RegexFilter extends FilterIterator {
protected $regex;

public function __construct(Iterator $it, $regex) {
parent::__construct($it);
$this->regex = $regex;
}

public function accept() {
return preg_match($this->regex, $this->current());
}
}

function find_files($path, $pattern, $include_dir=FALSE) {
$objects = new RecursiveDirectoryIterator($path);
$objects = new RecursiveIteratorIterator($objects, RecursiveIteratorIterator::SELF_FIRST);
$objects = new RegexFilter($objects, $pattern);
return $objects;
}


Example usage:

$files = find_files('/tmp', '/.py$/');
foreach ($files as $file) {
echo $file;
}


Previously using php 4:

function find_files4($path, $pattern, $callback=null) {
$path = rtrim(str_replace("\\", "/", $path), '/') . '/';
$matches = Array();
$entries = Array();
$dir = dir($path);
while (false !== ($entry = $dir->read())) {
$entries[] = $entry;
}
$dir->close();
$files = array();
foreach ($entries as $entry) {
$fullname = $path . $entry;
if ($entry != '.' && $entry != '..' && is_dir($fullname)) {
$this->find_files($fullname, $pattern, $callback);
} else if (is_file($fullname) && preg_match($pattern, $entry)) {
if (!$callback) {
$files[] = $fullname;
} else {
call_user_func($callback, $fullname);
}
}
}
if (!$callback) {
return $files;
}
}

import data from csv into postgresql

We can use sql command, COPY. But programmer still need to create the table before copy the data. Simple python script to help


#!/usr/bin/python
fn = '/home/helmi/world.csv'
columns = file(fn).readline()
print 'create table world (%s text);' % " text,".join(columns.split(','))
print "copy world from '%s' with csv header;" % fn


then

python csv2psql.py | psql mydb