Thursday, December 10, 2009

MySQL5.0 同步备份恢复的三种方法

第一种最简单的方法适用于数据库文件比较小,能在停止主数据库服务后几分钟内打完tar包的情况,这种情况与第一次做slave同步的方法一样:
mysql> FLUSH TABLES WITH READ LOCK;
mysql > SHOW MASTER STATUS;
记录状态后进入命令行将数据库原生数据文件打个tar包,再
mysql> UNLOCK TABLES;
将tar包重布署到MySQL slave上即可,注意将tar包中的日志文件,master.info,relay-log.info要删除之后再CHANGE MASTER TO。

第二种方法是利用mysql的二进制日志文件。
首先重启一次主数据库。
然后在slave上用以下命令查看二进制日志文件执行的最后SQL语句,其中start-datetime时间为此二进制日志文件最后的修改时间,或者提前30秒方便查看最后执行完成的SQL语句:
$> mysqlbinlog -S /tmp/mysql.sock hostname-relay-bin.000002 --start-datetime='2009-12-11 11:12:00'

然后在主数据库上用命令筛选出符合时间范围的日志:
$> mysqlbinlog --start-datetime='2009-12-11 11:12:00' -S /tmp/mysql.sock mysql-bin.000007 > /home/username/bin-log.sql
再用grep命令,查找到bin-log.sql中与之前在slave上查到的SQL行号,并用sed命令删除1到此行号的全部行(举例查到行号为1234):
$> grep -n "last executed sql statement" /home/username/bin-log.sql
$> sed '1,1234d' /home/username/bin-log.sql > /home/username/bin-log-sed.sql
将生成的bin-log-sed.sql文件传到slave数据库上用mysql命令行工具导入数据。
$> mysql -uroot -p < bin-log-sed.sql
如果碰到报错,用sed再删除sql文件的前几行导入。
导入完成后,进行mysql控制台,下面的master_log_file是同步中断的主数据库日志文件mysql-bin.000007的后继日志文件名mysql-bin.000008:
$> stop slave;
$> change master to master_log_file='mysql-bin.000008', master_log_pos=98;
$> start slave;
$> show slave status\G

第三种方法也是利用二进制日志文件恢复。
与第二种方法类似,只是在grep查到行号之后,用awk命令找到日志中断的位置,重新调整slave上的master_log_pos即可。
举例查到行号为1234:
$> cat /home/username/bin-log.sql |awk 'NR >= 1234 {print $0}' |more
可以找到最后执行完的那个SQL之后,服务器的二进制日志文件位置:
last executed sql statuement;
之后会看到类似:
# at 1023411738
这样的内容,用这个值更新slave上的master信息:
$> stop slave;
$> change master to master_log_file='mysql-bin.000007', master_log_pos=1023411738;
$> start slave;
$> show slave status\G
在slave的二进制日志或者是hostname-relay-log.info,hostname.err中也会有master上的end_log_pos,可以先尝试用一下,一般因为master/slave异常才导致同步失败,在slave上的这些信息已经不正确,所以需要用awk找到服务器上的二进制日志位置。


MySQL5 Replication fails with "log event entry exceeded max_allowed_packet"

配置文件中有二个参数设置需要注意,max_allowed_packet在主从服务器上的设置最好是设置相同,并且将read_buffer_size <= max_allowed_packet。 
如果这二个配置正确,仍然报错,则需要STOP SLAVE; 并CHANGE MASTER TO,调整master_log_pos的值,这个值与服务器的日志文件要对应上。
Reference: http://bugs.mysql.com/bug.php?id=15937
http://bugs.mysql.com/bug.php?id=8215

Thursday, December 03, 2009

mysql5中注意UUID函数的使用

NOW() 函数,因为在二进制日志里已经包括了时间戳,可以被正确复制到slave server上。
UUID() 函数,具有非确定性,所以不能被复制到slave server,所以在存储过程或者触发器中要慎用。
the UUID() function is nondeterministic (and does not replicate). You should be careful about using such functions in triggers. It is not safe.
SYSDATE() 函数也具有非确定性,与NOW()函数不一样,在同步复制时会与master上的时间不一致。官方文档说明如下:
SYSDATE()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context.

As of MySQL 5.0.13, SYSDATE() returns the time at which it executes. This differs from the behavior for NOW(), which returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.)


mysql> SELECT NOW(), SLEEP(2), NOW();
+---------------------+----------+---------------------+
| NOW() | SLEEP(2) | NOW() |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:36 | 0 | 2006-04-12 13:47:36 |
+---------------------+----------+---------------------+

mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
+---------------------+----------+---------------------+
| SYSDATE() | SLEEP(2) | SYSDATE() |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:44 | 0 | 2006-04-12 13:47:46 |
+---------------------+----------+---------------------+

In addition, the SET TIMESTAMP statement affects the value returned by NOW() but not by SYSDATE(). This means that timestamp settings in the binary log have no effect on invocations of SYSDATE().

Because SYSDATE() can return different values even within the same statement, and is not affected by SET TIMESTAMP, it is non-deterministic and therefore unsafe for replication. If that is a problem, you can start the server with the --sysdate-is-now option to cause SYSDATE() to be an alias for NOW(). The non-deterministic nature of SYSDATE() also means that indexes cannot be used for evaluating expressions that refer to it.

Wednesday, December 02, 2009

在64位的CentOS5中编译安装mysql5.0.88

$> wget http://dev.mysql.com/get/Downloads/MySQL-5.0/mysql-5.0.88.zip/from/http://mysql.byungsoo.net/
$> yum -y install gcc
$> yum -y install gcc-c++
$> yum -y install ncurses-devel

$> CC=gcc \
CFLAGS="-O3 -fno-omit-frame-pointer" \
CXX=gcc \
CXXFLAGS="-O3 -fno-omit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" \
./configure --prefix=/usr/local/mysql --without-debug --with-big-tables --with-unix-socket-path=/tmp/mysql.sock --with-client-ldflags=-all-static --with-mysqld-ldflags=-all-static --enable-assembler --with-extra-charsets=gbk,gb2312,utf8 --with-pthread --enable-thread-safe-client

$> make && make install

Reference: http://dev.mysql.com/doc/refman/5.0/en/linux-ia-64.html

.bashrc中rc的含义说明

rc (像是 ".cshrc" 或 "/etc/rc" 中的 rc 这两个字母) = "RunCom"

"rc" 是取自 "runcom", 来自麻省理工学院在 1965 年发展的 CTSS系统。相关文献曾记载这一段话:
具有从档案中取出一系列命令来执行的功能;这称为 "run commands" 又称为 "runcom",而这种档案又称为一个 runcom (a runcom)。

Monday, November 09, 2009

在linux命令行中批量新建文件夹

$> printf 'dir%01d\n' {1..100} | xargs mkdir

Mysql Server System Variables

mysql 数据库中几个系统变量的分析说明

connect_timeout

Command Line Format --connect_timeout=#
Config File Format connect_timeout
Option Sets Variable Yes, connect_timeout
Variable Name connect_timeout
Variable Scope Global
Dynamic Variable Yes
   Permitted Values (<= 5.1.22)
Type numeric
Default 5
   Permitted Values (>= 5.1.23)
Type numeric
Default 10

The number of seconds that the mysqld server waits for a connect packet before responding with Bad handshake. The default value is 10 seconds as of MySQL 5.1.23 and 5 seconds before that.
Increasing the connect_timeout value might help if clients frequently encounter errors of the form Lost connection to MySQL server at 'XXX', system error: errno.
增加此值可以解决此问题:Lost connection to MySQL server at 'XXX', system error: errno.



delay_key_write

Command Line Format --delay-key-write[=name]
Config File Format delay-key-write
Option Sets Variable Yes, delay_key_write
Variable Name delay-key-write
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type enumeration
Default ON
Valid Values ON, OFF, ALL

This option applies only to MyISAM tables.
此参数只针对MyISAM表。
It can have one of the following values to affect handling of the DELAY_KEY_WRITE table option that can be used in CREATE TABLE statements.
Option Description
OFF DELAY_KEY_WRITE is ignored.
ON MySQL honors any DELAY_KEY_WRITE option specified in CREATE TABLE statements. This is the default value.
ALL All new opened tables are treated as if they were created with the DELAY_KEY_WRITE option enabled.

If DELAY_KEY_WRITE is enabled for a table, the key buffer is not flushed for the table on every index update, but only when the table is closed. This speeds up writes on keys a lot, but if you use this feature, you should add automatic checking of all MyISAM tables by starting the server with the --myisam-recover option (for example, --myisam-recover=BACKUP,FORCE). See Section 5.1.2, “Server Command Options”, and Section 13.5.1, “MyISAM Startup Options”.
Warning
如果启用了DELAY_KEY_WRITE,说明使用该项的表的键缓冲区在每次更新索引时不被清空,只有关闭表时才清空。遮掩盖可以大大加快键的写操作,但如果你使用该特性,你应用--myisam-recover选项启动服务器,为所有MyISAM表添加自动检查(例如,--myisam-recover=BACKUP,FORCE)。
If you enable external locking with --external-locking, there is no protection against index corruption for tables that use delayed key writes.



expire_logs_days

Command Line Format --expire_logs_days=#
Config File Format expire_logs_days
Option Sets Variable Yes, expire_logs_days
Variable Name expire_logs_days
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 0
Range 0-99

The number of days for automatic binary log removal. The default is 0, which means “no automatic removal.” Possible removals happen at startup and when the binary log is flushed.
二进制日志自动删除的天数,可设置值的范围为0至99。默认值为0,表示“没有自动删除”。启动时和二进制日志循环时可能删除。

init_connect
Command Line Format --init-connect=name
Config File Format init_connect
Option Sets Variable Yes, init_connect
Variable Name init_connect
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type string

A string to be executed by the server for each client that connects. The string consists of one or more SQL statements. To specify multiple statements, separate them by semicolon characters. For example, each client begins by default with autocommit mode enabled. There is no global system variable to specify that autocommit should be disabled by default, but init_connect can be used to achieve the same effect:

SET GLOBAL init_connect='SET autocommit=0';

This variable can also be set on the command line or in an option file. To set the variable as just shown using an option file, include these lines:

[mysqld]
init_connect='SET autocommit=0'

Note that the content of init_connect is not executed for users that have the SUPER privilege. This is done so that an erroneous value for init_connect does not prevent all clients from connecting. For example, the value might contain a statement that has a syntax error, thus causing client connections to fail. Not executing init_connect for users that have the SUPER privilege enables them to open a connection and fix the init_connect value.
在这里比较常用的初始化语句是设置一个字符集,当然也可以直接修改my.cnf中的配置参数(character_set_connection/character_set_client等):
[mysqld]
init_connect='SET names utf8'




interactive_timeout

Command Line Format --interactive_timeout=#
Config File Format interactive_timeout
Option Sets Variable Yes, interactive_timeout
Variable Name interactive_timeout
Variable Scope Both
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 28800
Min Value 1

The number of seconds the server waits for activity on an interactive connection before closing it. An interactive client is defined as a client that uses the CLIENT_INTERACTIVE option to mysql_real_connect(). See also wait_timeout.
一个连接如果长时间空闲会被mysql服务端强行关闭掉,其默认的时间是8小时,在用JDBC连接到mysql中,如果池里的连接超过8小时没有使用,就会产生连接异常。

wait_timeout
Command Line Format --wait_timeout=#
Config File Format wait_timeout
Option Sets Variable Yes, wait_timeout
Variable Name wait_timeout
Variable Scope Both
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 28800
Range 1-31536000
   Permitted Values
Type (windows) numeric
Default 28800
Range 1-2147483

The number of seconds the server waits for activity on a noninteractive connection before closing it. This timeout applies only to TCP/IP and Unix socket file connections, not to connections made via named pipes, or shared memory.

On thread startup, the session wait_timeout value is initialized from the global wait_timeout value or from the global interactive_timeout value, depending on the type of client (as defined by the CLIENT_INTERACTIVE connect option to mysql_real_connect()).
这个值一般不需要去设置,只要设置interactive_timeout。



join_buffer_size
Command Line Format --join_buffer_size=#
Config File Format join_buffer_size
Option Sets Variable Yes, join_buffer_size
Variable Name join_buffer_size
Variable Scope Both
Dynamic Variable Yes
   Permitted Values
Platform Bit Size 64
Type numeric
Default 131072
Range 8200-18446744073709547520

The size of the buffer that is used for plain index scans, range index scans, and joins that do not use indexes and thus perform full table scans. Normally, the best way to get fast joins is to add indexes. Increase the value of join_buffer_size to get a faster full join when adding indexes is not possible. One join buffer is allocated for each full join between two tables. For a complex join between several tables for which indexes are not used, multiple join buffers might be necessary.

The maximum allowable setting for join_buffer_size is 4GB. As of MySQL 5.1.23, values larger than 4GB are allowed for 64-bit platforms (except 64-bit Windows, for which large values are truncated to 4GB with a warning).




key_buffer_size

Command Line Format --key_buffer_size=#
Config File Format key_buffer_size
Option Sets Variable Yes, key_buffer_size
Variable Name key_buffer_size
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 8388608
Range 8-4294967295

此参数仅用于MyISAM表中,一般此值可设置为物理内存的25-50%,尽可能的使用 Key_reads/Key_read_requests 的比率小于0.01,最重要的mysql性能调优参数。

Index blocks for MyISAM tables are buffered and are shared by all threads. key_buffer_size is the size of the buffer used for index blocks. The key buffer is also known as the key cache.
MyISAM表的索引块分配了缓冲区,由所有线程共享。key_buffer_size是索引块缓冲区的大小。键值缓冲区即为键值缓存。
The maximum allowable setting for key_buffer_size is 4GB on 32-bit platforms. As of MySQL 5.1.23, values larger than 4GB are allowed for 64-bit platforms, except 64-bit Windows prior to MySQL 5.1.31, for which large values are truncated to 4GB with a warning. As of MySQL 5.1.31, values larger than 4GB are also allowed for 64-bit Windows. The effective maximum size might be less, depending on your available physical RAM and per-process RAM limits imposed by your operating system or hardware platform. The value of this variable indicates the amount of memory requested. Internally, the server allocates as much memory as possible up to this amount, but the actual allocation might be less.
key_buffer_size的最大允许设定值为4GB。有效最大值可以更小,取决于可用物理RAM和操作系统或硬件平台强加的每个进程的RAM限制。
You can increase the value to get better index handling for all reads and multiple writes; on a system whose primary function is to run MySQL using the MyISAM storage engine, 25% of the machine's total memory is an acceptable value for this variable. However, you should be aware that, if you make the value too large (for example, more than 50% of the machine's total memory), your system might start to page and become extremely slow. This is because MySQL relies on the operating system to perform file system caching for data reads, so you must leave some room for the file system cache. You should also consider the memory requirements of any other storage engines that you may be using in addition to MyISAM.
增加该值,达到你可以提供的更好的索引处理(所有读和多个写操作)。通常为主要运行MySQL的机器内存的25%。但是,如果你将该值设得过大(例如,大于总内存的50%),系统将转换为页并变得极慢。MySQL依赖操作系统来执行数据读取时的文件系统缓存,因此你必须为文件系统缓存留一些空间。
For even more speed when writing many rows at the same time, use LOCK TABLES. See Section 7.2.21, “Speed of INSERT Statements”.
同时写多行时要想速度更快,应使用LOCK TABLES。
You can check the performance of the key buffer by issuing a SHOW STATUS statement and examining the Key_read_requests, Key_reads, Key_write_requests, and Key_writes status variables. (See Section 12.5.5, “SHOW Syntax”.) The Key_reads/Key_read_requests ratio should normally be less than 0.01. The Key_writes/Key_write_requests ratio is usually near 1 if you are using mostly updates and deletes, but might be much smaller if you tend to do updates that affect many rows at the same time or if you are using the DELAY_KEY_WRITE table option.

The fraction of the key buffer in use can be determined using key_buffer_size in conjunction with the Key_blocks_unused status variable and the buffer block size, which is available from the key_cache_block_size system variable:

   ((Key_blocks_unused × key_cache_block_size) / key_buffer_size)
  
用key_buffer_size结合Key_blocks_unused状态变量和缓冲区块大小,可以确定使用的键值缓冲区的比例。从key_cache_block_size服务器变量可以获得缓冲区块大小。使用的缓冲区的比例为:
   ((Key_blocks_unused * key_cache_block_size) / key_buffer_size)
该值为约数,因为键值缓冲区的部分空间被分配用作内部管理结构。

可以创建多个MyISAM键值缓存。4GB限制可以适合每个缓存,而不是一个组。
This value is an approximation because some space in the key buffer may be allocated internally for administrative structures.

It is possible to create multiple MyISAM key caches. The size limit of 4GB applies to each cache individually, not as a group. See Section 7.4.5, “The MyISAM Key Cache”.



log_slave_updates

Whether updates received by a slave server from a master server should be logged to the slave's own binary log. Binary logging must be enabled on the slave for this variable to have any effect.
假如mysql slave还用作为master server时,需要设置此参数,记录所有SQL操作,提供其他slave复制。



log_slow_queries
Command Line Format --log-slow-queries[=name]
Config File Format log-slow-queries
Option Sets Variable Yes, log_slow_queries
Variable Name log_slow_queries
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type boolean

Whether slow queries should be logged. “Slow” is determined by the value of the long_query_time variable.
记录查询非常慢的SQL到一个独立的日志文件中,可用于SQL分析和优化。




lower_case_file_system
Command Line Format --lower_case_file_system[=#]
Config File Format lower_case_file_system
Option Sets Variable Yes, lower_case_file_system
Variable Name lower_case_file_system
Variable Scope Global
Dynamic Variable No
   Permitted Values
Type boolean

This variable describes the case sensitivity of file names on the file system where the data directory is located. OFF means file names are case sensitive, ON means they are not case sensitive.

lower_case_table_names
Command Line Format --lower_case_table_names[=#]
Config File Format lower_case_table_names
Option Sets Variable Yes, lower_case_table_names
Variable Name lower_case_table_names
Variable Scope Global
Dynamic Variable No
   Permitted Values
Type numeric
Default 0
Range 0-2

If set to 1, table names are stored in lowercase on disk and table name comparisons are not case sensitive. If set to 2 table names are stored as given but compared in lowercase. This option also applies to database names and table aliases. See Section 8.2.2, “Identifier Case Sensitivity”.

这个参数在linux服务器上需要注意,一般是将此值设置为1,使表名全部以小写方式写入硬盘,避免表名的大小写问题。

If you are using InnoDB tables, you should set this variable to 1 on all platforms to force names to be converted to lowercase.

You should not set this variable to 0 if you are running MySQL on a system that does not have case-sensitive file names (such as Windows or Mac OS X). If this variable is not set at startup and the file system on which the data directory is located does not have case-sensitive file names, MySQL automatically sets lower_case_table_names to 2.


max_allowed_packet
Command Line Format --max_allowed_packet=#
Config File Format max_allowed_packet
Option Sets Variable Yes, max_allowed_packet
Variable Name max_allowed_packet
Variable Scope Both
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 1048576
Range 1024-1073741824

The maximum size of one packet or any generated/intermediate string.

The packet message buffer is initialized to net_buffer_length bytes, but can grow up to max_allowed_packet bytes when needed. This value by default is small, to catch large (possibly incorrect) packets.

此值需要是1024的一个倍数值,如果操作的数据有使用很长的字符串和大的BLOB字段,如图片,需要增加此值。
You must increase this value if you are using large BLOB columns or long strings. It should be as big as the largest BLOB you want to use. The protocol limit for max_allowed_packet is 1GB. The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.

When you change the message buffer size by changing the value of the max_allowed_packet variable, you should also change the buffer size on the client side if your client program allows it. On the client side, max_allowed_packet has a default of 1GB. Some programs such as mysql and mysqldump enable you to change the client-side value by setting max_allowed_packet on the command line or in an option file.




max_connect_errors
Command Line Format --max_connect_errors=#
Config File Format max_connect_errors
Option Sets Variable Yes, max_connect_errors
Variable Name max_connect_errors
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Platform Bit Size 32
Type numeric
Default 10
Range 1-4294967295
   Permitted Values
Platform Bit Size 64
Type numeric
Default 10
Range 1-18446744073709547520

If there are more than this number of interrupted connections from a host, that host is blocked from further connections. You can unblock blocked hosts with the FLUSH HOSTS statement.
如果从某台服务器的连接错误过多,会被mysql服务器阻挡连接。




max_connections
Command Line Format --max_connections=#
Config File Format max_connections
Option Sets Variable Yes, max_connections
Variable Name max_connections
Variable Scope Global
Dynamic Variable Yes
   Permitted Values (<= 5.1.14)
Type numeric
Default 100
   Permitted Values (>= 5.1.15)
Type numeric
Default 151
Range 1-16384
   Permitted Values (>= 5.1.17)
Type numeric
Default 151
Range 1-100000

The number of simultaneous client connections allowed. By default, this is 151, beginning with MySQL 5.1.15. (Previously, the default was 100.)
这个值一般都会调整得大一些,如200或者是500,用于处理并发连接数。如果看到“Too many connections”这样的错误提示就是表示mysql服务器的连接数已经被用完。



max_relay_log_size
Command Line Format --max_relay_log_size=#
Config File Format max_relay_log_size
Option Sets Variable Yes, max_relay_log_size
Variable Name max_relay_log_size
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 0
Range 0-1073741824

If a write by a replication slave to its relay log causes the current log file size to exceed the value of this variable, the slave rotates the relay logs (closes the current file and opens the next one). If max_relay_log_size is 0, the server uses max_binlog_size for both the binary log and the relay log. If max_relay_log_size is greater than 0, it constrains the size of the relay log, which enables you to have different sizes for the two logs. You must set max_relay_log_size to between 4096 bytes and 1GB (inclusive), or to 0. The default value is 0.



net_read_timeout
Command Line Format --net_read_timeout=#
Config File Format net_read_timeout
Option Sets Variable Yes, net_read_timeout
Variable Name net_read_timeout
Variable Scope Both
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 30
Min Value 1

The number of seconds to wait for more data from a connection before aborting the read. This timeout applies only to TCP/IP connections, not to connections made via Unix socket files, named pipes, or shared memory. When the server is reading from the client, net_read_timeout is the timeout value controlling when to abort. When the server is writing to the client, net_write_timeout is the timeout value controlling when to abort.
此参数只针对TCP/IP的mysql连接,当超过此值的秒数后,服务器端会放弃从客户端读取数据。



old_passwords
Command Line Format --old_passwords
Config File Format old-passwords
Option Sets Variable Yes, old_passwords
Variable Name old_passwords
Variable Scope Both
Dynamic Variable Yes
   Permitted Values
Type boolean
Default FALSE

Whether the server should use pre-4.1-style passwords for MySQL user accounts.
如果客户端收到的错误消息为:“Client does not support authentication protocol”,说明服务器使用的是旧的密码格式,需要为用户按旧的格式重设密码。
mysql>SET PASSWORD 'some_user'@'some_host' = OLD_PASSWORD('newpwd');




read_only
Command Line Format --read_only
Config File Format read_only
Option Sets Variable Yes, read_only
Variable Name read_only
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 0

This variable is off by default. When it is enabled, the server allows no updates except from users that have the SUPER privilege or (on a slave server) from updates performed by slave threads. On a slave server, this can be useful to ensure that the slave accepts updates only from its master server and not from clients. This variable does not apply to TEMPORARY tables, nor does it prevent the server from inserting rows into the log tables (see Section 5.2.1, “Selecting General Query and Slow Query Log Output Destinations”).

read_only exists only as a GLOBAL variable, so changes to its value require the SUPER privilege. Changes to read_only on a master server are not replicated to slave servers. The value can be set on a slave server independent of the setting on the master.

As of MySQL 5.1.15, the following conditions apply:

    * If you attempt to enable read_only while you have any explicit locks (acquired with LOCK TABLES) or have a pending transaction, an error occurs.
    * If you attempt to enable read_only while other clients hold explicit table locks or have pending transactions, the attempt blocks until the locks are released and the transactions end. While the attempt to enable read_only is pending, requests by other clients for table locks or to begin transactions also block until read_only has been set.
    * read_only can be enabled while you hold a global read lock (acquired with FLUSH TABLES WITH READ LOCK) because that does not involve table locks.
这个参数用于slave服务器上,可以控制避免同步复制发生问题。在master上设置此值与slave是无关的,二都互相独立。




server_id
Command Line Format --server-id=#
Config File Format server-id
Option Sets Variable Yes, server_id
Variable Name server_id
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 0
Range 0-4294967295

The server ID, used in replication to give each master and slave a unique identity. This variable is set by the --server-id option. For each server participating in replication, you should pick a positive integer in the range from 1 to 232 – 1 to act as that server's ID.
这个参数用在同步复制时,分配给每个mysql server一个独立唯一的ID标识。




skip_networking

This is ON if the server allows only local (non-TCP/IP) connections. On Unix, local connections use a Unix socket file. On Windows, local connections use a named pipe or shared memory. On NetWare, only TCP/IP connections are supported, so do not set this variable to ON. This variable can be set to ON with the --skip-networking option.
这个参数在许多linux发行版中是被打开的,这样如果是通过TCP/IP进行连接的话,是无法连接成功的,需要注释掉这一行设置才可以,或者使用socket进行连接。





slow_query_log

Whether the slow query log is enabled. The value can be 0 (or OFF) to disable the log or 1 (or ON) to enable the log. The default value depends on whether the --slow_query_log option is given (--log-slow-queries before MySQL 5.1.29). The destination for log output is controlled by the log_output system variable; if that value is NONE, no log entries are written even if the log is enabled. The slow_query_log variable was added in MySQL 5.1.12.
用于分析查询效率低下的SQL


slow_query_log_file
Version Introduced 5.1.12
Command Line Format --slow-query-log-file=file_name
Config File Format slow_query_log_file
Option Sets Variable Yes, slow_query_log_file
Variable Name slow_query_log_file
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type filename

The name of the slow query log file. The default value is host_name-slow.log, but the initial value can be changed with the --slow_query_log_file option (--log-slow-queries before MySQL 5.1.29). This variable was added in MySQL 5.1.12.


  
sort_buffer_size
Command Line Format --sort_buffer_size=#
Config File Format sort_buffer_size
Option Sets Variable Yes, sort_buffer_size
Variable Name sort_buffer_size
Variable Scope Both
Dynamic Variable Yes
   Permitted Values
Platform Bit Size 32
Type numeric
Default 2097144
Max Value 4294967295
   Permitted Values
Platform Bit Size 64
Type numeric
Default 2097144
Max Value 18446744073709547520

Each thread that needs to do a sort allocates a buffer of this size. Increase this value for faster ORDER BY or GROUP BY operations. See Section B.5.4.4, “Where MySQL Stores Temporary Files”.

The maximum allowable setting for sort_buffer_size is 4GB. As of MySQL 5.1.23, values larger than 4GB are allowed for 64-bit platforms (except 64-bit Windows, for which large values are truncated to 4GB with a warning).
对于SQL中用到order by和group by子句的,提高此值可以增加查询的速度。



table_cache
Version Removed 5.1.3
Version Deprecated 5.1.3
Command Line Format --table_cache=#
Config File Format table_cache
Option Sets Variable Yes, table_cache
Variable Name table_cache
Variable Scope Global
Dynamic Variable Yes
Deprecated 5.1.3, by table_open_cache
   Permitted Values
Type numeric
Default 64
Range 1-524288

This is the old name of table_open_cache before MySQL 5.1.3. From 5.1.3 on, use table_open_cache instead.



table_open_cache
Version Introduced 5.1.3
Command Line Format --table-open-cache=#
Config File Format table_open_cache
Variable Name table_open_cache
Variable Scope Global
Dynamic Variable Yes
   Permitted Values
Type numeric
Default 64
Range 64-524288

The number of open tables for all threads. Increasing this value increases the number of file descriptors that mysqld requires. You can check whether you need to increase the table cache by checking the Opened_tables status variable. See Section 5.1.7, “Server Status Variables”. If the value of Opened_tables is large and you don't do FLUSH TABLES often (which just forces all tables to be closed and reopened), then you should increase the value of the table_open_cache variable. For more information about the table cache, see Section 7.4.7, “How MySQL Opens and Closes Tables”. Before MySQL 5.1.3, this variable is called table_cache.
  


thread_concurrency
Command Line Format --thread_concurrency=#
Config File Format thread_concurrency
Option Sets Variable Yes, thread_concurrency
Variable Name thread_concurrency
Variable Scope Global
Dynamic Variable No
   Permitted Values
Type numeric
Default 10
Range 1-512

This variable is specific to Solaris systems, for which mysqld invokes the thr_setconcurrency() with the variable value. This function enables applications to give the threads system a hint about the desired number of threads that should be run at the same time.

Tuesday, October 27, 2009

grep命令参数-显示查询内容的所在行号

使用grep命令时,添加行号(-n)可以显示查询内容的所在行的行号,如:
$> grep -n ls ~/.bashrc
1:# ~/.bashrc: executed by bash(1) for non-login shells.
47: else
54:else
77:# enable color support of ls and also add handy aliases
80: alias ls='ls --color=auto'
81: alias ll='ls -la'
90:# some more ls aliases
91:#alias ll='ls -l'
92:#alias la='ls -A'
93:#alias l='ls -CF'

Sunday, September 27, 2009

svn 批量添加新文件

$> svn status |grep '^\?'|awk -F " " '{print $2}'|xargs svn add

或者是
$> svn st|grep '^\?'|sed 's/^\?\s*//g'|xargs svn add

Monday, September 07, 2009

Helpers Outside Views

How to access helper methods outside of the view layer?


# models/category.rb
def description
  "This category has #{helpers.pluralize(products.count, 'product')}."
end

def helpers
  ActionController::Base.helpers
end

# products_controller.rb
def create
  @product = Product.new(params[:product])
  if @product.save
    flash[:notice] = "Successfully created #{@template.link_to('product', @product)}."
    redirect_to products_url
  else
    render :action => 'new'
  end
end


Reference: http://railscasts.com/episodes/132-helpers-outside-views

Sunday, August 23, 2009

Unix 哲学基础[Unix编程艺术读书笔记]

1、让每个程序就做好一件事。如果有新任务,就重新开始,不要往原程序中加入新功能而搞得复杂。
2、假定每个程序的输出都会成为另一个程序的输入,哪怕那个程序还是未知的。输出中不要有无关的信息干扰。避免使用二进格式输入,而是坚持使用文本流,不要坚持使用交互式输入。
3、尽可能早地将设计和编译的软件投入使用,对于拙劣的代码别犹豫,扔掉重写。
4、优先使用工具减轻编程任务,工欲善其事,必先利其器。
5、花哨的算法复杂度大,并比简单的算法更容易出bug,更难实现,理解和维护。尽量使用简单的算法配合简单的数据结构。
6、编程的核心是数据结构,而不是算法。
7、不确定的时候就用穷举。
8、小就是美,在确保任务完成的基础上,程序功能尽可能少。

Unix 原则
1、模块原则:使用简洁的接口拼合拼合简单的部件。
2、清晰原则:清晰胜于机巧。
3、组合原则:设计时考虑拼接组合。
4、分离原则:策略同机制分离,接口同引擎分离。
5、简洁原则:设计要简洁,复杂度能低则低。
6、吝啬原则:不要编写庞大的程序。
7、透明性原则:设计要可见,以便审查和调试。
8、健壮原则:健壮源于透明和简洁。
9、表示原则:要求逻辑质朴而健壮。
10、通俗原则:即最小惊异原则,接口设计避免标新立异。
11、缄默原则:如果一个程序没什么好说的,就沉默。
12:补救原则:出现异常时要给出足够的错误信息。
13、经济原则:宁花机器一分钟,不花程序员一分钟。
14、生成原则:避免手工hack,尽量编写程序去生成程序。
15、优化原则:原型设计,先求运行,再求正确,最后求快。
16、多样原则:决不相信所谓“不二法门”的断言。
17、扩展原则:设计着眼未来,未来总比预想来得快。

Unix 哲学之总结
所有Unix的哲学用一句话来概括就是“KISS”原则:
Keep It Simple, Stupid!

Thursday, August 20, 2009

Element Data in jQuery

Added in jQuery 1.2
Attaching data to elements can be hazardous.
Store data: jQuery.data(elem, "name", "value");
Read data: jQuery.data(elem, "name");
All data is stored in a central cache and completely garbage collected,
as necessary.

Added in jQuery 1.2.3
Can handle namespacing:


$("div").data("test", "original");
$("div").data("test.plugin", "new data");
$("div").data("test") == "original"; // true
$("div").data("test.plugin") == "new data"; // true

Advanced data handling can be overridden by plugins:

$(element).bind("setData.draggable", function(event, key, value) {
self.options[key] = value;
}).bind("getData.draggable", function(event, key) {
return self.options[key];
});

Special Events in jQuery

Added in jQuery 1.2.2
Can create whole shadow event system
New events: mouseenter, mouseleave, ready
$("li").bind("mouseenter", function(){
$(this).addClass("hover");
}).bind("mouseleave", function(){
$(this).removeClass("hover");
});

Non-DOM Events in jQuery

>>> function User(){}
>>> var u = new User
>>> u
Object
>>> $(u)
[Object]
>>> $(u).bind('login', function(){console.log('login')})
[Object jQuery1250738637761=27]
>>> var j = $(u).bind('login', function(){console.log('login')})
>>> j
[Object jQuery1250738637761=27]
>>> $(u).trigger('login')
login
login
[Object jQuery1250738637761=27]

Tuesday, August 11, 2009

Convert ^M to newline character in text files

If the ^M character is showing up in files while opening the file
concerned, then follow these steps to convert it to a new line.
In vi use the following:

:%s/^M/\n/g

or with perl on the command line:

$ perl -pi.bak -e 's/^M/\n/g'

NOTE: Be sure to create the ^M by typing ctrl V followed by ctrl M.

^M is ASCII 13 (Ctrl M), which is the carriage return.

Different operating systems use different symbols to set the end of a
line/new line.
Unix uses newline (\n)
Mac uses carriage return (\r)
And Windows/DOS use both (\n\r)

To prevent the ^M from showing up in files, be sure to use the ASCII
(text) mode when transfering text files.

Source article link:
http://blog.eukhost.com/webhosting/convert-m-to-newline-character-in-text-files/

Thursday, August 06, 2009

todo list on linux

1. devtodo
2. tudu
3. remind
4. todo.txt
5. awn todo list applet

使用之后觉得devtodo最为好用,tudu也不错,有vi类似的操作快捷键,用起来很顺手。
awn todo list applet结合awn一起用,做为桌面工具可以即时看到任务数量,操作也非常简单。

Friday, July 31, 2009

Linux 环境变量显示和设置

$> export
export命令不带参数可以将系统的环境变量全部列出来,如果需要设置环境变量,
可以在/etc/profile, ~/.bash_profile, ~/.bashrc文件中设置。

一些标准的环境变量:
SHELL 默认shell
LANG 默认语言
PATH linux寻找命令的默认路径,一般包括/bin,/usr/bin,/sbin,/usr/sbin,
/usr/X11R6/bin, /opt/bin,/usr/local/bin等。用户可以自行添加,
MANPATH man手册的默认路径
INPUTRC 默认键盘映象,详见/etc/inputrc
BASH_ENV bash shell的环境变量,通常在~/.bashrc中
DISPLAY X窗口适用的控制台,DISPLAY=:0对应于控制台F7,DISPLAY=:1对应于
控制台F8,DISPLAY=server:0向远程计算机发送 GUI应用程序。
COLORTERM GUI中的默认终端,通常是gnome-terminal.
USER 自动设置当前登陆用户的用户名。
LONGNAME 通常设置为$USER
MAIL 设置特定$USR的标准邮件目录
HOSTNAME 设置为/bin/hostname的命令输出
HISTSIZE 设置为history命令记住的命令数

Reference:http://matt-u.javaeye.com/blog/411379

IE 中将tr appendChild到Table的问题及解决方法

将一个TableRow对象appendChild到Table,在Firefox3/Safari4中测试都正常,在
IE6中则不能正常显示。
Table无论是否有写TBODY,生成的DOM中都会自动生成,在IE中,TR对象被
appendChild到了Table中,而非TBODY中,所以无法显示,所以可以将TR对象
appendChild到TBODY中。
还有就是可以使用Table.insertRow()方法添加一个新行。

Monday, July 27, 2009

在excel中转换unix timestamp

A1 = 1248255194
=(A1+8*3600)/86400+70*365+19

在excel中没有直接的函数可以将一个unix时间截,转换为一个可阅读的时间格式,
这个公式可以用来转换显示时间,转换出来的还是一个数字,需要调整其显示格式,选择一个日期格式。

Wednesday, July 15, 2009

提示是否下载PHP文件的解决方法

如果当您浏览PHP网页的时候,浏览器提示您是否下载PHP文件而不是去显示它的时候,就可能是您没有安装libapache2-mod- php5。

当您安装PHP5的时候,它会被默认的安装进去的,如果您不小心的将它遗忘了。

您就需要去将它打开

$> sudo a2enmod php5

然後使用

$> sudo /etc/init.d/apache2 restart

来重新启动APACHE。

Reference: http://blog.chinaunix.net/u2/68904/showart_695284.html

ubuntu上mysql远程访问限制

用nestat命令查看3306端口状态:
~# netstat -an | grep 3306
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN

从结果可以看出3306端口只是在IP 127.0.0.1上监听,所以拒绝了其他IP的访问。

解决方法:修改/etc/mysql/my.cnf文件。打开文件,找到下面内容:

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address  = 127.0.0.1
把上面这一行注释掉

重新启动后,重新使用netstat检测:

~# netstat -an | grep 3306
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN

此时再从远程机器就可以telnet通3306端口了。
Reference: http://blog.csdn.net/mydeman/archive/2009/01/21/3847695.aspx

mysql5 table name case sensitive problem on linux

add below line under [mysqld] block of my.cnf :
lower_case_table_names=1
Reference:
http://dev.mysql.com/doc/refman/5.1/en/identifier-case-sensitivity.html

Sunday, July 12, 2009

iframe src problem in firefox

<iframe src='javascript:'></iframe>
在firefox下,当运行到上面语句的时候,将会弹出错误控制台。

打印IE中iframe内容

需要将被打印的iframe先focus(),不然打印仍然是最外面的窗体内容。如:
window.frames[0].focus();
window.frames[0].print();

linux 基础学习篇一

1973 UNIX
1977 BSD (Bill Joy) -> FreeBSD
1979 AT&T 版权声明
1984 x86 Minix
1984 Richard Mathew Stallman -> GNU & FSF
GPL / LGPL / Apache / BSD / MIT
1991 Linus Torvalds -> Linux

Linux 执行命令
Command [-options] parameters
date -s '2009-09-09 09:09:09'
cal 2009
netstat -a
ps -aux
查看错误信息
google错误信息和example用法
用man/info查说明及用法

keyboard shortcut
Tab
CTRL + C
CTRL + D

Linux 目录和文件相关命令
root
文件权限:所属用户、所属组、其他人
drwxr-xr-x   19        yu            staff   646     Mar 11 18:39 Books
[属性]        [文件数] [所属用户]   [所属组]  [大小]  [修改日期]    [文件名]
mtime 修改时间(modify)
ctime 状态变更时间(change)
atime 访问时间(access)
touch 修改文件的3个时间值
chgrp/chown/chmod

目录相关操作
./../-/~/~yu
pwd/mkdir/rm/ls/cp/mv

文件相关操作
cat/tac/nl/more/less/head/tail
man/more/less 过程中可以按h/H帮助键

Note: This article is published from gmail.

Thursday, May 14, 2009

RegExp escape function

RegExp.escape = (function() {
var punctuationChars = /([.*+?|/(){}[\]\\])/g;
return function(text) {
return text.replace(punctuationChars, '\\$1');
}
})();

var str = RegExp.escape('a+b/c*d$ ^{.}');
var reg = new RegExp(str);


Reference: http://simonwillison.net/2006/Jan/20/escape

Wednesday, May 13, 2009

Write excel tool for ruby

require 'rubygems'
require 'writeexcel'

# Create a new Excel Workbook
workbook = Spreadsheet::WriteExcel.new('ruby.xls')

# Add worksheet(s)
worksheet = workbook.add_worksheet
worksheet2 = workbook.add_worksheet

# Add and define a format
format = workbook.add_format
format.set_bold
format.set_color('red')
format.set_align('right')

# write a formatted and unformatted string.
worksheet.write(1, 1, 'Hi Excel.', format) # cell B2
worksheet.write(2, 1, 'Hi Ruby.') # cell B3

# write a number and formula using A1 notation
worksheet.write('B4', 3.14159)
worksheet.write('B5', '=SIN(B4/4)')

# write to file
workbook.close

Tuesday, May 12, 2009

Non-blocking JavaScript

Include via DOM

var js = document.createElement('script'); 
js.src = 'myscript.js'; 
var h = document.getElementsByTagName('head')[0]; 
h.appendChild(js);

Non-blocking JavaScript
  And what about my inline scripts?
  Setup a collection (registry) of inline scripts

Step 1
Inline in the <head>:
var myapp = { 
   stuff: [] 
}; 

Step 2
  Add to the registry
Instead of:
  alert('boo!');
Do:
  myapp.stuff.push(function(){ 
    alert('boo!'); 
  );

Step 3
  Execute all

var l = myapp.stuff.length;  
var l = myapp.stuff.length;  
for(var i = 0, i < l; i++) { 
myapp.stuff[i](); 

Premature optimization

Knuth: The premature optimization is the root of all evil.

Crockford: Make it right before you make it fast.

Sunday, April 19, 2009

0.1+0.2!==0.3 in javascript

>>> 0.1 + 0.2 !== 0.3
true
>>> 0.1 + 0.2
0.30000000000000004

javascript compare operations

'' == '0'; // false
0 == ''; // true
0 == '0'; // true
false == 'false'; // false
false == '0'; // true
false == undefined; // false
false == null; // false
null == undefined; // true
' \t\r\n ' == 0; // true

CSS 2.1 Tutorial (Basic Terms and Concepts)

CSS element basic types

  • Replaced and nonreplaced
  • Inline and block-level
  • Replaced element: img/object/input,占位元素,在文档中起占位符作用,内容由元素本身决定(img),或者元素类型可以替换(如input)。
  • Nonreplaced element: 非占位元素,其内容由浏览器渲染得到,并且内容包含于文档中。

Block-level element

  • Normal flow: The left-to-right, top-to-bottom rendering of text.
  • Root element: html
  • Block element seven properties (three width properties can be set auto)
  • “background”是指content, padding and border区域的背景
  • Margins永远是透明的(transparent)

Box Model

  • IE Box Model Issues
  • width in IE: border + padding + width
  • CSS box model hack

Inline element

  • Content area:nonreplaced element(font-size) and Replaced element(vertical seven properties)
  • Leading (行间空白): ‘line-height’ 减 ‘font-size’
  • (注意:行间空白只对nonreplaced元素起作用)
  • Inline box: line-height(nonreplaced) and content area(replaced)
  • Line box: 当前行中最高的inline box的顶到最低的inline box的底组成的box
  • ‘line-height’, ‘vertical-align’ and ‘font-size’这三个属性会影响当前行的高度
  • inline nonreplaced element border: 由’font-size’控制其边框,而不是’line-height’,边框会环绕在content area上
  • inline replaced elements能增高line box,但是不会使line-height加高
  • 为inline replaced element添加padding/border/margin可以增高inline-box
  • inline nonreplaced element的padding, borders, margin不会影响line-height,并且margin-top/margin-bottom设置了是不会生效的,但margin-left /margin-right会生效

display: list-item

  • 除inline和block-level元素外,还有一个特殊的元素LI,display: list-item
  • list-item: LI此属性的默认值,该值使一个元素生成一个原始块框(principal box)和一个列表框(block box)

About margins

  • margin is always transparent
  • navigate value margin for css effects
  • collapsing margins (边距重合)
  • horizontal margins never collapse.
  • Vertical margins may collapse between certain boxes.
  1. 常规流向中两个或多个块框相邻的垂直边距会重合。结果的边距宽度是相邻边距宽度中较大的值。如果出现负边距,则在最大的正边距中减去绝对值最大的负边距。如果没有正边距,则从零中减去绝对值最大的负边距。
  2. 在一个浮动框和其它框之间的垂直边距不重合。
  3. 绝对和相对定位的框的边距不重合。

Positioning

  • static: 默认值。无特殊定位
  • relative: 依据 left , right , top , bottom 等属性在正常文档流中偏移位置,占据原来的正常文档流中的空间位置
  • absolute: 将元素从文档流中拖出,使用 left,right,top,bottom 等属性相对于其最接近的一个具有定位设置的父元素 (position非static元素)进行绝对定位。如果不存在这样的父元素,则依据 body元素
  • fixed: 与absolute一样从正常文档流中拖出,区别在于其定位的容器是屏幕窗口(viewpoint)
  • ‘top’, ‘right’, ‘bottom’, ‘left’只能针对position非static元素设置
  • containing block: 为绝对定位的元素提供定位容器的,位置属性非static的元素

Floats and Clear

  • float: 当该属性不等于 none 引起对象浮动时,对象将被视作块对象( block-level ),即 display 属性等于 block 。也就是说,浮动对象的 display 属性将被忽略
  • clear在布局中与float同时使用的情况较多

CSS specificity value

  • specificity值表示方法: 0,0,0,0
  • id:0,1,0,0
  • class:0,0,1,0
  • element:0,0,0,1
  • h1 {color: red;} /* specificity = 0,0,0,1 */
  • p em {color: purple;} /* specificity = 0,0,0,2 */
  • .grape {color: purple;} /* specificity = 0,0,1,0 */
  • *.bright {color: yellow;} /* specificity = 0,0,1,0 */
  • p.bright em.dark {color: maroon;} /* specificity = 0,0,2,2 */
  • #id216 {color: blue;} /* specificity = 0,1,0,0 */
  • div#sidebar *[href] {color: silver;} /* specificity = 0,1,1,1 */

Selectors

  • * { sRules } 通配选择符
  • *.div { text-decoration:none;
  • E { sRules } 类型选择符
  • a { text-decoration:none; }
  • E1 E2 { sRules } 包含选择符 Descendant Selectors
  • table td { font-size:14px; }
  • E1 > E2 { sRules } 子对象选择符 Selecting Children (IE6 not support)
  • div ul>li { font-size:14px; }
  • #ID { sRules } ID选择符
  • E.className { sRules } 类选择符
  • E1 + E2 {sRules} 相邻节点选择符 Selecting Adjacent Sibling Elements
  • h1 + p {margin-top: 0;}
  • E1 , E2 , E3 { sRules } 分组选择符 grouping selectors
  • 将同样的定义应用于多个选择符
  • E : Pseudo-Classes { sRules }
  • div:first-letter { font-size:14px; }
  • a.fly :hover { font-size:14px; color:red; }

属性选择符

  • 1. E [ attr ] { sRules }
  • 2. E [ attr = value ] { sRules }
  • 3. E [ attr ~= value ] { sRules }
  • example: class partial value
  • 4. E [ attr *= value ] { sRules }
  • substring
  • 5. E [ attr ^= value ] { sRules }
  • 6. E [ attr $= value ] { sRules }
  • 7. E [ attr |= value ] { sRules } (explode by ‘-’)
  • a[href][title] {font-weight: bold;} /*multiply attributes*/
  • *[lang|="en"] {color: white;} /*en or begin with en-*/

About CSS classes

  • 如果某个元素具有特殊意义,在文档中只出现一次,则可使用id,同时也有利于js操作此节点。如果有不同的元素都可能用到相同的一个css效果,如div/p/a/span等,则可使用class
  • 一个元素的class的值可以是以空格间隔的一系列class名,如:
  • <p class=”urgent warning”>这个P元素有二个css class</p>

Position is everything

Reference:
5. Selectors
http://www.w3.org/TR/CSS21/selector.html
8. Box model
http://www.w3.org/TR/CSS21/box.html
9. Visual formatting model
http://www.w3.org/TR/CSS21/visuren.html
10. Visual formatting model details
http://www.w3.org/TR/CSS21/visudet.html

Tuesday, April 14, 2009

document onmousemove event differences in different browsers

当前文档document中如果有一个iframe时,当mouse滚过当前文档进入到iframe区域中时,不同的浏览器的表现形式有所不同,safari4/opera9.6中仍然能触发mouseover事件,但是在firefox3/ie中则不触发此mouseover事件,因为mouse已经离开了当前文档。

Friday, April 10, 2009

EmulatingFixedPositioning in IE


/* For fixed positioning savvy browsers */
.fixed{
position: fixed;
}

#header{
top: 0;
left: 0;
height: 80px;
}

#footer{
bottom: 0;
left: 0;
height: 30px;
}

body{
padding: 80px 0 30px;
}

/* For IE for Windows \*/
* html{
width: 100%;
height: 100%;
overflow: hidden;
}

* html body{
width: 100%;
height: 100%;
overflow: auto;
}

* html .fixed{
position: absolute;
}
/* */

Reference: http://css-discuss.incutio.com/?page=EmulatingFixedPositioning

Monday, March 16, 2009

Test take place of print

[Martin Fowler]: Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test.

Tuesday, March 10, 2009

pentaho2 install in ubuntu

$> export JRE_HOME=/usr/lib/jvm/java-6-sun-1.6.0.10
$> cd pentaho/biserver-ce
$> chmod a+x *.sh
$> ./start-pentaho.sh
$> cd pentaho/biserver-ce/administration-console/
$> ./start.sh
INFO: Console is now started. It can be accessed using http://localhost:8099 or http://127.0.0.1:8099

update admin password to "admin", reference http://wiki.pentaho.com/display/ServerDoc2x/Configuring+Security+with+Pentaho+Administration+Console:
$> cd pentaho/biserver-ce/administration-console/
$> vi resource/config/login.properties
admin: admin,server-administrator,content-administrator,admin

Restart pentaho bi server and pentaho administrator-console server.
Visit http://127.0.0.1:8099, and use admin/admin login administratation console(old username/password is admin/password)

Sunday, March 08, 2009

String compare trap in php

If string compare with an integer, php will evaluate string to integer intval() and compare it with that integer.

if('test' != 0) {
echo "true";
} else {
echo "false"; // return false
}
if('0test' != 0) {
echo "true";
} else {
echo "false"; // return false
}
if('1test' != 0) {
echo "true"; // return true
} else {
echo "false";
}

Regular expression of ip4

/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/

Using get_class() in superclass

<?php
abstract class bar {
public function __construct()
{
var_dump(get_class($this));
var_dump(get_class());
}
}

class foo extends bar {
}

new foo;
?>


The above example will output:

string(3) "foo"
string(3) "bar"

Reference:
http://cn.php.net/manual/en/function.get-class.php

Thursday, March 05, 2009

Howto maven2 download java source jar package

$> mvn dependency:sources -Dsilent=true filename
dependency:sources tells Maven to resolve all dependencies and their source attachments, and displays the version.

maven plugins lists page:
http://maven.apache.org/plugins/maven-dependency-plugin/
http://maven.apache.org/plugins/index.html

Reference:
http://groups.google.com/group/maven-zh/browse_thread/thread/20494aa10d7818ba?pli=1

Firefox3 keyboard shortcuts on macbook

function key (fn) + option (alt) + left arrow key (<-) = HomePage

Command-D = Add bookmark
Command-Backspace = Back
Command-B = Bookmarks
F7 = Caret Browsing
Command-W = Close Tab
Command-F4 = Close Tab
Command-Shift-W = Close Window

Option-F4 = Close Window
Shift-Return = Add .net to address bar
Command-C = Copy
Command-X = Cut
Command-- = Shrink text
Delete = Delete
Shift-Delete = Delete Individual Form AutoComplete Entry
Command-J = Downloads
Command-G = Find Again
F3 = Find Again
‘ = Find As You Type Link
/ = Find As You Type Text
Command-Shift-G = Find Previous
Shift-F3 = Find Previous
Command-F = Find in This Page
Shift-Backspace = Forward
Command-Enter = Forward
Down Arrow = Scroll Down
Up Arrow = Scroll Up

Command-H = History
Option-Home = Go to your homepage
Command-+ = Enlarge text
F6 = Move to Next Frame
Shift-F6 = Move to Previous Frame
Command-M = New Mail Message
Command-T = New Tab
Command-Option-Tab = Next Tab
Command-Page Down = Next Tab
Command-N = New Window
Command-O = Open File
Command-Return = Activate selected hyperlink
Shift-Return = Open Link in New Window
Option-Return = Open address in address bar in a new tab
Command-I = Page Info
Command-U = Page Source
Command-V = Paste
Command-Shift-Tab = Previous Tab
Command-Page Up = Previous Tab
Command-P = Print
Command-Shift-Z = Redo
F5 = Refresh
Command-R = Refresh
Command-F5 = SuperRefresh (refreshes the page even if no changes have been made to the page since you last loaded it)
Command-Shift-R = SuperRefresh (refreshes the page even if no changes have been made to the page since you last loaded it)
Command-0 = Restore text size
Command-S = Save Page As
Option-Return = Save target of selected hyperlink as
Command-A = Select All
Command-L = Select Location Bar
Down Arrow = Select Next AutoComplete entry in textbox
Up Arrow = Select Previous AutoComplete entry in textbox
Command-Down Arrow = Select Next Search Engine in Search Bar
Command-Up Arrow = Select Previous Search Engine in Search Bar
Command-1 = Select first tab
Command-2 = Select second tab
Command-3 = Select third tab
Command-4 = Select fourth tab
Command-5 = Select fifth tab
Command-6 = Select sixth tab
Command-7 = Select seventh tab
Command-8 = Select eighth tab
Command-9 = Select ninth tab (select last tab)
Escape = Stop loading a page
Command-Z = Undo
Command-K = Web Search

Installing PHP XDebug on Mac OS X Leopard

$> curl -O http://xdebug.org/files/xdebug-2.0.4.tgz
$> tar zxvf ./xdebug-2.0.4.tgz
$> cd ./xdebug-2.0.4/xdebug-2.0.4
$> phpize
$> MACOSX_DEPLOYMENT_TARGET=10.5 CFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp" CCFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe" CXXFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe" LDFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -bind_at_load" ./configure --enable-xdebug
$> make
$> sudo make install
$> sudo cp modules/xdebug.so /usr/lib/php/extensions/no-debug-non-zts-20060613/
$> sudo cp /etc/php.ini.default /etc/php.ini
$> sudo vi /etc/php.ini
; append below lines to file bottom of /etc/php.ini


zend_extension=/usr/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so
[xdebug]
xdebug.file_link_format="txmt://open?url=file://%f&line=%l"
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_autostart=1

$> php -m
You should see xdebug module in list.
$> sudo apachectl restart

phpinfo will output xdebug module.
After xdebug installed, then install PDT for eclipse, or download MacGDBp, php can debug using bleakpoint.

Reference:
http://jamesangus.ucantblamem.com/programming/installing-php-xdebug-on-mac-os-x-leopard/214/
http://developers.sugarcrm.com/wordpress/2008/11/25/enabling-xdebug-under-os-x-leopard/

Wednesday, February 18, 2009

Remove msn advertises

close msn firstly.
open "C:\WINDOWS\system32\drivers\etc\hosts":
then add below 2 line under 127.0.0.1 localhost:
127.0.0.1 msn.allyes.com

127.0.0.1 rad.msn.com

open msn and try it.

Friday, February 13, 2009

java 计算字符串长度

/**
* 计算字符串长度,对于0-255之间的字符按1计算,大于255的字符按2计算
*
* @param str
* @return
*/
public static int getStringLength(String str) {
int length = 0;
Pattern pattern = Pattern.compile("([^\\x00-\\xff])");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
length++;
}
return str.length() + length;
}

java unicode字符串转换

/**
* 转换unicode字符串为其对应的实际字符串, UnicodeToString("测试\\u4E2D\\u6587") 输出为: "测试中文"
*
* @param str
* @return
*/
public static String UnicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}

Reference:
http://yuweijun.blogspot.com/2008/06/unicode.html
http://yuweijun.blogspot.com/2008/08/unicode-and-html-entities-in-javascript.html
http://yuweijun.blogspot.com/2008/12/rubyunicodeutf8.html

Java Pattern.quote 使用说明

Java 引用说明:

\ Nothing,但是引用以下字符
\Q Nothing,但是引用所有字符,直到 \E
\E Nothing,但是结束从 \Q 开始的引用

例子:
Pattern.quote("[test]")
返回 => \Q[test]\E
这样就不需要对正则的特殊字符'['和']'做转义了

Tuesday, February 03, 2009

urlencode and urldecode in java

import java.net.URLDecoder;
import java.net.URLEncoder;

import junit.framework.TestCase;

public class URLEncodeAndDecode extends TestCase {

public void testUrlEncode() throws Exception {
String str = "中文";
String utf8Code = URLEncoder.encode(str, "UTF-8");
assertEquals("%E4%B8%AD%E6%96%87", utf8Code);
String gbkCode = URLEncoder.encode(str, "GBK");
assertEquals("%D6%D0%CE%C4", gbkCode);

assertEquals("中文", URLDecoder.decode("%E4%B8%AD%E6%96%87", "UTF-8"));
assertEquals("中文", URLDecoder.decode("%D6%D0%CE%C4", "GBK"));
}

}

Javascript expression '\s'=='s' is true in ie6

在ie6中
var exp = '\s'=='s';
的结果返回为true.

Monday, January 19, 2009

Remove gmail Sponsored link in firefox3

under ubuntu8.10, goto user profile directory and create dir "chrome" if "chrome" is not exists.
$> cd ~/.mozilla/firefox/user*profile.default/chrome
$> vi userContent.css

/*
* For remove gmail ad links
*/
.eWTfhb div[class="XoqCub"][style="width: 225px;"]{
height:0px!important;overflow:hidden!important;width:0px!important;
}
.tELAdc div[class="XoqCub"][style="width: 225px;"]{
height:0px!important;overflow:hidden!important;width:0px!important;
}
div.qWFFaf {
display:none!important;
}
restart firefox.
in other OS, userContent.css may in below path:
Windows 2000/XP
C:\Documents and Settings\[USER]\Application Data\Mozilla\Firefox\Profiles\*.default\chrome\
Mac OS X
~/Library/Application Support/Firefox/Profiles/[profile-name]/chrome/

Monday, January 12, 2009

open gbk encoing files in gedit

$> gconf-editor
It will open "Configuration Edition", and choose /apps/gedit-2/preferences/encoding, edit "auto_detected" key, add "GBK" before "ISO-8859-15".

Friday, January 09, 2009

页面重定向与url中的hash在不同的浏览器中的表现

访问时url上带有hash(如http://localhost/a.php#test),重定向到b.php页面时,当前a.php页上hash会被带到b.php页面上,在Firefox/Opera上测试的效果是如此,但IE6上则直接到b.php页,不会将a.php页上hash值带过来。
示例代码:
a.php
<php
header("Location: b.php");
?>
b.php
<php
?>
访问http://localhost/a.php#test,跳转完成后url为http://localhost/b.php#test

Thursday, January 08, 2009

stack level too deep in will_paginate

After update rails from 1.2.5 to 2.2.2, get below exception:
stack level too deep
../vendor/plugins/will_paginate/lib/will_paginate/finder.rb:81:in `method_missing_without_paginate'
../vendor/plugins/will_paginate/lib/will_paginate/finder.rb:82:in `method_missing'

solution, update will_paginate:
$> script/plugin install git://github.com/mislav/will_paginate.git

Tuesday, January 06, 2009

Difference of String.match and Regexp.exec

The match( ) method is the most general of the String regular-expression methods. It takes a regular expression as its only argument (or converts its argument to a regular expression by passing it to the RegExp( ) constructor) and returns an array that contains the results of the match. If the regular expression has the g flag set, the method returns an array of all matches that appear in the string. For example:

"1 plus 2 equals 3".match(/\d+/g) // returns ["1", "2", "3"]

If the regular expression does not have the g flag set, match( ) does not do a global search; it simply searches for the first match. However, match( ) returns an array even when it does not perform a global search. In this case, the first element of the array is the matching string, and any remaining elements are the parenthesized subexpressions of the regular expression. Thus, if match( ) returns an array a, a[0] contains the complete match, a[1] contains the substring that matched the first parenthesized expression, and so on. To draw a parallel with the replace( ) method, a[n] holds the contents of $n.
For example, consider parsing a URL with the following code:
var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = "Visit my blog at http://www.example.com/~david";
var result = text.match(url);
if (result != null) {
var fullurl = result[0]; // Contains "http://www.example.com/~david"
var protocol = result[1]; // Contains "http"
var host = result[2]; // Contains "www.example.com"
var path = result[3]; // Contains "~david"
}
Finally, you should know about one more feature of the match( ) method. The array it returns has a length property, as all arrays do. When match( ) is invoked on a nonglobal regular expression, however, the returned array also has two other properties: the index property, which contains the character position within the string at which the match begins, and the input property, which is a copy of the target string. So in the previous code, the value of the result.index property would be 17 because the matched URL begins at character position 17 in the text. The result.input property holds the same string as the text variable. For a regular expression r and string s that does not have the g flag set, calling s.match(r) returns the same value as r.exec(s). The RegExp.exec( ) method is discussed a little later in this chapter.
var pattern = /\bJava\w*\b/g;
var text = "JavaScript is more fun than Java or JavaBeans!";
var result;
while((result = pattern.exec(text)) != null) {
alert("Matched '" + result[0] +
"' at position " + result.index +
" next search begins at position " + pattern.lastIndex);
}
When exec( ) is invoked on a nonglobal pattern, it performs the search and returns the result described earlier. When regexp is a global regular expression, however, exec( ) behaves in a slightly more complex way. It begins searching string at the character position specified by the lastIndex property of regexp. When it finds a match, it sets lastIndex to the position of the first character after the match. This means that you can invoke exec( ) repeatedly in order to loop through all matches in a string. When exec( ) cannot find any more matches, it returns null and resets lastIndex to zero. If you begin searching a new string immediately after successfully finding a match in another string, you must be careful to manually reset lastIndex to zero.
Note that exec( ) always includes full details of every match in the array it returns, whether or not regexp is a global pattern. This is where exec( ) differs from String.match( ), which returns much less information when used with global patterns. Calling the exec( ) method repeatedly in a loop is the only way to obtain complete pattern-matching information for a global pattern.

This article copy from OReilly's《JavaScript The Definitive Guide》5th Edition.

Rails module include way

# Rails module include way
# 以下方式的代码在rails中源码中的相当多见,其中的self.included(base)方法是一个回调方法,当此module被其他名为base的module(或者class)include的时候触发此方法。通过class_eval,include,extend加入了实例方法和类方法到base中,代码划分得很干净。

module ActionController
module Components
def self.included(base)
base.class_eval do
include InstanceMethods
extend ClassMethods
helper HelperMethods
end
end

module ClassMethods
end

module HelperMethods
end

module InstanceMethods
end
end
end

Saturday, January 03, 2009

trap of in_array in php

$array = array('testing',0,'name');
var_dump($array);
//this will return true
var_dump(in_array('foo', $array));
//this will return false
var_dump(in_array('foo', $array, TRUE));

Reference:
http://cn.php.net/manual/en/function.in-array.php