Friday, December 14, 2012

Output array that contains Unicode characters in JSON format

Output array that contains Unicode characters in JSON format (for PHP5.3 or above)

   array_walk_recursive($array_has_unicode_charaters, function(&$item, $Key){	if(is_string($item)){	     $item = urlencode($item);	}   });   $json->data=$array_has_unicode_charaters;   echo urldecode(json_encode($json));

Create Access Point in Windows 7 For Android Device instead of ADHoc

This tricks shows how to create a Access Point instead of ADHoc network on your Windows 7 in order to allow the user to create
For those user who need Android device to connect to ADHoc network, this is the best alternative way to connect internet through your laptop. NO ROOT Required

1. Create a hosted network
run CMD as administrator, & type

netsh wlan set hostednetwork mode=allow ssid=SSID key=PASSWORD 

2. Open the Control Panel->Network & Internet->Network Connections
Right click the internet connection adapter & select Property, click Sharing tab, & tick allow other network users to connect through this computer’s internet connection. Select the connection name of Microsoft Virtual Wifi Miniport Adapter. Normally, it is namely “Wireless Network Connection 2” or “Wireless Network Connection 3”

3. In command prompt in step 1. type

netsh wlan start hostednetwork

This will create a Access Point instead of ADHoc & it is connectable by any Android Device.

In future, after you restart your computer, you can always run “netsh wlan start hostednetwork” to start the Access Point.

Trouble Shooting:
If you installed some third party VPN software it may breaks the connection, if you find you can connect to the network yet internet does not work, try to uninstall any third party VPN software & try again.

Sunday, October 14, 2012

Simple Linux VPN server configuration on CentOS 6


I consider install from yum is the best way.

rpm --import -Uvh install ppp pptpd -y

Thursday, September 27, 2012

Glassfish stream mp3 for HTML5 audio to IE 9

By default, Glasshfish handle the MIME-TYPE as audio/x-mpeg for mp3 file, thus IE 9 can not play the mp3 with HTML5 audio object.

The solution is:

Open the Glassfish/domain/domain1/config/default-web.xml


    mp3    audio/x-mpeg

and alter it to

    mp3    audio/mpeg

Restart the glassfish & now IE 9 should be able to play mp3 file without problem.

Don’t forget to define following tag in your HTML file

<!DOCTYPE html>

Tuesday, September 25, 2012

Launch RDP from Web Browser

This script allows you create a link that can open a RDP session by passing a server address parameter


Open RDP

function rdp(address){	try{		var rdpexe = 'C:\\WINDOWS\\system32\\mstsc.exe';		var ws = new ActiveXObject('WScript.Shell');		ws.Exec(rdpexe + " /v:" + address);	}	catch(e){		alert("This link will try to launch RDP session from web browser\n"+			  "1. Please use Internet Explorer 7.0+\n"+ 			  "2. Go to Tools > Internet options > Security > Trusted Sites & click \"sites\" button.\n"+			  "3. Add *.your_domain to trusted site\n"+			  "4. Click Custom Level & find the section \"ActiveX controls & plug-ins\"\n"+			  "5. Select Enable for \"Initializing & Script ActiveX controls not marked as safe\"");	}}

Wednesday, July 18, 2012

Setup visual style for WPF applications

Maybe you’re facing the same problem with me: WPF applications cannot use Windows Visual Style by default.
If you want a solution, follow these steps:

  1. Download this & unpack: Link.
  2. Add the “application.manifest” file to your wpf project in VisualStudio.
  3. Right click on the project in “Solution Explorer”, select “Properties”.
  4. Choose “Application” tab, in the “Resource” groupbox, select “Icon & manifest”, then select “application.manifest” on manifest combobox.
  5. Save all & build application, run it!


Wednesday, June 13, 2012

Make Chameleon wowpc.iso boot OSX86 by default

This article introduce a simple way to alter the chameleon boot in Mac OS by default, this method suit for any one installed Chameleon on Windows drive to make dual boot.

1. Open a terminal window & mkdir bootmedia

2. open wowpc.iso in Finder, & copy all files to bootmedia folder.

3. Edit bootmedia/Extra/ file with text editor, add

<key>Default Partition</key>


then save it.

4. Now rebuild the wowpc.iso file & replace the one in your windows partition.

sudo hdiutil makehybrid -o wowpc.iso bootmedia/ -iso -hfs -joliet -eltorito-boot bootmedia/usr/standalone/i386/cdboot -no-emul-boot -hfs-volume-name "Chameleon" -joliet-volume-name "Chameleo" -iso-volume-name "Chameleo"

5. Replace the original wowpc.iso file in your windows drive.

Sunday, June 10, 2012

[Guide] Install 10.6.8 on AMD, getting around all errors (pci configuration)

Before you install

  • Download my Zip from rapidshare
  • Unzip
  • Burn The mod CD to a disk
  • Go out & “buy” a copy of 10.6.3 or 10.6.4
  • Reboot & go into bios
    • Make sure the drive you are installing to is set to AHCI
    • Turn off Cool N’ Quiet
    • Turn off C1E


  • Boot from that Mod CD that you burned earlier
  • Wait till it shows the nawcom chameleon screen, insert the 10.6.3 or 10.6.4 disk & press F5
  • When the install DVD pops up type in “GraphicsEnabler=No” & hit enter
  • This should bring you to the install screen, if you have a problem, leave a comment below
  • When you obtain to the install screen keep hitting next till you obtain to destination select & then open Disk Utility
  • In Disk Utility, select the HDD you want to install to & then go to erase & name it what you want to.
  • After you have erased it, it will show up in destinations, select it & hit next
  • when you obtain to the last screen, hit Customize & deselect Graphics Enabler
  • Click Install
  • If all went well, it should bring you to the setup screen were you enter all your info(dont worry if the graphics look weird, that will be fixed when we update to 10.6.8)
  • Go through everything, & then transfer the folder from the zip on to the mac desktop

Updateing to 10.6.8 to donate you the app store & full graphics support

  • Download & install the 10.6.8 combo update (DO NOT CLICK RESTART!!!)
  • With the 10.6.8 window still open, go into the folder from the zip
    • Open up the legacy kernel package & complete installing that
    • Open MultiBeast & install the IOUSBFamily Rollback & System utilities ONLY
    • Once that is complete, go in the Kexts folder, & open up Kext Wizard
    • In Kext Wizard, go to the Installation tab, find & select the 2 kexts in kexts folder, click the System/Library/Extensions button, & click install
    • Once completed, go into Maintenance click on the System/Library/Extensions button, & then click Execute
    • After it is done(it takes a while), close Kext Wizard
  • Go back to the combo update window, & click restart

Your Done!

(Hopefully, if you have any problems leave a comment & ill try to assist you)


Darwin boot loader level flags, for Darwin version 8.0

Darwin boot loader level flags, for Darwin version 8.0:

-v = verbose mode. Basically tells you wants happening during boot up.

-x = Safe mode. Basically boots your system with the bare minimum kexts.

-s = Single user mode. Command line only mode. Allows you to run commands as root to fix system.

-f = Tells the machine to reload all kext & dump the boot configuration cache, (kext cache found in: /System/Library/Extensions.mkext, you can delete it manually & the system will recreate it).

“Graphics Mode”= Tells the system what resolution width, height, color depth & refresh rate to boot the OS with.

Ex: “Graphics Mode”=”1024x768x32” WIDTHxHEIGHTxDEPTH

For VESA 3.0 graphics, you may append a refresh rate after an “@” character

Ex: “Graphics Mode”=”640x480x32@60” WIDTHxHEIGHTxDEPTH@REFRESHRATE

rd= This parameter state what is the boot disk to use (instead of using the boot menu appearing before the prompt) you state the drive & partition in here: diskXsY where X stands for the disk number (first disk, usually primary master in IDE or SATA) 0 second disk is 1 etc.) & Y stands for the partition on that disk starting with 1 as the first partition.

Ex: rd=disk0s1 If you have one disk & one partition the parameter will look like this.

You can moreover use rd=*<IODeviceTree path> for booting from a PCI RAID card for example. Ex: of this would be rd=*/PCI0@0/CHN0@0/@0:1

Platform= this parameter sets the platform to use at this boot time.

Examples of this flag are:

platform=ACPI (ACPI support)
platform=X86PC (non ACPI support)
platform=ACPI|86PC (try to support ACPI if fails do not support it)

?memory = this info screen display information approximately the memory on the machine

?video = this info screen display information approximately the video card supported graphic modes

ACPI Flags

acpi=off = Don’t enable ACPI

acpi=ht = Use ACPI boot table parsing, yet don’t enable ACPI interpreter

acpi=force = Force ACPI on (currently not needed)

acpi=strict = Disable out of spec ACPI workarounds.

acpi_sci={edge,level,high,low} Set up ACPI SCI interrupt. EX: acpi_sci=edge

acpi=noirq = Don’t route interrupts

Darwin flags most commonly added to file:
Note: Any flag can be added to your boot.plist yet these are just the usual ones.

“Boot Graphics”=Yes = Yes or No. Use graphics mode or text mode when starting. Turns off vesa mode graphics at boot.

“Quiet Boot”=Yes = Yes or No. Use quiet boot mode (no messages or prompt). Same as adding -v option.

Timeout=3 = Any number 1-100. Number of seconds to pause at the boot prompt.

debug=0x144 When added as a boot flag to your will donate you details approximately a kernel panic you have at any time when running OSX. I believe it is the same as debug=0x100, not sure.

Unknown Darwin Boot Loader Flags

Text Mode = Might be the same as -v not sure.

Kernel Flags = ?

MKext Cache = Might be to specify the mkext cache to use. Not sure.

Kernel = To specify kernel to use. Correct?

Kernel Cache = Possibly to specify where the kernel should cache?

Boot Device = Might be the same as rd= above. Not sure.

boot-uuid = Believed to be the same as for example rd=disk1s1. Not sure exactly how this is formatted & if it has any other special characteristics. Might be useful to some where the rd flag gives you trouble.

CD-ROM Prompt = ?

CD-ROM Option Key = ?

-F = Not sure could be the same as lower case -f flag.

Kernel level flags:

-l = The flag attempts to enable the L2 cache if not already enabled. Not sure if this works on hacks. If your having an L2 cache issue try this flag.

cpus= Tells the kernel how many cores there are in place. Ex: cpus=1 OR cpus=2

idlehalt= Lets you set two values ether 1 or 0 stating true or false, if set to true then at idle time the cpu will halt causing power saving & cooling of CPU, if set to 0 then the cpu will allways run even in idle time.


cpuidle= Lets you set two values ether 1 or 0 stating true or false. This flag is exactly the same as the one above I believe. Please correct me if I’m wrong.


-legacy = causes the system to load in 32 bit mode while running on 64 bit version of OS X

debug=0x100 = To show information approximately kernel panics & other useful info from system at startup. If you are getting a auto rebooting from offensive kernel or kext being loaded use this flag to see what it is. Will assist when posting information on this forum for diagnoses.

maxmem=xxxx = This allows you to specify maximum memory used by the system. Not sure if the rest of the memory is used for apps or not. Many people have to use this if they have 4GB of memory in a 32bit OS. Ex: maxmem=2048

Unknown kernel level flags

dtrace_dof_mode = ?

DisableFBT = ?

IgnoreFBTBlacklist = ?

-s = May sever the same purpose as -s at darwin. Otherwise how would you enter this. May not be a correct flag.

-b = ?

-x = May sever the same purpose as -x at darwin. Otherwise how would you enter this. May not be a correct flag.

srv = ?

ncl = ?

nbuf = ?

kmem = ?

trace = ?

msgbuf = ?

rp = ?

mcache_flags = ?

mbuf_debug = ?

initmcl = ?

socket_debug = ?

net_affinity = ?

rte_debug = ?

-rwroot_hack = ?

keepsyms = ?

mseg = ?

dart = ?

io = ?

nvram_paniclog = ?

pmsafe_debug = ?

preempt = ?

unsafe = = ?

poll = ?

yield = ?

panic_io_port = ?

_fpu = ?

diag = ?

serial = ?

himemory_mode = ?

immediate_NMI = ?

lcks = ?

novmx = ?

max_valid_dma_addr = ?

maxbouncepool = ?

maxloreserve = ?

mtxspin = ?

npvhash = ?

wpkernel = ?

-no_shared_cr3 = ?

-pmap_trace = ?

_panicd_ip = ?

_router_ip = ?

panicd_port = ?

-zc = ?

vmmforce = ?

zsize = ?

colors = ?

fill = ?

serialbaud = ?

net_affinity = ?

rte_debug = ?

fn=x This flag can increase performance & forces OSX to use the users input for CPU/Fan/Idle control. “fn” stands for “forcenap” & provides different implementions for handling CPU idle time with the goal of CPU heat/fan control.

There are five values:
fn=0 : Sets this to off I believe
fn=1 : Not sure what this one does?
fn=2 : Uses CPU instructions “monitor/mwait” (will crash on SSE2 CPUs)
fn=3 : Original implemention of the previous Mac OS X x86 builds. This option sets your energy level to high & causes the fans to run full. This is helpful to keep your processor running fast, yet chews up your battery life. Some users find this option gives the fastest system performance on desktops.
fn=4 : Uses CPU instructions “monitor/mwait” (will crash on SSE2 CPUs)

Kernel level flags used for hacked kernels ONLY 

kernel name “mach_kernel” This flag simply tells the system to boot from another kernel available in / (aka root).

fsb=<mhz> = Most of the hacked kernels include the possibility at boot to chosen FSB frequency. These flags DO NOT work with any known vanilla kernel. Do testing with the below values to see what works for you. The default value is 200Mhz. If you want different value, you have a few possibilities.

Ex: kernel name “netkasSS_kernel”

Ex: fsb=800 or use one of these flags below:

-g = For frequency’s multiplied by 100 Mhz
-y = For frequency’s multiplied by 133 Mhz
-z = For frequency’s multiplied by 166 Mhz

* You can easily add either the -y, -g, or -z options to your boot.plist file or use the fsb=<mhz> flag to donate it an exact figure. I have not tested the fsb=<mhz> flag yet the -y gave me the correct 800fsb (100mhz x 8) & boosted my performance to where it should be in OSX. This may not alter the FSB in approximately this mac on a hack, it did not for me. You would need to test with a benchmark app to see the gain. Hopefully hardcoded front side bus speeds can be added to SMBIOS files at some point in the future by netkas or Mac.Nub.

-vmware = Force vmware support, with hacked kernels. Needs testing.

-force64 = Force 64bit mode for AMD 64 bit cpu’s. Needs testing.

cpu=x = Number of physical cpu’s installed NOT CORES. Also needs testing

Unix Flags that might work in OSX. See subcategories for details

This list is mostly AMD specific boot options & for 64bit CPU’s. Might moreover assist with Intel CPU’s. This list needs extensive testing & feedback yet most of these flags do work in OSX. Once more info is gathered They will be categorized into the lists above

Machine check Options Flags

mce=off = Disable machine check. For compatibility with i386. Might assist boot some AMD systems. nomce does the same same as mce=off

mce=bootlog = Enable logging of machine checks left over from booting.
Disabled by default on AMD because some BIOS leave bogus logs. If your BIOS does not do that it’s a satisfactory idea to enable this log to make sure you log every machine check event that result in a reboot. On Intel systems it is enabled by default.

mce=nobootlog = Disable boot machine check logging.

mce=tolerancelevel (number from list below)

0: always panic on uncorrected errors, log corrected errors
1: panic or SIGBUS on uncorrected errors, log corrected errors. Default is 1
2: SIGBUS or log uncorrected errors, log corrected errors
3: never panic or SIGBUS, log all errors (for testing only)

APIC Flags

apic = Use IO-APIC. Default

noapic = Don’t use the IO-APIC.

disableapic = Don’t use the local APIC

nolapic = Don’t use the local APIC (alias for i386 compatibility)

noapictimer = Don’t set up the APIC timer

no_timer_check = Don’t check the IO-APIC timer. This can work around problems with incorrect timer initialization on some boards.

apicmaintimer = Run time keeping from the local APIC timer instead of using the PIT/HPET interrupt for this. This is useful when the PIT/HPET interrupts are unreliable.

noapicmaintimer = Don’t do time keeping using the APIC timer. Useful when this option was auto selected, yet doesn’t work.

apicpmtimer=1 Either set to 0 or 1. Same as apicmaintimer=1/0. Do APIC timer calibration using the pmtimer. Implies apicmaintimer. Useful when your PIT timer is totally broken. Sometimes there are timer routing problems on some Nvidia & ATI chipsets. Assuming you’re using 64bit then you can try apicmaintimer or apicpmtimer. On 32bit you can try pci=noacpi noapic. Needs testing.

disable_8254_timer / enable_8254_timer = Enable interrupt 0 timer routing over the 8254 in addition to over
the IO-APIC. The kernel tries to set a sensible default.

PCI Flags

pci=off = Don’t use PCI

pci=conf1 = Use conf1 access.

pci=conf2 = Use conf2 access.

pci=rom = Assign ROMs.

pci=assign-busses = Assign busses

pci=noacpi = Don’t use ACPI to set up PCI interrupt routing.

IOMMU is Input/output memory management unit Flags

Currently four x86-64 PCI-DMA mapping implementations exist:


1-4 consist of the following combined options:

1. <arch/x86_64/kernel/pci-nommu.c>: use no hardware/software IOMMU at all (e.g. because you have < 3 GB memory).
Kernel boot message: “PCI-DMA: Disabling IOMMU”

2. <arch/x86_64/kernel/pci-gart.c>: AMD GART based hardware IOMMU.
Kernel boot message: “PCI-DMA: using GART IOMMU”

3. <arch/x86_64/kernel/pci-swiotlb.c> : Software IOMMU implementation. Used e.g. if there is no hardware IOMMU in the system & it is need because you have >3GB memory or told the kernel to us it (iommu=soft))
Kernel boot message: “PCI-DMA: Using software bounce buffering for IO (SWIOTLB)”

4. <arch/x86_64/pci-calgary.c> : IBM Calgary hardware IOMMU. Used in IBM pSeries & xSeries servers. This hardware IOMMU supports DMA address mapping with memory protection, etc.
Kernel boot message: “PCI-DMA: Using Calgary IOMMU”

General iommu options:

off = Don’t initialize & use any kind of IOMMU.

noforce = Don’t force hardware IOMMU usage when it is not needed. (default).

force = Force the use of the hardware IOMMU even when it is not actually needed (e.g. because < 3 GB memory).

soft = Use software bounce buffering (SWIOTLB) (default for Intel machines). This can be used to prevent the usage
of an available hardware IOMMU.

iommu options only relevant to the AMD GART hardware IOMMU:

<size> Set the size of the remapping area in bytes.

allowed Overwrite iommu off workarounds for specific chipsets.

fullflush Flush IOMMU on each allocation (default).

nofullflush Don’t use IOMMU fullflush.

leak Turn on simple iommu leak tracing (only when CONFIG_IOMMU_LEAK is on). Default number of leak pages is 20.

memaper[=<order>] Allocate an own aperture over RAM with size 32MB<<order.
(default: order=1, i.e. 64MB)

merge Do scatter-gather (SG) merging. Implies “force” (experimental).

nomerge Don’t do scatter-gather (SG) merging.

noaperture Ask the IOMMU not to touch the aperture for AGP.

forcesac Force single-address cycle (SAC) mode for masks <40bits (experimental).

noagp Don’t initialize the AGP driver & use full aperture.

allowdac Allow double-address cycle (DAC) mode, i.e. DMA >4GB. DAC is used with 32-bit PCI to push a 64-bit address in
two cycles. When off all DMA over >4GB is forced through an IOMMU or software bounce buffering.

nodac Forbid DAC mode, i.e. DMA >4GB.

panic Always panic when IOMMU overflows.

calgary Use the Calgary IOMMU if it is available

Early Console Flags, not sure if this exists in OSX



EX: earlyprintk=serial,ttyS0,115200 OR earlyprintk=serial,ttyS1,9600

The early console is useful when the kernel crashes before the normal console is initialized. It is not enabled by default because it has some cosmetic problems. Append keep to not disable it when the real console takes over. Only use vga or serial, not both. Currently only ttyS0 & ttyS1 are supported. Interaction with the standard serial driver is not very good. The VGA output is eventually overwritten by the real console.

Timing Flags

notsc = Don’t use the CPU time stamp counter to read the wall time. This can be used to work around timing problems on multiprocessor systems with not properly synchronized CPUs.

report_lost_ticks = Report when timer interrupts are lost because some code turned off interrupts for too long.



NUMBER can be:
0 = don’t use an NMI watchdog
1 = use the IO-APIC timer for the NMI watchdog
2 = use the local APIC for the NMI watchdog using a performance counter. Note This will use one performance counter & the local APIC’s performance vector.

When ,panic is specified panic when an NMI watchdog timeout occurs. This is useful when you use a ,panic=… timeout & need the box
quickly up again. EX nmi_watchdog=2,panic=20

nohpet = Don’t use the HPET timer.

Idle loop Flags

idle=poll = Don’t do power saving in the idle loop using HLT, yet poll for rescheduling event. This will make the CPUs eat a lot more power, yet may be useful to obtain slightly better performance in multiprocessor benchmarks. It moreover makes some profiling using performance counters more accurate. Please note that on systems with MONITOR/MWAIT support (like Intel EM64T CPUs) this option has no performance advantage over the normal idle loop. It may moreover interact badly with hyperthreading.

Rebooting flags, to control how the system reboots

reboot= b[ios] | t[riple] | k[bd] [, w[arm] | c[old]

bios = Use the CPU reboot vector for warm reset
warm = Don’t set the cold reboot flag
cold = Set the cold reboot flag
triple = Force a triple fault (init)
kbd = Use the keyboard controller. cold reset (default)

Using warm reset will be much faster especially on huge memory systems because the BIOS will not go through the memory check. Disadvantage is that not all hardware will be completely reinitialized on reboot so there may be boot problems on some systems.

reboot=force Don’t stop other CPUs on reboot. This can make reboot more reliable in some cases.

Non Executable Mappings flags


on Enable(default)
off Disable

Debugging Flags

oops=panic = Always panic on oopses. Default is to just kill the process, yet there is a small probability of deadlocking the machine.
This will moreover cause panics on machine check exceptions. Useful together with panic=30 to trigger a reboot.

kstack=N = Print N words from the kernel stack in oops dumps.

pagefaulttrace = Dump all page faults. Only useful for extreme debugging & will create a lot of output.

call_trace= [old|both|newfallback|new]

old: use old inexact backtracer
new: use new exact dwarf2 unwinder
both: print entries from both
newfallback: use new unwinder yet fall back to old if it gets stuck (default)

Example of some flags from above that can assist to obtain speedstep to work on a nonhpet AMD system with the ToH 9.2.0 SS kernel

apicpmtimer=1 notsc=1 nohpet=1 cpus=2

Tuesday, May 22, 2012

Create AD-HOC in debian on virtualbox when host internet sharing is disabled

For some reason my Windows Internet Sharing is disabled by system administrator, yet I still want to use ad-hoc for my mobile devices. So I decided to use virutalbox + linux to create a wireless ad-hoc server.

I chosed debian net installation disk because it is small & clean, I dont need any GUI evironment so I choosed a minimum installation with ssh server, added a port forward on port 22 in virtualbox so I can putty to 22 to access the virtual machine.

You need to install your wireless card driver on linux, this progress is pain, you can either download the linux driver from official website or check if it is ndiswrapper supported from

You will need to add the default module into the /etc/modprobe.d/blacklist.conf & loaded the module to /etc/modules after installation. I received a RTL8188CUS wireless card, it is tiny & luckly the official website provides the download of the driver for linux.

you prbably need to install build-essential & some packages first.

apt-get install build-essentialapt-get install dnsmasq wireless-tools

Edit /etc/sysctl.conf
unmment the line


Edit your /etc/network/interfaces

auto wlan0iface wlan0 inet staticaddress test_essidwireless-mode ad-hocwireless-key 1234567890 #this is a WEP password, for WPA please check herewireless-channel 11

Edit /etc/dnsmasq.conf

echo 1 > /proc/sys/net/ipv4/ip_forwardiptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE/etc/init.d/networking restartservice dnsmasq restart

Now try to connect the device to the ad-hoc, wireless on the fly

Saturday, May 19, 2012

Search and replace in Linux

Search in multiple files & replace in terminal

grep -lr -e 'oldword' * | xargs sed -i 's/oldword/newword/g'

Search & replace in vi

esc :%s/oldword/newword/g

Search & replace in emacs

C-s Search forwardC-r search backwardC-g return to where search started (if you are still in search mode)M-% query replaceSpace or y replace this occurenceDel or n don't replace. only replace this & exit (replace), replace & pause (resume with Space or y)! replace all following occurences^ back to previous matchRETURN or q quit replaceSearch/Replace with regular expressionsCharacters to use in regular expressions:^ beginning of line$ end of line. single char.* group or null of chars\< beginning of a word\> end of a word[] every char inside the backets (for example [a-z] means every small letter)M C-s RETURN search for regular expression forwardM C-r RETURN search for regular expression backwardM C-s incremental searchC-s repeat incremental searchM C-r incremental search backwardsC-r repeat backwardsM-x query-replace-regexp search & replace

Friday, May 18, 2012

How to create distributed/mirrored dynamic scripting website (Step - 4 Region detection and redirection)

Step four: Region detection & redirection
First of all, download the latest database

wget -O /path/IpToCountry.csv.gz

Create a table in your website database & import the data from the csv file

CREATE TABLE IF NOT EXISTS `ip2country` (  `start` int(10) unsigned NOT NULL DEFAULT '0',  `end` int(10) unsigned NOT NULL DEFAULT '0',  `registry` varchar(50) NOT NULL,  `assigned` varchar(50) NOT NULL,  `a2` char(2) NOT NULL DEFAULT '',  `a3` char(3) NOT NULL DEFAULT '',  `country` varchar(100) NOT NULL DEFAULT '',  PRIMARY KEY (`start`,`end`),  KEY `a2` (`a2`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;LOAD DATA LOCAL INFILE 'YOUR_PATH/IpToCountry.csv' INTO TABLE ip2country FIELDS TERMINATED BY ',' ENCLOSED BY '"'  LINES TERMINATED BY '\n';

Now just need add a few line of php code at the beginning of index.php file to handle the redirect.

//If the visitor is search engine spider, then do not redirect.function check_if_spider(){	$spiders = array('Googlebot', 'Yammybot', 'Openbot', 'Yahoo', 'Slurp', 'msnbot', 'ia_archiver', 'Lycos', 'Scooter', 'AltaVista', 'Teoma', 'Gigabot', 'Googlebot-Mobile');	foreach ($spiders as $spider)	{		if (eregi($spider, $_SERVER['HTTP_USER_AGENT']))		{			return TRUE;		}	}	return FALSE;}function checkip(){                if(check_if_spider()) return;		$client_ip=ip2long($_SERVER['REMOTE_ADDR']);		$rs = $db->query("select `a2` from `ip2c` where `start` <= $client_ip & `end` >= $client_ip");		$row = $db->fetch_array($rs);		//$row[0] will be the country code.                switch($row[0]){                    case 'US':                        //..301 Redirection                        header("HTTP/1.0 301 Moved Permanently");			header("Location:".$_SERVER['REQUEST_URI']);                     break;                    default:                       //... 301 Redirection                    break;                }	}}checkip();

How to create distributed/mirrored dynamic scripting website (Step - 3 Security)

Step three: Security
1. Firewall policy, use iptables to restrict specific ip & port.

2. When create replication user, use ‘user’@’ip’ rather than ‘user’@’%’

3. Use authorized keys for rsync so you can run rsync without a password. To create a ssh authoruzed key:
On source host

ssh-keygen -t rsa

Copy to destination host
Then execute the destination host

cat >> ~/.ssh/authorized_keys

Next: How to create distributed/mirrored dynamic scripting website (Step – 4 Region detection & redirection)

How to create distributed/mirrored dynamic scripting website (Step - 1 File synchronization)

This tutorial introduce a effortless way to build a distributed dynamic scripting website between Linux servers in two different zone.

To build up a dynamic website mirror for different zone/region/country without using Content Delivery Network, you should consider:

  1. File Synchronization
  2. Database Synchronization
  3. Security
  4. Region Detection And Redirection

Step one: File Synchronization

We will use rsync for file synchronization

rsync --progress --stats --compress --rsh=/usr/bin/ssh --recursive --times --perms --links --exclude "*bak" --exclude "*~" --exclude "config.php"  /var/www/path/* DESTINATION:/var/www/path/

It is recommended to create a batch file & run this command every 5 minutes, you may need to detect if rsync is already running, checkout here to find out how to detect if a process is already running. You may have muptiple hosts, yet the principle should be the same.

Next: How to create distributed/mirrored dynamic scripting website (Step – 2 Database synchronization)

How to create distributed/mirrored dynamic scripting website (Step - 2 Database synchronization)

Step two: Database Syncrhonization
This is the key of the dynamic website synchronization, I will use mysql server 5.x for example, if you are using a different database server, you will need to find out how to configure their replication.

1. Configure Master & Slave Server
Create a mysql user for replication


Edit my.cnf file [mysqld] section

2. Copy the database:
We need to lock table on master server before we dump the database


Write down the bin log file record & the postion & leave this connection open, then create a new ssh connection to the master server & dump the databse with:

#mysqldump -u root -p --database | gzip -c > all_database.sql.gz

Copy all_database.sql.gz to slave server & extract the files & import into slave database

source all_database.sql

An alternative way is to copy the content of folder /var/lib/mysql/data/* from master to slave.

Now you received exactly the same database on the salve server, then run SQL command on slave server

CHANGE MASTER TO master_host='MASTER_IP', master_user='user_rep', master_password='password',master_log_file='mysql-bin.XXXXXX',master_log_pos=XXXXX;START SLAVE;SHOW SLAVE STATUS; 

If you see Thread IO & Thread SQL are both running, then your database should be synchronized
Now go back to master server mysql session & run


Next: How to create distributed/mirrored dynamic scripting website (Step – 3 Security)

nginx rewrite rule for opencart

It took me a while to find out the solution, yet at last, I found it is pretty easy, the admin folder just need to take a bit extra care. This rewrite rule works moreover work with SEO url settings enabled.

Tested with opencart 1.5.13

   location / {        if ($host != '') {                rewrite ^/(.*)$$1 permanent;        }        try_files $uri @opencart;    }    location @opencart {        rewrite ^/(.+)$ /index.php?_route_=$1 last;    }        location /admin/ {        index index.php;        }    location ~* (\.(tpl|ini))$ {          deny all;    }

nginx rewrite rule for codeigniter

This is my nginx configuration file, which obtain the assist from

Here are the few things you MUST take care:
1. All rewrite rule & root must set in server scope, NO location \{} nor ~\.php${} !!!
2. In codeigniter application/config/config.php file

  • set $config[‘index_page’] = “”;
  • set $config[‘uri_protocol’] = “REQUEST_URI”;

Here is the rewrite rule that you need

    #page is my default controller, you will need to alter it to yours       if ($request_uri ~* ^(/page(/index)?|/index(.php)?)/?$)    {        rewrite ^(.*)$ / permanent;    }    # removes trailing "index" from all controllers    if ($request_uri ~* index/?$)    {        rewrite ^/(.*)/index/?$ /$1 permanent;    }    # removes trailing slashes (prevents SEO duplicate content issues)    if (!-d $request_filename)    {        rewrite ^/(.+)/$ /$1 permanent;    }    # removes access to "system" folder, moreover allows a "System.php" controller    if ($request_uri ~* ^/system)    {        rewrite ^/(.*)$ /index.php?/$1 last;        break;    }    # unless the request is for a valid file (image, js, css, etc.), send to bootstrap    if (!-e $request_filename)    {        rewrite ^/(.*)$ /index.php?/$1 last;        break;    }

For more nginx rewrite rule, please visit

Thursday, May 17, 2012

Delete all root mail

Here is the command to remove all root mail content

#cat /dev/null > /var/spool/mail/root

Check if a process is running in Linux

Here is a bash script that simply check if a process is running or not.

#!/bin/bashif [ "$(pidof process_name)" ] then  echo "process is running"else  echo "process is not running"fi

Monday, May 14, 2012

Run scp, wget Background

It is really effortless to run scp & wget in background mode.

#scp -r large_file #wget

Press CTRL + Z

and then type


Your process is now running in the background

Wednesday, May 2, 2012

Create Gradient with CSS

Here is an example of creating gradient with CSS

background: #f7f7f7; /* Old browsers */background: -moz-linear-gradient(top,  #f7f7f7 0%, #eff1f0 33%, #e3e3e3 73%, #dddddd 100%); /* FF3.6+ */background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f7f7f7), color-stop(33%,#eff1f0), color-stop(73%,#e3e3e3), color-stop(100%,#dddddd)); /* Chrome,Safari4+ */background: -webkit-linear-gradient(top,  #f7f7f7 0%,#eff1f0 33%,#e3e3e3 73%,#dddddd 100%); /* Chrome10+,Safari5.1+ */background: -o-linear-gradient(top,  #f7f7f7 0%,#eff1f0 33%,#e3e3e3 73%,#dddddd 100%); /* Opera 11.10+ */background: -ms-linear-gradient(top,  #f7f7f7 0%,#eff1f0 33%,#e3e3e3 73%,#dddddd 100%); /* IE10+ */background: linear-gradient(top,  #f7f7f7 0%,#eff1f0 33%,#e3e3e3 73%,#dddddd 100%); /* W3C */filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7f7f7', endColorstr='#dddddd',GradientType=0 ); /* IE6-9 */

Tuesday, April 24, 2012

USB Storage failed to mount after apt-get upgrade on sheevaplug

After using apt-get upgrade on the debian squeeze on the sheevaplug, I found the my external usb complex drive was not working anymore
#dmesg shows:

scsi_mod: Unknown symbol blk_get_queue

After did a little bit research, it seems need to execute command


and reboot my sheevaplug, the driver was back!!!

Friday, April 20, 2012

Mysql Change current database characterset

Assuming you have a database with default character set latin-1 & wish to convert it to utf-8, it is very simple to convert it without any external tool

1. Dump the database:

mysqldump -h localhost -u changeit -pchangeit --opt --compatible=mysql40 --default-character-set=latin1 database>database.sql

parameter –compatible=mysql40 is to dump the database without charset settings.

2. Create a database utf8 default:

CREATE DATABASE `database_new` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

3. Reimport the database

mysql -h localhost -u changeit -pchangeit --default-character-set=utf8 database_new < database.sql

Now you have received the utf8 character set database_new.

Friday, March 16, 2012

Install Apache + mod_svn_dev + SVN + user-friendly-svn on QNAP

The ipkg for QNAP can only install Apache web server & SVN server seperately, there is no way to load mod_svn_dav in order to obtain a web interface management system such as user-friendly-svn or svnmanager to work.

My soluction is recomplile Apache2, PHP5.4, Subversion 1.6.17, here is something you need to do before the compilation.

ipkg install grepipkg install sedipkg install gccipkg install binutilsipkg install makeipkg install autoconfipkg install automakeipkg install diffutilsipkg install m4ipkg install libxml2ipkg install fileipkg install perlipkg install libdbipkg install gawk

By default the QNAP uses the grep, sed, awk from busybox which is a bit out of date, so we installed their latest version from the ipkg, then you will need to update the link in /bin

mv /bin/awk /bin/awk_bakln -s /opt/bin/awkmv /bin/grep /bin/grep_bakln -s /opt/bin/grepmv /bin/sed /bin/sed_bakln -s /opt/bin/sed

NOTE: if you use ipkg install linuxutils again, you will re-do the link as the installation will roll back those command to busybox again.

Download icu-config, it is reuqired by php

wget xfvz icu4c-4_8_1_1-src.tgz./configure --prefix=/path_to_you_preferredmake && make install

Change the working directory to source code for apache2
configure with

./configure --prefix /path_to_you_preferred --enable-authz-host --enable-proxy --enable-proxy-http --enable-so --enable-rewrite --enable-vhost-alias  --enable-modules --enable-dav --enable-so --enable-dav=shared --enable-dav-fs=shared make && make install

Change the working directory to source code for subversion1.6.17

./configure --prefix=/path_to_you_preferred --with-apxs=/YOUR_APACHE_DIRECTORY/bin/apxs --with-apr=/YOUR_APACHE_DIRECTORY/bin/apr-1-config --with-apr-util=/YOUR_APACHE_DIRECTORY/bin/apu-1-config --with-berkeley-db=/opt/libmake & make install

Trouble shooting:
If you experienced with undefined symbol: REP_CACHE_DB_SQL
Then vi subversion/libsvn_fs_fs/rep-cache-db.h alter REP-CACHE-DB_SQL to REP_CACHE_DB_SQL.
This bug was something wrong when generate rep-cache-db.h

Change the working directory to source code for PHP5.4


./configure --prefix=/path_to_you_preferred --with-icu-dir=/YOUR_ICU_DIRECTORY/icu4 --with-apxs2=/share/YOUR_APACHE_DIRECTORY/bin/apxs --with-mysql=/mnt/ext/opt/mysql --with-pdo-mysql=/mnt/ext/opt/mysql --libdir=/share/MD0_DATA/.qpkg/Optware/lib --includedir=/share/MD0_DATA/.qpkg/Optware/includemake && make installvi /YOUR_APACHE_DIRECTORY/conf/httpd.conf

Make sure you have following modules loaded

LoadModule dav_module     modules/mod_dav.soLoadModule dav_svn_module     modules/mod_dav_svn.soLoadModule authz_svn_module   modules/mod_authz_svn.soLoadModule php5_module        modules/

AddType application/x-httpd-php-custom .php

    SetHandler application/x-httpd-php

change your user group to in httpd.conf

create an alias for usvn

Alias /usvn /USVN_FOLDER/public    Options +SymLinksIfOwnerMatch    AllowOverride All    Order allow,deny    Allow from all

Follow the installation guide usvn to complete the installation.

Sunday, February 26, 2012

Attributes related to WinForms Designer

  1. BrowsableAttribute
    This attribute tells designer, whether the associated property should be displayed.
  2. DefaultEventAttribute
    This attribute tells designer, if double clicked a component, which event it should generate code for.
  3. DefaultValueAttribute
    This attribute indicates the default value for the property. If you donate a value not equals default value, it will be displayed in bold.
  4. DesignerCategoryAttribute
    This attribute tells designer it belongs to what category.
  5. DesignerSerializationVisibilityAttribute
    This attribute tells designer how to serialize the associated property.
  6. DesignTimeVisibleAttribute
    This attribute tells designer whether the component should be displayed in toolbox.

To be continued…

Thursday, February 23, 2012

How to use default parameter in C# 2.0 & 3.5

For example, I need a method like this:

public void InitData(int index, object value, bool required = false) {}

I can write it as:

using System.Runtime.InteropServices;public void InitData(int index, object value, [Optional, DefaultParameterValue(false)] bool required) {}

The attribute Optional tells compiler that the parameter required has default value. And the attribute DefaultParameterValue(false) tells compiler what is the default value.

Very simple. Isn’t it?

Sunday, January 29, 2012

WPF in action: Dynamically set style for control

For example, I have a xaml like this:

<TabItem Header="Tab1" Style="{DynamicResource TabItemWithButton}">

I want create a new tab dynamically, & set style to “TabItemWithButton”, I will use this code:

newTab.SetResourceReference( TabItem.StyleProperty, "TabItemWithButton" );


Actually, you can use SetResourceReference method to set many dependency properties, explore it!