Archive for the ‘Programming/misc’ Category.

PHP Coding Standards

參考: Mantis : http://www.mantisbt.org/guidelines.php

中文翻譯: http://www.ichiayi.com/wikipage/tech/mantis_coding

First, start off by reading the PHP Coding Standards document. I’ve deviated in a few places but just about everything in the document applies here as well.

Above all, write code that is easy to read and maintain. Comment blocks of code and functions at all times. And get on my case if I deviate too much as well!

Naming Variables
  • Use all lower case.
  • Use _ to separate words, e.g. $green_color_value
  • Use descriptive names (except loop variables).
  • Loop variables can be of the usual variety: $i, $j, $k, etc.
  • Count variables should follow the format $*_count, e.g. $bug_count
  • Global variables should be prefixed with g_
  • Temporary variables should be prefixed with t_
  • Parameters and variables passed from forms that have been cleaned of any special SQL chars (i.e. slashes) should be prefixed with c_
  • Uncleaned function parameters should be prefixed with p_
  • Uncleaned variables passed from forms should be prefixed with f_
  • Other variables are prefixed with v_, v2_, etc.
  • Never prefix with l_ or o_ or q_ (visually confusing)
  • $query and $result should be used for SQL query and results respectively
Naming Functions
  • Use all lower case.
  • Use _ to separate words, e.g. setup_page_breaks()
  • Keep functions to 5 words or less
  • Functions that print should be prefixed with print_.
  • Try to use prefixes to group functions (i.e., email_, news_, etc.)
Naming Classes
  • Use FirstLetterOfWordIsCaptilized style
  • Variables that are class objects should have the prefix coo_
Naming Files
  • Use all lower case.
  • Use _ to separate words, e.g. view_new_bugs_page.php
  • Use .php file extensions
  • Filenames must be less than 32 characters in length. This plays nice with older file systems like Mac OS.
  • Included files should be suffixed by _inc.php
SQL formatting
  • UPPERCASE all SQL keywords:
    $query = "SELECT *
    	FROM $g_mantis_bug_table
    	WHERE id='1'";
  • Always assign a query string to a variable. This makes code easier to debug when problems occur. Do not create the query in the call to the function.
  • Break up SQL queries over multiple lines to be easy to read.
General Formatting
  • Use TABS with a size of 4
  • Follow the table formatting of existing pages
  • Use <?php ?> for php delimiters.
  • Try not to print/echo HTML unless it’s short or in a function loop
  • Do not use the EOF construct
Miscellaneous
  • Don’t use the ?: construct except in very rare cases. It is confusing and has a lot of bug potential.
  • Avoid magic numbers. The only magic numbers in use should be 1 and 0 and their meaning should be obvious.
Page Guidelines
  • The first item should be the copyright notice
  • At the bottom will be the footer information and closing print_ functions.
Braces and Parantheses
  • Parantheses should be right after a function name, e.g. function() not function ()
  • Parantheses should have a space right after a keyword (if, while, for), e.g. for (…)
  • Formatting of braces is illustrating below. We use unmatched placing.
  • Arrays should be referenced with no spaces, e.g. $arr['index'] not $arr[ 'index' ]
    for (...) {
        blah
    }
    
    or
    
    if (...) {
        blah
    }
  • if … else blocks should be in this format:
    if (...) {
        blah1
    } else {
        blah2
    }
Comparisons
  • The NOT operator should be placed next to its operand. No spaces, e.g. !$value
  • Parentheses should be used for grouping, especially with multiple comparisons, e.g. if ( ( null == $val ) && ( null == $val2 ) )
Strings
  • Use spaces around the string concatenation operator, e.g. ‘str ‘ . $value . ‘ str2′;
  • Use ‘ instead of " if there are no variables or special characters.
Comments
  • Use the # symbol for line commenting, not //
  • Use /* */ for block commenting unless you nest /* */ comments. Generally, only use this during development.
  • Use @@@ followed by a brief message (BROKEN, TEMPORARY, etc) as a "look at this" indicator. Leaving your name next to is a good idea. This way critical items can easily be found.
Editor Features
  • Search and replace in multiple files
  • Goto line number
  • Syntax highlighting
  • Adjustable TAB spacing

Protected: css 命名方式參考 / CSS Naming Standards

This post is password protected. To view it please enter your password below:


中文 字詞 文章 索引 對照規畫

tbl_term

term_id term
1 ipod
2 apple
3 nano
4 iphone

tbl_doc

doc_id text_content uptime
1 【蘋果先生】Moshi iGlaze Apple iPhone 3G 專用保護殼 黑/紅/白
2 iTunes Gift Card蘋果線上音樂商店預付卡儲值Apple iTunes Shop Ipod Nano Shuffle iphone Mp3電影歌曲下載促銷
3 Apple iPhone 3G (8G)  

tbl_lookup

id term_id doc_id
1 2 1
2 4 1
3 2 2
4 1 2
5 3 2
6 4 2
7 2 3
8 4 3

Protected: [好文] 這個人實在太強了

This post is password protected. To view it please enter your password below:


[c code] 檢查某檔案是否存在 – check file exists using C

FILE* fp = fopen(path, "r");
if (fp) {
    // file exists
    fclose(fp);
} else {
    // file doesn't exist
}

解決 error while loading shared libraries 的方法

執行程式時, 若遇到

./update_item: error while loading shared libraries: libsqlrclientwrapper-0.40.so.1: cannot open shared object file: No such file or directory

像這樣的錯誤訊息 , 表示程式中所需的 so 檔(share library) 沒找到 , 要修改 /etc/ld.so.conf 加上這個目錄 , 改完要下 ldconfig –v 讓路徑生效

可以用 ldd 看該程式所使用到的 shared library 有那些, 及 lib 路徑

—–

以下是 gentoo 的標準解法 , 其他版本的 linux 則不太相同!!

cat /etc/ld.so.conf   這個檔是由 env-update 產生的 , 所以再繼續看一下 /etc/env.d 下 , 究竟有啥

# ld.so.conf autogenerated by env-update; make all changes to
# contents of /etc/env.d directory
/usr/local/lib
/usr/i686-pc-linux-gnu/lib
/usr/lib/gcc/i686-pc-linux-gnu/4.1.2
/usr/lib/gcc/i686-pc-linux-gnu/4.1.1
/usr/local/firstworks/lib

參考資料, 這是 compile sqlrelay 列出來的 information

See any operating system documentation about shared libraries for

more information, such as the ld(1) and ld.so(8) manual pages.

———————————————————————-

/bin/sh ../../libtool –mode=finish /usr/local/firstworks/lib

PATH=”$PATH:/sbin” ldconfig -n /usr/local/firstworks/lib

———————————————————————-

Libraries have been installed in:

/usr/local/firstworks/lib

If you ever happen to want to link against installed libraries

in a given directory, LIBDIR, you must either use libtool, and

specify the full pathname of the library, or use the `-LLIBDIR’

flag during linking and do at least one of the following:

- add LIBDIR to the `LD_LIBRARY_PATH’ environment variable

during execution

- add LIBDIR to the `LD_RUN_PATH’ environment variable

during linking

- use the `-Wl,–rpath -Wl,LIBDIR’ linker flag

- have your system administrator add LIBDIR to `/etc/ld.so.conf’

在 /etc/env.d 下建立一個 90sqlrelay

內容是

LDPATH="/usr/local/firstworks/lib"

再run : env-update , 就看到 /etc/ld.so.conf 多了正確的 lib path 了

Protected: [摘] 2009.0122 : code sample , coding convention

This post is password protected. To view it please enter your password below:


[C CODE] BIG5 (ascii) to UTF-8 轉碼 sample code – use iconv , libiconv

#include "iconv.h"
#define MAX_STRING_LEN 10*1024

char tmp[MAX_STRING_LEN];
char p2[MAX_STRING_LEN];
iconv_t cd;
int v1 , v2;
char *sin , *sout;

cd = iconv_open("utf-8","big5");
if (cd==0) return -1;

// ----> LOOP
sin=p2;
sout=tmp;
v1=strlen(p2)+1;
v2=MAX_STRING_LEN;
if ( !iconv(cd,&sin,&v1,&sout,&v2) ) strcpy(dat[26],tmp);
else strcpy(dat[26],"Error");

// ----> LOOP END

iconv_close(cd);

這邊看到一句話:

首先 iconv_open() 函式就是做 “開啟” 動作,也就是當我們要將編碼系統 A 轉換到編碼系統 B 時,必須先呼叫此函式,將 FROMENC 設成編碼系統 A 的名字,同時將 TOENC 設成編碼系統 B 的名字,這時此函式就會做類似檔案開啟的動作,傳回一個代表此轉換管道的資料結構 iconv_t 供後續使用。事實上,在系統的實作中真的是將 iconv_open() 當作 “開啟檔案” 來處理,故它會受到目前系統或同一行程中可開啟檔案數所限,如果系統或程式的其他部分已開啟了太多的檔案以至於逼近系統上限,則有可能這邊的 iconv_open() 會失敗。

我想到一個問題 , 不曉得 PHP 裡面的 iconv 函式是否有同樣問題, 好像用 mbstring 安全一些!!

看來寫這種 convert encoding 的程式 真的要很小心 , 避免把 iconv_open 寫進 loop 裡面 , 免得他造成吃記憶體怪物!!

Sample code , 用 getopt 取得 command line 的參數

5c30343361478502ed9711dd38115baf

#include "stdlib.h"
#include "stdio.h"
#include "getopt.h"
#include "string.h"

void print_help(int exval);
char program[100] = "sample";

int main(int argc, char *argv[]) {
  int opt;
  strcpy(program,argv[0]);
  if (argc == 1) print_help(1);
  while((opt = getopt(argc, argv, "hVvf:o:")) != -1) {
    switch(opt) {
      case 'h':
        print_help(0);
        break;
      case 'V':
        printf("%s", program);
        exit(0);
        break;
      case 'v':
        printf("%s: Verbose option is set '%c'\n", program, optopt);
        break;
      case 'f':
        printf("%s: Filename %s\n", program, optarg);
        break;
      case 'o':
        printf("Output: %s\n", optarg);
        break;
      case ':':
        fprintf(stderr, "%s: Error - Option '%c' needs a value\n\n", program, optopt);
        print_help(1);
        break;
      case '?':
        fprintf(stderr, "%s: Error - No such option: '%c'\n\n", program, optopt);
        print_help(1);
    }
  }

  for(; optind < argc; optind++) printf("argument: %s\n", argv[optind]);
  return 0;
}

// -----
void print_help(int exval) {
  printf("Usage: %s [-h] [-V] [-f FILE] [-o FILE]\n\n", program);
  printf(" -h print this help and exit\n");
  printf(" -V print version and exit\n\n");
  printf(" -v set verbose flag\n");
  printf(" -f FILE set intput file\n");
  printf(" -o FILE set output file\n\n");
  exit(exval);
}

我的 subversion / svn server 設定

OS : Gentoo Linux 2.6.22-gentoo-r5 #11

gcc –version
gcc (GCC) 4.1.2 (Gentoo 4.1.2 p1.1)

svnserve –version
svnserve, version 1.5.4 (r33841)
   compiled Dec 17 2008, 08:11:10

/usr/bin/svnserve –foreground –daemon –root=/var/svn

很奇怪 , 裝法都一樣, 但我另一台 MLP Lite 就不 work??

b3427f82eb24f02a7a8c162d19f344c6 

74fe80d6a738a7f3beb1c6da3e33b80f

 

一些 subversion command 下的操作:

用 svn co 一個 source 到目錄下 , 把要加到 svn  的檔案/目錄 copy 過來 , 下 svn status 會看到一堆 ? 表示那些是新的檔案

e7cd532c5adf186cfae84be0973cfcf6

下 svn add * 或 svn add dirname

84befb5056c4efb725a40ba8ef42577f

下 svn status 可以看到 剛剛的 ? 變成 A 了 (add)

eaf23dbfa9a596768ee8e351bb792062

下 svn ci 把 source code commit 進 svn

5ffc7c116629e31e25b3b274d4f9ee4a

cd 到工作目錄

svn –username monster export svn://xxx.com/my_repos/search/src

把 source code export 出來

這段字會加上底線

[code language='html']
這段字會加上底線
[/code]

21 ways to streamline your CSS

如果程式語言是艘船, 那麼 …. 是….

Virtual appliance

看到 http://virtualappliances.net/ 這裡面立即提供了 5 總 ready to go 的 appliance  , 只要 “抓下來 / 啟動 就立即可用” —> 這就是 virtual appliance 的精神 , 看了這頁頓時覺得 這些 appliance 真的對 developer 非常 friendy , 看看這頁
http://virtualappliances.net/documentation/readme/README.lamp.html

裝好立即有

  • Apache HTTP Server
  • PHP
  • Perl
  • Python
  • ZendOptimizer (www.zend.com)
  • MySQL
  • phpMyAdmin

然後要開發就只要到它開放的 samba  目錄下寫程式即可 , 這點跟我包裝的 Monster LAMP Pack 精神是相同的.

opensolaris / Optimized Open Source Software Stack (Cool Stack)

看到一個有用的套件

for the Sun Solaris Operating System(TM)

http://cooltools.sunsource.net/coolstack/

Cool Stack includes several packages in the SVR4 package format, so you can install just the ones you need. Some of the applications in Cool Stack already ship with Solaris, but these are either older versions and/or not built with full optimization. Further, Cool Stack has been pre-configured to have the most popular applications (Apache, PHP, MySQL) to work seamlessly out of the box.
Deploying PHP From Cool Stack in Sun Java System Web Server

Configuring Cool Stack PHP With Web Server

Next, do the following:

1. Go to the Cool Stack PHP 5 installation location. Type:

cd /opt/coolstack/php5

In that directory is a script called setup-ws7-php.sh.

2. Run setup-ws7-php.sh. Type:

./setup-ws7-php.sh

This message is displayed:

Usage:
This script will configure Coolstack PHP with Sun Java System Web Server
7. Here, you will need to provide the top level location of your Web Server
7 installation and your Web Server 7 instance_name name to which this
script should configure to run PHP scripts.

Enter your Web Server installation location(/sun/webserver7):

3. Type the full path for your Web Server installation.

The script then prompts you to type a Web Server instance name. That name is the path to a directory in your installation location—one that contains all the configuration files for running your Web site. If you are using Web Server in Sun Java Enterprise System 5, your instances are under /var/opt/SUNWwbsvr7.

For the example in this article, cite the instance https-coolstack that you created previously. To enable a different instance for PHP, type that instance name. Your instance is then ready for PHP, which you can deploy with Cool Stack 1.2 PHP on Web Server.

Finally, do the following:

1. Start Web Server. Type:

/sun/webserver7/https-coolstack/bin/startserv

2. Create sample PHP files under /sun/webserver7/https-coolstack/docs.

Protected: Senna for mysql install 安裝說明

This post is password protected. To view it please enter your password below:


mysql c api 設定執行時的 timeout 時間

int fnSetTimeout(int timeout) {
  char **row;
  char sql[100];
  char data[200];

  sprintf(sql,"set session wait_timeout=%d",timeout);
  if ( mysql_real_query( &mysql, sql, strlen(sql) ) ) {
    printf("FAILED : %s\n",sql);
    exit(3);
  }

  sprintf(sql,"set session interactive_timeout=%d",timeout);
  if ( mysql_real_query( &mysql, sql, strlen(sql) ) ) {
    printf("FAILED : %s\n",sql);
    exit(3);
  }

  strcpy(sql,"select @@session.interactive_timeout" );
  if ( mysql_real_query( &mysql, sql, strlen(sql) ) ) {
    printf("FAILED : %s\n",sql);
    exit(3);
  }

  if ( (result=mysql_store_result(&mysql)) != NULL ) {
    row=mysql_fetch_row(result);
    strcpy( data, row[0] );
    mysql_free_result( result );
    timeout=atoi(data);
  } else {
    timeout=0;
  }

  return(timeout);
}

adject file descriptors

On Unix, each TCP/IP connection uses a file descriptor, so you must increase the total number of descriptors available to the operating system, and also increase the maximum number of descriptors each process is allowed to use. All Unix style operating systems have a “ulimit” shell command (sh and bash) which can allow more open file descriptors to commands started in that shell, once the appropriate kernel tweak has been made. We recommend “ulimit -n 8192″. Here are our recommended kernel tweaks:

Linux: “echo 65536 > /proc/sys/fs/file-max” changes the number of system-wide file descriptors

FreeBSD: append to /etc/sysctl (or you can use sysctl -w to add these)

kern.maxfiles=65536
kern.maxfilesperproc=32768

Solaris: add the following to /etc/system and reboot:

set rlim_fd_max=0×8000
set rlim_fd_cur=0×8000