May 19, 2010

Add color to your linux console program

You can add color to your linux console print outs, such as usage.


#define CSI "\x1B\x5B"
main(){
printf("%s1;31m This is color text %s0m\n",CSI,CSI);
}

shell:
red text:
printf "\x1b\x5b1;31m Ignoring callcatcher \x1b\x5b0m\n";

green text:
printf "\x1b\x5b2;31m Ignoring callcatcher \x1b\x5b0m\n";

Details:
\x1B is Escape Char, \x5B is '['. They form the control string indicator.

1;31 are two commands
1 means bold color
31-37 are the colors

m: set display attributes command

0m: reset to normal display

color code list:
   Black      0;30       Dark Gray    1;30
  Red        0;31       Bold Red     1;31
  Green      0;32       Bold Green   1;32
  Yellow     0;33       Bold Yellow  1;33
  Blue       0;34       Bold Blue    1;34
  Purple     0;35       Bold Purple  1;35
  Cyan       0;36       Bold Cyan    1;36

  Light Gray 0;37       White        1;37


Other commands (from Wikipedia)
Code Effect Note
0 Reset / Normal all attributes off
1 Bright (increased intensity) or Bold
2 Faint (decreased intensity) not widely supported
3 Italic: on not widely supported. Sometimes treated as inverse.
4 Underline: Single
5 Blink: Slow less than 150 per minute
6 Blink: Rapid MS-DOS ANSI.SYS; 150 per minute or more
7 Image: Negative inverse or reverse; swap foreground and background
8 Conceal not widely supported
9 Crossed-out Characters legible, but marked for deletion.
10 Primary(default) font
11-19 n-th alternate font Select the n-th alternate font. 14 being the fourth alternate font, up to 19 being the 9th alternate font.
20 Fraktur
21 Underline: Double not widely supported
22 Normal color or intensity neither bright, bold nor faint
23 Not italic, not Fraktur
24 Underline: None not singly or doubly underlined
25 Blink: off
26 Reserved
27 Image: Positive
28 Reveal conceal off
29 Not crossed out
30–37 Set text color 3x, where x is from the color table below
38 Reserved
39 Default text color implementation defined (according to standard)
40–47 Set background color 4x, where x is from the color table below
48 Reserved
49 Default background color implementation defined (according to standard)
50 Reserved
51 Framed
52 Encircled
53 Overlined
54 Not framed or encircled
55 Not overlined
56-59 Reserved
60 ideogram underline or right side line
61 ideogram double underline or double line on the right side
62 ideogram overline or left side line
63 ideogram double overline or double line on the left side
64 ideogram stress marking
90–99 Set foreground color, high intensity aixterm (not in standard)
100–109 Set background color, high intensity aixterm (not in standard)

May 18, 2010

Unofficial Smartq V5/V7 Linux Development Guide

This is a backup of the original doc at: http://docs.google.com/View?id=ddtx8wkh_18g39zskpm

Unofficial Smartq V5/V7 Linux Development Guide


This guide describes how to compile your own linux kernel and how to create SmartqV firmware image for flashing the V5 or V7.
You need a working linux host for development, I'm using Ubuntu.

  1. Download the SmartqV SDK: http://rghost.net/980682
  2. Extract SDK to your working directory: tar -xvf SmartqV_SDK.tar.gz
  3. Install ARM toolchain:
    • Extract armv6_codesourcery.tar.bz2 file into /opt directory: tar –xvf armv6_codesourcery.tar.bz2
    • You should see /opt/armv6/... directory created.
  1. Go back to SmartqV_SDK directory and extract the kernel:
  1. Extract fw-utils:
    • tar -xvf fw-utils.tar.bz2
  1. Compiling the kernel:
    • cd mer-smartq-mer-smartq-kernel
  • Create default configuration: make SmartV7_defconfig for V7 or make SmartV5_defconfig for V5.
  • Run ./make_zImage_rootfs.sh and you can find a file named linux.rom under ../fw-utils directory.
  • make modules && make modules_install INSTALL_MOD_PATH=`pwd`/module-collection
    This pulls the generated modules into the ./module-collection directory, which can then be easily transferred with the kernel.
  1. Creating firmware image:
    • cd ../fw-utils
    • For V7: ./compress.v tcboot.V7 linux.rom 0 && mv SmartQV5 SmartQV7
    • For V5: ./compress.v tcboot.V5 linux.rom 0. The tcboot.V5 is not included in SDK, but you can extract it from official V5 image (see below).
    • This will create SmartQV5 or SmartQV7 firmware image.
  1. Copy the image to SD card and flash as usual.
  2. Notes: The firmware image will update only the bootloader and kernel image.
    You can create a full image including rootfs and homefs using compress.v utility.
    Use uncompress utility to extract newest bootloader from official firmware. Extracted files saved in /tmp directory.

Enjoy!

May 7, 2010

pause/resume a linux process

To pause:

kill -STOP pid

To Resume:

kill -CONT pid

Works perfectly.

May 4, 2010

Simple NAT for Internet sharing

You need a Linux machine (or virtual machine running Linux, or Colinux) to do this:


#enable routing
echo 1 > /proc/sys/net/ipv4/ip_forward

#flush iptable
iptables -t nat -F

#enable DNAT (also known as IP masquerading)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

#enable port forwarding
iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 2401 -j DNAT --to 192.168.16.66:2401
iptables -t nat -A PREROUTING -i eth1 -p ALL --dport 82:88 -j DNAT --to 192.168.16.66:5000:5006

April 26, 2010

A good Javascript Calculator

http://cc.joensuu.fi/~tniemi/tools/calc.html

April 19, 2010

rpl_malloc error with configure

If you get a problem about an undefined reference to rpl_malloc, you probably need to do:
$ export ac_cv_func_malloc_0_nonnull=yes
before running ./configure ...

March 19, 2010

Serial Terminal Emulator on Linux/Ubuntu

Minicom, PuTTY, picocom, gtkterm, or cutecom

Console based:

1. minicom: the grand master and the one most people use
2. picocom: a mini minicom
3. some others not very well used such as: microcom, nanocom

GUI based:
1. cutecom (Qt based), able to dispaly and send HEX
2. gtkterm (GTK based, last release 2005), able to set serial port pin, and read pin status, and display and send HEX
3. PUTTY for linux (GTK based)



I recommend minicom, picocom and gtkterm.

March 7, 2010

Sichua Earthquake and Three Gorges Dam

From the following article, this Dam most likely have contributed to the Sichua earthquake. You use use Google Translate to read it in English.

http://www.zaobao.com/special/feature/pages/feature080706.shtml

  中国地震界制定了可能产生水库诱发地震的七项定性标准:①坝高于100米,库容大约10亿立方米;②库坝区有活动断裂;③库坝区为中新生代断陷 盆地或其边缘,近代升降活动明显;④深部存在重力梯度异常;⑤岩体深部张裂隙发育,透水性强;⑥库坝区曾有地震发生;⑦库坝区有温泉。上述七项,符合数越 多,该水库蓄水后诱发地震的可能性就越大。

  范晓说:“紫坪铺水库符合了上述七项标准中的前六项。”惟独没有的是,紫坪铺附近没有温泉。

  他根据本身进行的调查进一步指出,紫坪铺水库所处的地质结构位置相当令人担忧。“水库大坝下距龙门山主边界断裂在地表的出露迹线仅2公里,库尾淹没线上距龙门山中央断裂地表出露迹线仅约500米,库区还有与上述断裂平行的密集断层群通过。”


March 5, 2010

ctags for matlab on Windows

1. create a environment variable called HOME, and pointed it to whatever directory you like. On vista, I pointed to c:\Users\MYNAME

2. create file ctags.cnf under HOME directory you just pointed to with the following 3 lines:

--langdef=matlab
--langmap=matlab:.m
--regex-matlab=/^function([] A-Za-z0-9,_[]+=[ ]?|[ ]+)([^.(]+).*$/\2/f,function/

And done. Now you can run Ctags -R * on top of your project to create matlab tags file.

a short guide to enable samba server on Ubuntu

1. sudo apt-get install samba
2. sudo vi /etc/samba/smb.conf, look for [homes] and uncomment the following lines starting with [homes], change browserable to yes and readonly to no
[homes]
comment = Home Directories
browseable = yes

# By default, the home directories are exported read-only. Change the
# next parameter to 'no' if you want to be able to write to them.
read only = no

3. give samba user a password by doing:
sudo  smbpasswd -a USERNAME

4. reload samba conf file by doing:
sudo /etc/init.d/samba reload
Done.

On Windows Explorer, type \\UBUNTU_IP_ADDRESS\USERNAME to see the share.

ssh file system mount

1. sudo adduser USER fuse
2. mkdir destdir
3. sshfs USER@REMOTEHOST:. destdir

done.

March 4, 2010

Setup Ubuntu to be a remote desktop server

http://ubuntuwiki.net/index.php/Xrdp,_installing

1. sudo apt-get install xrdp

2. run as your user (not root) this:
"vncserver :1

3. vi /etc/xrdp/xrdp.ini and make sure you have this section. You can have one session for each user.

[xrdp1]
name=Your Name
lib=libvnc.so
username=na
password=ask
ip=127.0.0.1
port=5901

4. comment any line about twm or xterm and add this line to your local ~/.vnc/xstartup file:
#vncconfig -iconic &
#xterm -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &
#twm &
/etc/X11/Xsession

5. restart xrdp sevice: /etc/initrd/xrdp restart

6. vi /etc/rc.local to add this line for each user (vncserver :number should be different for each user):
su USER1 -c "cd && vncserver :1"
su USER2 -c "cd && vncserver :2"



done




February 17, 2010

List Debian installed packages by size

dpkg-query -W --showformat='${Installed-Size;10}\t${Package}\n' | sort -k1,1n

size is KBytes

February 12, 2010

Fix Mic for Skype on T61 Ubuntu 9.10

# In Skype’s Options / Sound Devices, change “Sound In” to the raw hardware device; mine was “HDA Intel (hw:Intel:0)”, but it will take some experimentation and some test calls to figure out the correct setting. Do NOT set it to “pulse”; there is a known bug in Ubuntu’s implementation of PulseAudio that causes delays of many seconds on microphone input.

# Also in Skype’s Options / Sound Devices, set both “Sound Out” and “Ringing” to “pulse”.

# Also in Skype’s Options / Sound Devices, it may be necessary to uncheck “Allow Skype to automatically adjust my mixer levels”.

# Right click on the task bar’s volume control (the speaker icon), and select Open Volume Control. Hit the Preferences button, and add the following two controls: Capture (Recording) and Input Source (Options). Then in the Volume Control dialog, in the Recording tab, bring up the Capture level to near full, and in the Options tab, set the Input Source to Internal Mic. On Xubuntu (XFCE), use the Mixer, and "select controls", and make sure you select the two "Input"s.

This should fix it. No reboot needed. I think the last line is the actual fix.

February 11, 2010

Two steps to install bootloader on your USB key

You can also use this to boot into Ubuntu Wubi installation while having your windows in Hibernation!

Install MBR on the USB stick


On windows:
  1. download grubutil for windows then extract all and run grubinst_gui.exe
  2. Select from the menu 'Disk' and click 'Disk Refresh' then choose your usb device.
  3. Select 'Part List Refresh' and choose 'Whole Disk (MBR)'
  4. Click 'Install', and that's it.
On Linux:
- Download the source of grubinst from SourceForge http://downloads.sourceforge.net/gru...7&big_mirror=0
- Uncompress the zip file to some directory (in your home partition for example)
- Open a terminal
- Go to that directory
- Compile grubinst using
Code:
make -f Makefile.lnx
- Get the proper device name of you USB key. It is IMPORTANT you do not do mistakes here otherwise you will destroy you hard disk regular MBR. So for example, type
Code:
sudo fdisk -l
and try to see how is your USB key named. For example, mine is /dev/sdc
- In case we got wrong (2 precautions), we are going to save the MBR we will overwrite, so that we should be able to put it back if there was a problem. So type:
Code:
sudo ./grubinst --save-mbr=USB.mbr /dev/sdX
(replace X by the proper letter of your USB)
- Now the MBR of you key has been saved next to grusint program.
- We can now write Grub4DOS MBR to the key (always replace X by relevant letter):
Code:
sudo ./grubinst /dev/sdX


Install a bootloader on a USB stick

To install wubi loader:
- Copy wubildr to the root of your key, and rename it grldr
- Make a ubuntu directory to the root of your key
- From your harddrive, copy /ubuntu/winboot to the /ubuntu on the key, so that you usb key will have the directory /ubuntu/winboot.
done.

To install regular grub4dos:

  1. download latest grub4dos here: http://download.gna.org/grub4dos/ and extract grldr and menu.lst to your usb flashdrive top directory.
  2. edit menu.1st as you wish.

Helpful links:
1. http://it.dennyhalim.com/2009/02/install-grub4dos-make-usb-bootable-from.html
2. http://ubuntuforums.org/showpost.php?p=5966083&postcount=7

Enable Windows Vista Hibernation

run "cmd" as administrator, and run the following command:

powercfg /hibernate on

February 9, 2010

Merge PDF file, FREE and EASY, NO acrobat needed

  1. Downloand pdftk at http://www.accesspdf.com/pdftk/, unzip it and put the pdftk.exe to c:\windows\system32
  2. Open cmd window by go to "Start -> Run, type cmd"
  3. On Vista and Windows 7, do "cd %APPDATA%\Microsoft\Windows\SendTo", On Windows XP, do "cd c:\documents and settings\YOUR_UESER_ID\sendto"
  4. use notepad to create a text file named MERGE-PDF.bat with the following one line in the file: pdftk %1 %2 %3 %4 %5 %6 %7 %8 %9 cat output pdftk-output.pdf
  5. done.
Now to merge two or multiple pdf files, simply select them in Windows File Exploerer, and right click, then "send to -> MERGE-PDF.bat", the new merged file will be called "pdftk-output.pdf" in your folder.

Now where is my beer?

January 11, 2010

Parse HTML

Use this link to parse your code so that it can be pasted on blogger.

http://www.blogcrowds.com/resources/parse_html.php

Mini2440 download program on Linux

To download image to the mini2440 bootloader, the manual requires to install a Windows USB Driver, and a DNW2.exe program. I did not want to install some unknown EXE program on my computer. Fortunately, core_rui wrote a simple Linux program to do the whole trick. No driver needed. I simply LOVE the simplicity of this. You can run this program in a Vmware virtual machine (with USB 2.0 emulation enabled). Note this program uses libusb. So to compile it you need to install libusb-dev on your computer.


/* dnw2 linux main file. This depends on libusb.
*
* Author: Fox <hulifox008@163.com>
* License: GPL
*
*/



#include <stdio.h>
#include <usb.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define QQ2440_SECBULK_IDVENDOR 0x5345
#define QQ2440_SECBULK_IDPRODUCT 0x1234


struct usb_dev_handle * open_port()
{
struct usb_bus *busses, *bus;

usb_init();
usb_find_busses();
usb_find_devices();

busses = usb_get_busses();
for(bus=busses;bus;bus=bus->next)
{
struct usb_device *dev;
for(dev=bus->devices;dev;dev=dev->next)
{
if( QQ2440_SECBULK_IDVENDOR==dev->descriptor.idVendor
&& QQ2440_SECBULK_IDPRODUCT==dev->descriptor.idProduct)
{
printf("Target usb device found!n");
struct usb_dev_handle *hdev = usb_open(dev);
if(!hdev)
{
perror("Cannot open device");
}
else
{
if(0!=usb_claim_interface(hdev, 0))
{
perror("Cannot claim interface");
usb_close(hdev);
hdev = NULL;
}
}
return hdev;
}
}
}

printf("Target usb device not found!n");

return NULL;
}

void usage()
{
printf("Usage: dnw2 <file>nn");
}

unsigned char* prepare_write_buf(char *filename, unsigned int *len)
{
unsigned char *write_buf = NULL;
struct stat fs;

int fd = open(filename, O_RDONLY);
if(-1==fd)
{
perror("Cannot open file");
return NULL;
}
if(-1==fstat(fd, &fs))
{
perror("Cannot get file size");
goto error;
}
write_buf = (unsigned char*)malloc(fs.st_size+10);
if(NULL==write_buf)
{
perror("malloc failed");
goto error;
}

if(fs.st_size != read(fd, write_buf+8, fs.st_size))
{
perror("Reading file failed");
goto error;
}

printf("Filename : %sn", filename);
printf("Filesize : %d bytesn", fs.st_size);

*((u_int32_t*)write_buf) = 0x30000000; //download address
*((u_int32_t*)write_buf+1) = fs.st_size + 10; //download size;

*len = fs.st_size + 10;
return write_buf;

error:
if(fd!=-1) close(fd);
if(NULL!=write_buf) free(write_buf);
fs.st_size = 0;
return NULL;

}

int main(int argc, char *argv[])
{
if(2!=argc)
{
usage();
return 1;
}

struct usb_dev_handle *hdev = open_port();
if(!hdev)
{
return 1;
}

unsigned int len = 0;
unsigned char* write_buf = prepare_write_buf(argv[1], &len);
if(NULL==write_buf) return 1;

unsigned int remain = len;
unsigned int towrite;
printf("Writing data ...n");
while(remain)
{
towrite = remain>512 ? 512 : remain;
if(towrite != usb_bulk_write(hdev, 0x03, write_buf+(len-remain), towrite, 3000))
{
perror("usb_bulk_write failed");
break;
}
remain-=towrite;
printf("r%d%t %d bytes ", (len-remain)*100/len, len-remain);
fflush(stdout);
}
if(0==remain) printf("Done!n");
return 0;
}


To compile: gcc dnw2.c -o dnw2 -lusb

January 8, 2010

Troubleshooting: X connection to localhost:10.0 broken (explicit kill or server shutdown).

If you remote connect to UNIX from Windows, then it's likely you will bump into this error message at least once in your lifetime:

X connection to localhost:10.0 broken (explicit kill or server shutdown).

This error messages occurs when you try to execute an X Window graphics user interface software, but you haven't started the X Windows display software on your Windows machine.

The X Window display server that I prefer to use on Windows is Xming 6.9.0.31. It's available on SourceForge and it's low-maintenance. If you haven't gotten a X Window display server software, you might give it a try. After starting Xming, you should not have this problem again.

However, if this problem does occur when you have Xming running, it's probably because you did not enable X11 forwarding in PuTTY, or your ssh software.

Chieh Cheng
Sun, 07 Jun 2009 18:35:41 +0000

Checklist for using Xming through a tunneled Putty session.

Putty:
* In the Connection->SSH->X11 panel, set the Enable X11 forwarding checkbox.
* (optional) In the same panel, enter "localhost:0" as the X display location. This redirects forwarded X traffic to display number 0. Match the Xming Display number, set below.
* Generally, MIT-Magic-Cookie-1 (set by default) is the most common authentication protocol. This will be added/updated in your .Xauthority file after a successful login for each display (one per Putty session).

Xming:
* In the Select display settings panel, set the Display number to 0. The IP port number used is 6000 + this number, so anything other than 0 will affect the display number used by X clients.
* In the same panel, if you want to connect directly from the remote client to the Xming server (not through Putty's X Forwarding), you should probably check the No Access Control box or your connection will be refused.

Remote system:
* Verify your SSH configuration allows X11 forwarding. In OpenSSH, the .ssh/config file should contain the entry "ForwardX11 yes".
* Your DISPLAY environment variable will be set automatically by Putty upon successful login. This will be "localhost:10.0" for the first session when the remote system's SSH daemon X11DisplayOffset is set to 10 (default). This display number will correspond to a TCP port that is listening on 6000 + display number, e.g. 6010. Use the command "netstat -an | grep -i listen" to see the ports on a Unix/Linux/Solaris box.
* If you "su" or "sudo" to a different user after login, you must merge the .Xauthority entry for the display associated with your session into the .Xauthority file of the new user. The DISPLAY environment variable should be set and exported the same as for the login user, for convenience. Otherwise, the X applications you lanuch with the new user will not have the authority to connect to your X server.

Windows:

* For the "localhost" part of the X display location to be converted to the correct IP address, your hosts file (%SYSTEMROOT%\System32\drivers\etc\hosts) must contain the entry "127.0.0.1 localhost".

* IMPORTANT: If you are using Windows Vista, the hosts file does not contain this entry by default. Instead, there is a "::1 localhost", which is for IPv6 instead of IPv4. Comment out/delete that entry and add the entry " 127.0.0.1 localhost". This causes the "X connection to localhost:10.0 broken (explicit kill or server shutdown)" error to appear when you try to launch an X client application.

* If you use a firewall, make sure that Putty SSH is allowed through it. If you can't establish a login session with Putty, X applications aren't going to work, either.