Monthly Archives: December 2008

heredoc

Almost all scripting languages support heredoc, include bash, perl, python, ruby, php and tcl, and more.

Bash

<< and delimiting identifer like EOF.

cat <<EOF
working dir is $PWD
working dir is `pwd`
EOF

Output:

working dir is /home/user
working dir is /home/user

By default, variables and commands in backticks are evaluated. This can disabledby setting the label in the command line in single or double quotes:

cat <<"EOF"
working dir is $PWD
working dir is `pwd`
EOF
 
cat <<'EOF'
working dir is $PWD
working dir is `pwd`
EOF

Output:

working dir is $PWD
working dir is `pwd`
working dir is $PWD
working dir is `pwd`

Perl

Like Bash, and using double quotes around the tag allows variables to be interpolated, using single quotes doesn't and using the tag without either behaves like double quotes.

my var="World"
 
# without quotes
print <<EOF;
Hello $var
EOF
 
# double quotes
print <<"EOF";
Hello $var
EOF
 
#single qutoes:
print <<EOF;
Hello $var
EOF

The output:

Hello World
Hello World
Hello $var

Python

Python supports heredocs delimited by single or double quotes repeated three times (i.e. ''' or """).

var = 'World'
 
print("""
Hello %(var)s
""" % locals())
 
print('''
Hello %(var)s
''' % locals())

Output:

Hello World
Hello World

Ruby

Ruby's grammer is from Bash and Perl.

now = Time.now
 
puts <<EOF
Hello #{now.hour}
EOF
 
puts <<"EOF"
Hello #{now.hour}
EOF
 
puts <<'EOF'
Hello #{now.hour}
EOF

Output:

Hello World
Hello World
Hello #{now.hour}

PHP

<?php
var = World;
 
// heredoc
echo <<<EOF
Hello $var
EOF;
 
// nowdoc, need php 5.3
echo <<<'EOF'
Hello $var
EOF;
?>

Output:

Hello World
Hello $var

Tcl

Tcl's ordinary string syntaxes already allow embedded newlines and preserve indentation.

set var "World"
 
puts "
Hello $var
"
 
puts {
Hello $var
}

Output:

Hello World
Hello $var

References

http://en.wikipedia.org/wiki/Heredoc
http://php.net/manual/en/language.types.string.php

Leave a comment

git svn

svn with git.

1 Import

$ git svn clone --username yourname -T trunk -s https://u-prj.googlecode.com/svn

2 Develop

$ git add/rm FILE
$ git commit -a
$ git reset --hard HEAD^
$ git checkout HEAD~5 FILE

3 Update

$ git svn rebase # svn update

4 Export

$ git svn dcommint # svn commit

src

Leave a comment

15 Exercises

往后学习一门新语言时,做做下面15个练习。当然,如果是编程语言,之前要知道如何编译与运行源程序;如果是脚本语言,首先要知道如何运行它。至于IDE,vim和emacs都是最好的IDE了。

不需要读完整个手册,才能开始写程序,读个十来页,知道基本了,就找个refcard,然后参照refcard开始做下面的练习。

(1) Display series of numbers (1,2,3,4, 5….etc) in an infinite loop. The program should quit if someone hits a specific key (Say ESCAPE key).

(2) Fibonacci series, swapping two variables, finding maximum/minimum among a list of numbers.

(3) Accepting series of numbers, strings from keyboard and sorting them ascending, descending order.

(4) Reynolds number is calculated using formula (D*v*rho)/mu Where D = Diameter, V= velocity, rho = density mu = viscosity

Write a program that will accept all values in appropriate units (Don’t worry about unit conversion)

If number is < 2100, display Laminar flow,
If it.s between 2100 and 4000 display 'Transient flow' and
if more than '4000', display 'Turbulent Flow' (If, else, then...)

(5) Modify the above program such that it will ask for 'Do you want to calculate again (y/n), if you say 'y', it'll again ask the parameters. If 'n', it'll exit. (Do while loop)

While running the program give value mu = 0. See what happens. Does it give 'DIVIDE BY ZERO' error? Does it give 'Segmentation fault..core dump?'. How to handle this situation. Is there something built in the language itself? (Exception Handling)

(6) Scientific calculator supporting addition, subtraction, multiplication, division, square-root, square, cube, sin, cos, tan, Factorial, inverse, modulus

(7) Printing output in different formats (say rounding up to 5 decimal places, truncating after 4 decimal places, padding zeros to the right and left, right and left justification)(Input output operations)

(8) Open a text file and convert it into HTML file. (File operations/Strings)

(9) Time and Date : Get system time and convert it in different formats 'DD-MON-YYYY', 'mm-dd-yyyy', 'dd/mm/yy' etc.

(10) Create files with date and time stamp appended to the name

(11) Input is HTML table, Remove all tags and put data in a comma/tab separated file.

(12) Extract uppercase words from a file, extract unique words

(13) Implement word wrapping feature (Observe how word wrap works in windows 'notepad')

(14) Adding/removing items in the beginning, middle and end of the array.

(15) Are these features supported by your language: Operator overloading, virtual functions, references, pointers etc.

原文中文

Leave a comment

收到OpenSolaris 2008.11光盘

OpenSolaris 2008.11 在2008年12月1日才正式发布,我12月24号收到unix-center从北京挂号邮寄过来的光盘。

马上进livecd里玩了下,很是喜欢。它是unix系的,跟linux的目录结构不大相同。又因为它是SUN家的,Java环境有预装,GNU工具都在一个目录下。

我喜欢的是*nix系统,不仅仅是Linux,更不仅仅是Ubuntu。Ubuntu是Linux几百个发行版中最流行一个,Linux是数十种*nix系统中最流行的一个。目前为止,我还只用Linux系统做桌面,服务器端用过FreeBSD,Unix-Center里体验过Solaris 10。

OpenSolaris有而Linux无的特性,最重要的三个是ZFS、DTrace、SMF。ZFS和DTrace,我闻大名久矣。SMF(Service Management Facility)是一种管理*nix下服务的创新技术,似乎也很不错。

经常有用户错误地认为Unix-Center.Net是一个Sun 公司的平台。事实上,Unix-Center.Net完全是我个人创建网站,包括服务器、机柜和带宽等等运营费用都是我个人支付的。由于我在Sun 公司工作的关系,目前Unix-Center.Net的内容偏向于Sun 公司的产品和技术。出于同样的理由,Unix-Center.Net有一些针对Sun 公司产品和技术的推广活动。我欢迎任何单位和个人在Unix-Center.Net这个平台上提供与其他Unix/Linux相关内容。

这里看到,unix-center.net竟然不是sun的,而是蒋清野个人提供的服务,令人不敢相信。一直以为是sun的,但鉴于蒋是sun的雇员,uc跟sun关系仍是非常密切的。

Leave a comment

Bash Special Parameters

这些古怪的符号,其实都是有含义有规律的。弄懂它们一点都不难,只需要写点代码,运行一下就知道了。perl 的特殊变量更多,perldoc perlvar.

#/bin/bash
 
# http://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html
 
# run it like 
# ./spec_para.sh 1 2 3
 
# Parameters
echo $_ # absolute pathname
echo $0 # ./spec_para.sh
echo $1 # 1
echo $2 # 2
echo $3 # 3
 
# $* and $@ is differents
echo $@ # 1 2 3 ("$1" "$2" "$3")
echo $* # 1 2 3 ("$1c$2c$3")
# c is the first character of the value of the IFS variable. If IFS is
# unset, the parameters are separated by spaces. If IFS is null, the
# parameters are joined without intervening separators. 
 
echo $# # 3 ( number of positional parameters in decimal )
 
echo $? # exit status of the most recently executed foreground pipeline 
echo $$ # process ID of the shell
echo $! # process ID of the most recently executed background command
 
echo $- # current option flags
Leave a comment

customize ubuntu for eee pc

# http://www.array.org/ubuntu/setup-intrepid.html
# to enable wireless network, install a kernel customized for eee pc
wget http://www.array.org/ubuntu/array-intrepid.list
sudo mv -v array-intrepid.list /etc/apt/sources.list.d/
wget http://www.array.org/ubuntu/array-apt-key.asc
sudo apt-key add array-apt-key.asc
sudo apt-get update
 
sudo apt-get install linux-eeepc linux-headers-eeepc
 
# http://forum.eeeuser.com/viewtopic.php?id=49081
# install ACPI scipts, for wifi toggle Fn-Keys and more
wget http://www.informatik.uni-bremen.de/~elmurato/EeePC/Intrepid_ACPI_scripts-EeePC.tar.gz
tar xfvz Intrepid_ACPI_scripts-EeePC_900A_901_1000.tar.gz
cd Intrepid_ACPI_scripts-EeePC_900A_901_1000/
chmod +x acpi-scripts.sh
sudo ./acpi-scripts.sh install
 
# https://help.ubuntu.com/community/EeePC/Using
# font size
gconftool-2 --set /apps/nautilus/preferences/desktop_font --type string "Sans 8"
gconftool-2 --set /desktop/gnome/interface/document_font_name --type string "Sans 8"
gconftool-2 --set /desktop/gnome/interface/font_name --type string "Sans 8"
gconftool-2 --set /apps/metacity/general/titlebar_font --type string "Sans Bold 8"
gconftool-2 --set /desktop/gnome/interface/monospace_font_name --type string "Monospace 8"
 
# alt-f11 fullscreen
gconftool-2 --set /apps/metacity/window_keybindings/toggle_fullscreen --type string "<Alt>F11"
 
# toolbar icons
gconftool-2 --set /desktop/gnome/interface/toolbar_style --type string "icons"
 
# menu icons
gconftool-2 --set /desktop/gnome/interface/menus_have_icons --type bool 0
 
# mixer mute key
gconftool-2 --set /desktop/gnome/sound/default_mixer_tracks --type list --list-type string "[PCM]"
 
# panel
gconftool-2 --set /apps/panel/toplevels/top_panel_screen0/size --type integer 19
gconftool-2 --set /apps/panel/toplevels/bottom_panel_screen0/size --type integer 19
 
# battery warning
gconftool-2 --set /apps/gnome-power-manager/notify/low_capacity --type bool 0
Leave a comment

disable post revision

I hate wordpress’ post revision feature, its only function is to waste my database storage. Every time I save or modify a post, it’ll store a full copy of that post to my database. I don’t know why need to do that, that’s a personal blog, not a wiki. The funny thing is that I can’t find a option in admin dashboard to disable it, the writer of wordpress maybe think everybody need that feature, they are wrong!

Find a way to disable it, http://wordpress.org/support/topic/175886.

adding to wp-config:

define ('WP_POST_REVISIONS', 0);  // disable post revisions feature
define('AUTOSAVE_INTERVAL', 600); // auto save interval time

or install a plugin:
http://exper.3drecursions.com/2008/07/25/disable-revisions-and-autosave-plugin/

clean-up SQL:

# can't delete wp_postmeta and wp_term_relationships table
DELETE FROM wp-posts WHERE post_type='revision';
 
# delete all post revision data
DELETE a,b,c  
FROM wp_posts a  
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)  
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)  
WHERE a.post_type = 'revision';
Leave a comment

bash choping strings

#!/bin/bash
 
# http://www.ibm.com/developerworks/library/l-bash.html
# how to chopping strings?
 
# basename and dirname
path='/usr/local/share/doc/foo.txt'
 
basename $path   # foo.txt
echo ${path##*/} # foo.txt
 
dirname $path    # /usr/local/share/doc
echo ${path%/*}  # /usr/local/share/doc
 
# professional chopping
var="somestring"
 
echo ${var#*s}  # omestring
echo ${var##*s} # tring
 
echo ${var%s*}  # some
echo ${var%%s*} # null!
 
echo ${var%%ng*} # somestri
echo ${var%%ing} # somestr
 
echo ${var:0:4}  # some

Search and replace on variables:

var="somestring"
echo ${var/some/any} # anystring
Leave a comment

ubuntu优化

1 建立开机索引 profile

2 停用开机画面 splash

3 dash取代sh dpkg-reconfigure dash

4 并行启动程序 /etc/init.d/rc CONCURRENCY=shell

5 降低swap写入

  echo "vm.swappiness = 10" >> /etc/sysctl.conf
  sysctl -p

6 减少console数目

  cd /etc/event.d
  rename 's/$/\.bak/' tty[2-6]

7 /tmp 使用 ramdisk

  vi /etc/fstab
  tmpfs /tmp tmpfs size=100m,mode=1777 0 0

8 使用prelink preload

  apt-get install prelink preload
 
  vi /etc/default/prelink PRELINKING=yes
  /etc/cron.daily/prelink
 
  vi /etc/apt/apt.conf
  DPkg::Post-Invoke {"echo Running prelink, please
	  wait...;/etc/cron.daily/prelink";}

9 停用ipv6

vi /etc/modprobe.d/aliases
alias net-pf-10 off #ipv6
 
vi /etc/hosts
# The following lines are desirable for IPv6
# capable hosts
#::1 ip6-localhost ip6-loopback
#fe00::0 ip6-localnet
#ff00::0 ip6-mcastprefix
#ff02::1 ip6-allnodes
#ff02::2 ip6-allrouters
#ff02::3 ip6-allhosts
 
echo "alias net-pf-10 off" >> /etc/modprobe.d/bad_list

10 使用sysv-rc-conf

11 调整gnome-session-properties

1 Comment