2012年9月20日 星期四

xampp phpmyadmin 登不進去 forbidden 403

已經第二次為這個事情傷腦筋了 馬上記錄下來。 C:\xampp\apache\conf\extra 這個路徑裡面的httpd-xampp.conf這個檔案要改

    Order deny,allow
    #Deny from all
    #Allow from ::1 127.0.0.0/8 
    Allow from all 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var

2012年7月4日 星期三

基隆行

黃金博物園區 黃金瀑布 忘憂谷 基隆廟口

2012年6月25日 星期一

mysql dateformat

轉載 http://kevyu.blogspot.tw/2011/03/mysql-datetime-format.html
魚乾的筆記本

mysql datetime format

  • 常用格式
    • 2011-03-28
      DATE_FORMAT(NOW(), '%Y-%m-%d');
  • DATE_FORMAT(date,format)

%M 月名字(January……December)
%W 星期名字(Sunday……Saturday)
%D 有英語前綴的月份的日期(1st, 2nd, 3rd, 等等。)
%Y 年, 數字, 4 位
%y 年, 數字, 2 位
%a 縮寫的星期名字(Sun……Sat)
%d 月份中的天數, 數字(00……31)
%e 月份中的天數, 數字(0……31)
%m 月, 數字(01……12)
%c 月, 數字(1……12)
%b 縮寫的月份名字(Jan……Dec)
%j 一年中的天數(001……366)
%H 小時(00……23)
%k 小時(0……23)
%h 小時(01……12)
%I 小時(01……12)
%l 小時(1……12)
%i 分鐘, 數字(00……59)
%r 時間,12 小時(hh:mm:ss [AP]M)
%T 時間,24 小時(hh:mm:ss)
%S 秒(00……59)
%s 秒(00……59)
%p AM或PM
%w 一個星期中的天數(0=Sunday ……6=Saturday )
%U 星期(0……52), 這裡星期天是星期的第一天
%u 星期(0……52), 這裡星期一是星期的第一天
%% 一個文字「%」。

2012年6月21日 星期四

bbclone

請參照石頭大這個篇文章
http://blog.markplace.net/marks_development_blog/2/2005/05/07/5

大致上就是去把bbclone整個資料夾載下來放到網頁根目錄
然後在系統每頁都會載入的檔案


define("_BBC_PAGE_NAME", "Test");
define("_BBCLONE_DIR", "../../bbclone/");  //這裡路徑自己要設定對
define("COUNTER", _BBCLONE_DIR."mark_page.php");
if (is_readable(COUNTER)) include_once(COUNTER);

這樣子就算安裝好了@_@
然後到bbclone資料夾裡面產生
.htaccess
檔案內容

AuthUserFile C:\xampp\htdocs\bbclone\.htpasswd  #密碼的路徑
AuthType Basic
AuthName "Please Login"
Require valid-user


.htpasswd
檔案內容
帳號:密碼
這兩個檔案


2012年6月19日 星期二

win7 兩個資料夾備份 鏡射

有一個指令可以很快的備份兩個資料夾、並且會辨別差異

robocopy "來源資料夾D:\1" "目的資料夾D:\2" /MIR /E /mt:100

/MIR:將指定的來源資料夾完整備份到指定的目的資料夾,要是檔案都一樣就忽略,;要是檔案不一樣就複製到目的資料夾;要是來源資料夾的檔案已經刪除,則在目的資料夾的這一端也將檔案刪除。所以使用這個指令,可以讓兩個資料夾達到完全同步的效果,尤其在資料夾檔案數目多,而異動的檔案很分散的情況下,非常好用。


/E 子資料夾也複製


/mt:100
通道開到100

2012年6月18日 星期一

網路基本名詞

認證方式 CHAP
是PPP協定的認證協定
PPP協定的認證協定有分兩種
1.PAP、2.CHAP
通常是CHAP

而MTU是訊格的大小
通常使用1500就好,比較不會出問題。

2012年6月1日 星期五

php 環境偵測 ini_get、ini_set

php 環境偵測 ini_get、ini_set

2012年5月31日 星期四

phppgadmin 有時候PHP會沒有連到postgres的模組 postgres postgresql

您的 PHP 環境未安裝必需的資料庫支援。
yum -y install php php-pgsql


然後需要建立一個postgres的密碼
sudo passwd postgres
建立密碼,但是這個帳號是沒有辦法元端連線的


此時這時候服務還沒起來
cd /etc/init.d
ll | grep post
會找到postgresql這個服務
service postgresql restart會發生錯誤,跟你說,還沒有初始化資料庫
這時候先
service postgresql initdb

service postgresql restart


-------
這時候再來建立可以外部連線的帳密
進入postgres的shell
su - postgres
然後
psql template1
這個資料庫

create user twsc_card with PASSWORD 'card20101213';




$conf['extra_login_security'] = false;






默认情况下服务中的postgresql没有启动,需要将该服务前的选择框勾上,点击开始,操作系统报告如下错误:postgresql failedThe error was:/var/lib/pgsql/data is missing. Use “Service postgresql initdb” to initialize the cluster first.说明postgresql数据目前还没有初始化,执行“Service postgresql initdb”服务就立即可以启动了,在命令行方式重启动服务也是使用“Service postgresql restart”,好像和以前有一点点不同。

2012年5月29日 星期二

postgre回復資料資料

備份的時候,是直接用pgadmin來做的
如果要用指令來備份,則用pg_dump來做備份

直接在shell底下

 psql -U postgres -h localhost test2 < /dump.sql
會問你密碼 就OK了

$conf['extra_login_security'] = false;

如果備份出來的是DUMP檔或是BAK
好像就是用pg_restore來做

2012年4月19日 星期四

LINUX phpmyadmin php.ini timeout

因為每次phpmyadmin都一下子就timeout了
所以要去調一下session的時間
/var/html/www/pma //這是我電腦的路徑,網友們的路徑自己要去找一下,而且應該是phpmyadmin不是pma
去/var/html/www/pma/libraries/config.default.inc.php裡面找$cfg['LoginCookieValidity']複製出來
貼到/var/html/www/pma/libraries/config.sample.inc.php檔案裡面。
並改成$cfg['LoginCookieValidity'] = 8*60*60;
然後去修改php.ini
/etc/php.ini 裡面修改session.gc_maxlifetime的值改成28800 (不可以用8*60*60 不知道為什麼...)
//這個隨便設一設
$cfg['blowfish_secret'] = 'sheepisgoodaNimal'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
//還有一個錯誤訊息 "缺少 mcrypt 外掛。請檢查 PHP 設定"

重啟服務service httpd restart

2012年4月18日 星期三

mc Midnight Commander

//安裝mc
yum install mc

...找時間來研究

ftp linux

//安裝FTP
yum install ftp
//ftp 連線主機
//帳號密碼
ftp>                <==最終登入的結果看起來是這樣!
ftp> help           <==提供需要的指令說明,可以常參考!
ftp> dir            <==顯示遠端伺服器的目錄內容 (檔名列表)
ftp> cd /pub        <==變換目錄到 /pub 當中
ftp> get filename   <==下載單一檔案,檔名為 filename 
ftp> mget filename* <==下載多個檔案,可使用萬用字元 *
ftp> put filename   <==上傳 filename 這個檔案到伺服器上
ftp> delete file    <==刪除主機上的 file 這個檔案
ftp> mkdir dir      <==建立 dir 這個目錄
ftp> lcd /home      <==切換『本地端主機』的工作目錄
ftp> passive        <==啟動或關閉 passive 模式
ftp> binary         <==資料傳輸模式設定為 binary 格式
ftp> bye            <==結束 ftp 軟體的使用

//----------

lftp
//安裝lftp
yum install lftp
//首先介紹基本使用
//利用排程進行抓檔同步
//寫一個.sh
#! /bin/bash
lftp
open [主機位置]
user [帳號] [密碼]
cd bk
mirror -R /home
//這樣就會把主機端的/home資料夾 丟到備份機的bk目錄了
//之後就可以使用 lftp -f /xxx.sh 來執行這個script
//如果你要用crontab來排程,再把lftp -f /xxx.sh丟到另一個sh就可以了
//如果發現無法傳輸,甚至沒有辦法執行ls指令,可能是類似防火牆的東西關起來了。
//去/etc/lftp.conf檔案最上頭增加下面這行就OK
//另外要複製的資料夾,權限先開777才有辦法複製。
set ftp:ssl-allow no

2012年4月16日 星期一

rsync 使用

#!/bin/bash
#!/bin/bash

#把.81的home資料丟到.82
localdir="/home" 
remotedir="/home_bk_192.168.4.81"
remoteip="192.168.4.82"
rsync -avz ssh ${localdir} root@${remoteip}:${remotedir}

#把.81的db資料丟到.82
localdir="/var/lib/mysql" 
remotedir="/home_bk_192.168.4.81/"
remoteip="192.168.4.82"
rsync -avz ssh ${localdir} root@${remoteip}:${remotedir}


#把.82的home資料抓回.81
localdir="/home_bk_192.168.4.82" #想備份的兩份資料夾。
remotedir="/home"
remoteip="192.168.4.82"
rsync -av -e ssh root@${remoteip}:${remotedir} ${localdir}

#把.82的db資料抓回.81
localdir="/home_bk_192.168.4.82" #想備份的兩份資料夾。
remotedir="/var/lib/mysql"
remoteip="192.168.4.82"
rsync -av -e ssh root@${remoteip}:${remotedir} ${localdir}

2012年4月15日 星期日

centos6不用密碼就可以立即登入的 ssh 用戶

參考自http://linux.vbird.org/linux_server/0310telnetssh.php

1.
我現在有兩台機器
192.168.4.81
192.168.4.82
我希望81這一台每次SSH進82這台的時候,不用再打登入的密碼,避免crontab卡住。

2.首先進入81這一台,製作一組金鑰

3.接下來把金鑰放到82這一台機器。

4.現在應該準備的東西已經丟到82這一台了
   我們只要設定,讀金鑰的時候要去讀 id_rsa.pub裡面的東西就可以了
   我們現在要把 id_rsa.pub 裡面的東西放到.ssh/authorized_keys
  

  


2012年4月6日 星期五

mysql 去空白~

update members 
set 
title = replace(title,' ',''),
name = replace(name,' ',''),
phone = replace(phone,' ',''),
ext = replace(ext,' ',''),
email = replace(email,' ','')

2012年4月5日 星期四

centos6 安裝 webmin

首先

# vi /etc/yum.repos.d/webmin.repo
把下面的東西貼進去
1
2
3
4
5
[Webmin]
name=Webmin Distribution Neutral
#baseurl=http://download.webmin.com/download/yum
mirrorlist=http://download.webmin.com/download/yum/mirrorlist
enabled=1

然後:打下面這行...

rpm  --import   http://www.webmin.com/jcameron-key.asc

Installing Webmin

# yum install webmin

這樣就安裝好啦

最後網址
你的網址:10000
就可以使用linux的帳號密碼登入了...好像不太安全
出處:http://www.how2centos.com/centos-6-webmin-install/

2012年4月3日 星期二

jquery 基本教學









LPIC 報名


一.註冊LPI ID:

1.先到http://www.lpi.org/ 選中文歡迎進入
2.選左邊的"馬上註冊",進入後名子,地址,國家,能用英文寫就用英文寫,用中文怕日後麻煩
3.若不知英文地址及英文姓名,請到http://www.tslfang.com/book/name.htm 及
http://www.post.gov.tw/post/index.jsp去查詢
4註冊完後會收到LPI ID即可註冊成功 

二,到考試中心報名


5.註冊完LPI ID後,接著請到Prometric申請考試日期及地點,網址為
http://www.prometric.com/Default.htm進入後點選左邊TEST TAKERS
6.然後點選Schedule a Test
7.選擇Information Technology(IT) Certification,然後下拉功能表選Linux Professional
institute,County選Taiwan,State不用選
8.成功能選Locate A Test Site進入,他會透一些考試的電話,說明及價錢,不管他,選Next
9.下一步後會要你選你要考試的科目,請選117-101 OR 117-102,然後下面Language選U.S. ENGLISH
後按next
10.下一步後會出現Available Test Sites,選擇你要考試的考場,選好考場後,點那個考場的Schedule Appointment
11.prometric Login,步驟1~4只是註冊LPI ID,此步是要PROMETRIC的帳號及密碼,若沒有申請,一樣
要到下面的Are you a new user? Clicik here進入註冊
12.註冊完prometric後,login請輸入註冊的email及passwd,若成功會進入
13.進入後即可看到日期及時間可以自己選擇,先點日期,再選時間後按next
14.確認資料無誤後,輸入email及LPI ID及信用卡資料(線上刷卡,若無信用卡,可用別人的,不一定要
自己的),最後按I agree後即可報名成功
15.成功後mail會收到確認信,表示成功囉....mail會給你一組srxxxx的號碼,以後要考試都要用這號
碼去報名,so這組號碼要記得哦..

第二次以後要報名,只需直接到步驟11 login後直接報名即可

考試時間為2小時,不倒扣,請提早到考場報到,500分PASS,總分好像是950~1000,總共考90~98題
,所以不要錯超過20題,應該都會PASS 


出處:http://www.test104.com/tw/board/topic_8214.html

用到的網站整理:
1.http://www.lpi.org/ 申請LPIC ID LPI000253555
2.中華郵政地址翻譯http://www.post.gov.tw/post/index.jsp
No.12, Aly. 12, Ln. 44, Youyong Rd., Pingzhen City, Taoyuan County 324, Taiwan (R.O.C.)
3.http://www.prometric.com/Default.htm 報名考試

bibibibibi

bibi你不見了 啦啦啦啦啦

2012年4月2日 星期一

centos6 安裝札記


20120403
用虛擬機器安裝centos6.2
開啟預設服務等等
adduser eip
passwd eip
-----------
/home/eip/新增public_html/index.htm
-----------
/etc/httpd/conf/httpd.conf
1.左邊#註解拿掉
<Directory /home/*/public_html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>
-----------------
2. disabled註解掉,UserDir public_html打開
<IfModule mod_userdir.c>
    #
    # UserDir is disabled by default since it can confirm the presence
    # of a username on the system (depending on home directory
    # permissions).
    #
    #UserDir disabled

    #
    # To enable requests to /~user/ to serve the user's public_html
    # directory, remove the "UserDir disabled" line above, and uncomment
    # the following line instead:
    #
    UserDir public_html

</IfModule>

1. 先關閉 /etc/selinux/config 的內容
[root@linux ~]# vi /etc/selinux/config
# 將底下的設定值改成這樣:
SELINUX=disabled

---到此為止應該可以進入網址/~eip/裡面的網頁---
然後要去/etc/php.ini改錯誤訊息要不要顯示
error_reporting = E_ALL | E_STRICT
display_errors = On
display_startup_errors = On
log_errors = Off
short_open_tag = On <--- <? 變可以了!
1.short_open_tag  預設變成打開了
2.預設變數一定要有值,$val; <- 犯法 $val=''; <- 合法
  這個真的超討厭的,所以我把這個錯誤訊息關掉了xd,看還會不會出現...
3.date.timezone = "Asia/Taipei" 一定要設

---設定mysql sql
mysql> -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newpass") where User=’root’;
mysql> flush privileges;
mysql> quit

---安裝pma
安裝於/var/www/html

---中間有遇到yum -y update無法執行
是因為DNS設定問題
使用setup 指令修改 dns 並且記得service network restart


---在家裡安裝時,首先要先克服上網問題---
要先把中華電信的小烏龜,設定成硬撥
然後進setup 網卡的東西都要設定好
目前的設定如下:

Name:eth0
Device:eth0
Use DHCP: [ ]
Static IP : 192.168.1.3
Netmask:255.255.255.0
Default gateway IP:192.168.1.1
Primary DNS Server:192.168.1.1

然後修改網卡設定:

vi /etc/sysconfig/network-scripts/ifcfg-eth0
然後把onboot=yes
重開機就搞定一切嚕。




PHP 5.3的改動 與5.2X的差異


http://phorum.study-area.org/index.php/topic,57153.0.html?PHPSESSID=f1onfb52rj4t83rc5vlnk9cke2
詳細情形容後查詢。

1.short_open_tag  預設變成打開了
2.預設變數一定要有值,$val; &lt;- 犯法 $val=''; &lt;- 合法
  這個真的超討厭的,所以我把這個錯誤訊息關掉了xd,看還會不會出現...
3.date.timezone = "Asia/Taipei" 一定要設


  • function name 不能用 namespace (保留字)
  • class name 不能用 Closure (保留字)
  • 加了 goto
  • 處理 array 相關的函式不能直接丟 object 進去了, 得先轉型成 array
  • magic method ( __get, __set 等函式 ) 的 visibility 得為 public
  • FileInfo, intl, Phar, mysqlnd, SQLite3 extensions 納入 PHP Core
  • ncurse, fpdf, dbase, fbsql, ming extensions 從 PHP Core 移出
  • PCRE, Reflection, SPL 無法 disable
  • 可以在 ini 檔案裡使用變數
  • 增加了可以針對網站或目錄的 ini 設定
  • 然後有一些東西 disabled 了, 像是 ereg, Ticks .. 等
原文有提供範例, 詳細多了。 話說終於要支援 SQLite3 了阿~

2012年3月23日 星期五

php htmlspecialchars 遞迴處理

//有一個需求,陣列裡面所有參數都要被一個函式處理過。
//此例是 htmlspecialchars
  $tmpary['a']['a1'] = 'a1v';
  $tmpary['a']['a2'] = 'a2v';
  $tmpary['b'] =  'bv';
  $tmpary = init_htmlargvfilter($tmpary);  //把外來參數,做個過濾。
  init_pre_printr($tmpary);
//fn zone-------------------------------------------------------
function init_htmlargvfilter(&$tmpary) {
  if (is_array($tmpary)) {
    foreach ($tmpary as $k => $v) {
      if (is_array($v)) {
        //於此作遞迴動作
        $tmpary[$k] = init_htmlargvfilter($v);
      } else {
        $tmpary[$k] = htmlspecialchars($v);
      }
    }
  }
  return $tmpary;
}
exit;
//後來寫了一個函式,可以遞迴這樣子處理很多東西
$_REQUEST['a']['a1'] = 'a1v';
$_REQUEST['a']['a2'] = 'a2v';
$_REQUEST['b'] =  'bv';

$_REQUEST = init_array_scan($_REQUEST, 'htmlspecialchars');  //把外來參數,做個過濾。
init_pre_printr($_REQUEST);
//fn zone-------------------------------------------------------
function init_array_scan($tmpary, $user_func) {
  if (is_array($tmpary)) {
    foreach ($tmpary as $k => $v) {
      if (is_array($v)) {
        $tmpary[$k] = init_array_scan($v, $user_func);
      } else {
        $tmpary[$k] = call_user_func($user_func, $v);
      }
    }
  }
  return $tmpary;
}
exit;

2012年3月21日 星期三

2012年3月19日 星期一

啦啦

你噗噗噗噗噗噗逼啦

如何在Blogger裡面使用SyntaxHighlighter 3

整件事情是這樣
1.找到blogger從哪裡讓你可以載入外來JS
2.哪裡有可靠的SyntaxHighlighter讓你從外載入(當然你可以自己架)
3.如何使用

步驟一:


步驟二:



步驟三:
把你的程式碼,用pre標籤包起來

//注意我的標籤故意用全形,到時候自己要修改喔~
<pre class="brush: javascript;" name="code">

</pre>

jquery ui datepicker 民國年 中文化

最近在研究怎麼把datepicker怎麼變成支援民國年

剛好也查到要怎麼把他變成中文化

其實文件就有說明

也許有些人會有些英文苦手

板上也沒看到相關的訊息,就貼上來。

首先,要先去下載中文的參數檔

http://jquery-ui.googlecode.com/svn/trunk/ui/i18n/

應該是最下面那一個

然後很神奇喔,你把他貼在你要使用的那一頁就行了。

例如

<script type="text/javascript">
$(function () {
  $('#test1').datepicker();
});

jQuery(function($){
 $.datepicker.regional['zh-TW'] = {
  closeText: '關閉',
  prevText: '&#x3c;上月',
  nextText: '下月&#x3e;',
  currentText: '今天',
  monthNames: ['一月','二月','三月','四月','五月','六月',
  '七月','八月','九月','十月','十一月','十二月'],
  monthNamesShort: ['一','二','三','四','五','六',
  '七','八','九','十','十一','十二'],
  dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
  dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
  dayNamesMin: ['日','一','二','三','四','五','六'],
  weekHeader: '周',
  dateFormat: 'yy/mm/dd',
  firstDay: 1,
  isRTL: false,
  showMonthAfterYear: true,
  yearSuffix: '年'};
 $.datepicker.setDefaults($.datepicker.regional['zh-TW']);
});
</script>

如果你覺得每次這樣要使用貼很麻煩 你當然也可以貼到jquery ui.js那個檔案裡面喔
基本上放在檔案最下面就搞定了。

最後發現我不用真的把套件變成民國年。
只要西元年顯示之前去-19110000就是我想要的效果了

$(function () {
  $('#test1').datepicker({ 
    dateFormat: "yymmdd",
    onSelect: function(dateText, inst) {
      dateText = dateText-19110000;
      $(this).val(dateText);
    },    
  });
});

延伸閱讀
http://aqr199.blog.ithome.com.tw/post/411/62016
http://maxclapton.comoj.com/?p=383

公司公佈欄規劃

資料庫方面
database:twnsc_eip
table:bulletin (公佈欄)
columns:
s_num 主鍵
title 標題
cont 內容
cate 分類
views 瀏覽次數
priority 優先權

b_empno      產生註記
b_proc       產生註記
b_date       產生註記
m_empno      修改註記
m_proc       修改註記
m_date       修改註記
d_empno      刪除註記
d_proc       刪除註記
d_date       刪除註記

畫面方面
1.程式編號(其實就是英文檔名)
2.程式名稱(中文名稱,暫定公佈欄)
3.版型要被限制,不能太大,要可以以變數控制整個大小
4.在同一頁裡面就要有
  _公告條列區
  _公告顯示區
  _公告查詢區
  _公告頁數區(上下都要有)
  _公告分類區

2012年3月17日 星期六

Code Conventions for the JavaScript Programming (javascript 程式編碼慣例)


Code Conventions for the JavaScript Programming Language

javascript 程是語言的編寫規範


This is a set of coding conventions and rules for use in JavaScript programming. It is inspired by the Sun document Code Conventions for the Java Programming Language. It is heavily modified of course because JavaScript is not Java.
The long-term value of software to an organization is in direct proportion to the quality of the codebase. Over its lifetime, a program will be handled by many pairs of hands and eyes. If a program is able to clearly communicate its structure and characteristics, it is less likely that it will break when modified in the never-too-distant future.
Code conventions can help in reducing the brittleness of programs.
All of our JavaScript code is sent directly to the public. It should always be of publication quality.
Neatness counts.


這些是使用javascript程是語言的一些規範規則
是由昇陽的文件Code Conventions for the Java Programming Language所提倡
不過當然被大量的修改了,因為javascript並不是java
軟體的長期價值對於一個組織直接影響了整個程式碼的質量
整個生命週期,一個程式會被無數的手和眼處理過
如果一個城市能夠很明瞭的傳達他的結構與特色,也就比較不會出錯當在那"不久的將來"修改的時候

程式規範可以幫助減少程式痛苦的部分
所有我們的javascript是直接的被送到使用者面前,這應該也要有一個給出版等級的質量
乾淨整齊是必要的

JavaScript Files

JavaScript programs should be stored in and delivered as .js files.
JavaScript code should not be embedded in HTML files unless the code is specific to a single session. Code in HTML adds significantly to pageweight with no opportunity for mitigation by caching and compression.
<script src=filename.js> tags should be placed as late in the body as possible. This reduces the effects of delays imposed by script loading on other page components. There is no need to use the language or type attributes. It is the server, not the script tag, that determines the MIME type.

javascript 檔案javascript程式應該被儲存或是被引用當作一個.js檔案
javascript程式碼應該不要被包在HTML裡面除非那些程式碼是確切使用在單一狀況
在HTML裡面的程式碼嚴重影響網頁大小還沒有機會去透過快取或是壓縮來紓解
<script src=filename.js>  標籤應該盡可能的被放置在body標籤的最後面
這減少了因為讀取script而延遲其他網頁元件載入的狀況。並不需要使用language或是type屬性
這是server標籤,不是程式碼標籤。決定了MIME的形式(http://zh.wikipedia.org/wiki/MIME)

Indentation

The unit of indentation is four spaces. Use of tabs should be avoided because (as of this writing in the 21st Century) there still is not a standard for the placement of tabstops. The use of spaces can produce a larger filesize, but the size is not significant over local networks, and the difference is eliminated by minification.


縮排
縮排的單位是四個空白,使用tab應該要被避免因為(當現在是21世紀)這並沒有一個標準
這個使用空白可以避免增大檔案,但是大小並不是很重要透過本機網路,且差異可以被忽略就由此縮小

Line Length

Avoid lines longer than 80 characters. When a statement will not fit on a single line, it may be necessary to break it. Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion. The next line should be indented 8 spaces.

避免一行超過80個字,當一個呈述單行放不下的時候,應該需要做斷行
斷行在一個操作符的後面,逗點更好。
斷行在一個操作符後面減少了剪貼錯誤的可能性,將會導致被複製一半的插入所覆蓋。
下一行,應該要被縮排八個空白。

Comments

Be generous with comments. It is useful to leave information that will be read at a later time by people (possibly yourself) who will need to understand what you have done. The comments should be well-written and clear, just like the code they are annotating. An occasional nugget of humor might be appreciated. Frustrations and resentments will not.
It is important that comments be kept up-to-date. Erroneous comments can make programs even harder to read and understand.
Make comments meaningful. Focus on what is not immediately visible. Don't waste the reader's time with stuff like
    i = 0; // Set i to zero.
Generally use line comments. Save block comments for formal documentation and for commenting out.


註解
註解多多益善,這是很有用的去留下重要訊息。馬上就會有需要的人來讀(很可能就是你本人)
去了解你做了甚麼。註解應該仔細又乾淨,就好像那些那些程式碼在說話。一點偶然的幽默是不錯的,沮喪或是生氣到是不必。
這是很重要的註解必須加上日期,謬誤的註解會讓程式更難以被理解
讓註解有意義,聚焦在那些一時留意不到的重點。不要浪費時間在無聊的註解
一般來說,使用行註解
區塊註解則是正式文件的時候再使用。

Variable Declarations

All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied globals. Implied global variables should never be used.
The var statements should be the first statements in the function body.
It is preferred that each variable be given its own line and comment. They should be listed in alphabetical order.
    var currentEntry; // currently selected table entry
    var level;        // indentation level
    var size;         // size of table
JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
Use of global variables should be minimized. Implied global variables should never be used.

宣告變數
所有的變數應該在使用前宣告
javascript是不需要,但是這樣會讓程式更易讀更容易去查到未被宣告的變數便成了全域變數
表示,全域變數是不該被使用的
var這個敘述 應該是函式本身內的第一件事情
每一個變數應該被給予自己獨立一行和註解,應該按照字母排列

    var currentEntry; // currently selected table entry
    var level;        // indentation level
    var size;         // size of table
javascript 並沒有區塊生命週期(http://home.so-net.net.tw/tzuyichao/javascript/lab.function.04.html)
所以定義變數在區塊{}裡面會讓那些經歷過C(JAVA)系列語言的人感到困惑
請在函式一開始的時候就定義變數
使用儘可能的不使用全域變數,全域變數不應該被使用。

Function Declarations

All functions should be declared before they are used. Inner functions should follow the var statement. This helps make it clear what variables are included in its scope.
There should be no space between the name of a function and the ( (left parenthesis) of its parameter list. There should be one space between the ) (right parenthesis) and the { (left curly brace)that begins the statement body. The body itself is indented four spaces. The } (right curly brace) is aligned with the line containing the beginning of the declaration of the function.



函式宣告
所有的函式應該在使用前就被宣告。函式內應該遵照var陳述
這對維持變數使用範圍清晰有很大的幫助
函式與左括弧(應該不能有空白
應該要有一個空白在右括弧和左大括號
這個涵式本身應該有四隔空白
右大括號是應該被安排在與函式一開始對齊



    function outer(c, d) {
        var e = c * d;

        function inner(a, b) {
            return (e * a) + b;
        }

        return inner(0, 1);
    }




This convention works well with JavaScript because in JavaScript, functions and object literals can be placed anywhere that an expression is allowed. It provides the best readability with inline functions and complex structures.

這個習慣在javascript運作良好 因為在javascript中,函式跟物件可以被放置在任何地方表示式式被允許的地方。這提供了最好的可讀性在行內函式還有複雜的結構



    function getElementsByClassName(className) {
        var results = [];
        walkTheDOM(document.body, function (node) {
            var a;                  // array of class names
            var c = node.className; // the node's classname
            var i;                  // loop counter

// If the node has a class name, then split it into a list of simple names.
// If any of them match the requested name, then append the node to the set of results.

            if (c) {
                a = c.split(' ');
                for (i = 0; i < a.length; i += 1) {
                    if (a[i] === className) {
                        results.push(node);
                        break;
                    }
                }
            }
        });
        return results;
    }
If a function literal is anonymous, there should be one space between the word function and the ( (left parenthesis). If the space is omited, then it can appear that the function's name isfunction, which is an incorrect reading.
在匿名函式的狀況下,應該會有一個空白在function與左括號之間
如果這個空白被忽略,則表示這個function的名稱是function,這是不正確的理解用法
    div.onclick = function (e) {
        return false;
    };

    that = {
        method: function () {
            return this.datum;
        },
        datum: 0
    };
Use of global functions should be minimized.
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

應該盡量不要用全域函式
當一個函式是準備被馬上啟用的,這整個運算應該被包覆在圓括弧裡面
這樣一來,產生的是函式的值而不是函式本身就很清楚了
var collection = (function () {
    var keys = [], values = [];

    return {
        get: function (key) {
            var at = keys.indexOf(key);
            if (at >= 0) {
                return values[at];
            }
        },
        set: function (key, value) {
            var at = keys.indexOf(key);
            if (at < 0) {
                at = keys.length;
            }
            keys[at] = key;
            values[at] = value;
        },
        remove: function (key) {
            var at = keys.indexOf(key);
            if (at >= 0) {
                keys.splice(at, 1);
                values.splice(at, 1);
            }
        }
    };
}());

Names

Names should be formed from the 26 upper and lower case letters (A .. Za .. z), the 10 digits (0 .. 9), and _ (underbar). Avoid use of international characters because they may not read well or be understood everywhere. Do not use $ (dollar sign) or \ (backslash) in names.
Do not use _ (underbar) as the first character of a name. It is sometimes used to indicate privacy, but it does not actually provide privacy. If privacy is important, use the forms that provideprivate members. Avoid conventions that demonstrate a lack of competence.
Most variables and functions should start with a lower case letter.
Constructor functions which must be used with the new prefix should start with a capital letter. JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted. Bad things can happen if new is not used, so the capitalization convention is the only defense we have.
Global variables should be in all caps. (JavaScript does not have macros or constants, so there isn't much point in using all caps to signify features that JavaScript doesn't have.)

命名
命名應該由大寫和小寫的英文字母和數字和底線組成
避免使用國際字元 因為這並不是每個地方都被使用或了解
不要使用$或是\在名稱當中
不要使用底線當作名稱的第一個字
有時候這是被拿來使用當作"私有"
但是實際上卻沒有作用
如果私有很重要,使用提供私有成員的格式
避免顯示能力不足的習慣
大部分的函式變數要以小寫字元開始
建構子函式應該被伴隨著new來使用用大寫字元來起頭
javascript問題並不是編譯時警告也不是執行的時候警告當一個必備的new被省略
有時候就是很雖如果new沒有被使用,大小字母習慣是我們最後一道防線
全域變式應該全部大寫(javascript不是一個宏觀的或是永久的,所以不需要很多使用大寫或是強調,javascript不需要)

Statements

Simple Statements

Each line should contain at most one statement. Put a ; (semicolon) at the end of every simple statement. Note that an assignment statement which is assigning a function literal or object literal is still an assignment statement and must end with a semicolon.
JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence of semicolon insertion. The only expressions that should be used as statements are assignments and invocations.

陳述

簡單陳述
每一行最多一個陳述,放一個;在每一個簡單陳述的結尾
注意指派陳述不管是指派一個函式或是一個物件衣就算是一個指派陳述,依舊用分號做結尾
javascript讓任何表示都當作陳述式般使用
這樣可能大有問題,尤其是分號出現的時候
唯一應該被當作陳述的表達就是指派陳述或祈使句

Compound Statements

Compound statements are statements that contain lists of statements enclosed in { } (curly braces).
  • The enclosed statements should be indented four more spaces.
  • The { (left curly brace) should be at the end of the line that begins the compound statement.
  • The } (right curly brace) should begin a line and be indented to align with the beginning of the line containing the matching { (left curly brace).
  • Braces should be used around all statements, even single statements, when they are part of a control structure, such as an if or for statement. This makes it easier to add statements without accidentally introducing bugs.

混和陳述

混和陳述是一堆陳述被大括號包覆
裡面的陳述應該有四個以上的縮排
左括號應該在混合陳述的開始的那一橫的結尾
右括弧應該與左括號對齊
括號應該在陳述式的周圍附近,即便只有一行
當她們是控制結構的一部分的時候,例如說if或是for,這會讓增加陳述更加簡單而不會引起意外的傳入錯誤

Labels

Statement labels are optional. Only these statements should be labeled: whiledoforswitch.

return Statement

return statement with a value should not use ( ) (parentheses) around the value. The return value expression must start on the same line as the return keyword in order to avoid semicolon insertion.

文字標籤

陳述文字是可有可無的,只有以下的陳述應該被標記
return 陳述
一個return陳述的值不應該使用()來包覆
必須開始在return那一行為了去避免分號插入的錯誤。

if Statement

The if class of statements should have the following form:
    if (condition) {
        
statements
    }

    if (
condition) {
        
statements
    } else {
        
statements
    }

    if (
condition) {
        
statements
    } else if (
condition) {
        
statements
    } else {
        
statements
    }

for Statement

for class of statements should have the following form:
    for (initializationconditionupdate) {
        
statements
    }

    for (
variable in object) {
        if (
filter) {
            
statements
        }
    }
The first form should be used with arrays and with loops of a predeterminable number of iterations.
The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object:
    for (variable in object) {
        if 
(object.hasOwnProperty(variable)) {
            
statements
        }
    }

while Statement

while statement should have the following form:
    while (condition) {
        
statements
    }

do Statement

do statement should have the following form:
    do {
        
statements
    } while (
condition);
Unlike the other compound statements, the do statement always ends with a ; (semicolon).

switch Statement

switch statement should have the following form:
    switch (expression) {
    case 
expression:
        
statements
    default:
        
statements
    }
Each case is aligned with the switch. This avoids over-indentation.
Each group of statements (except the default) should end with breakreturn, or throw. Do not fall through.

try Statement

The try class of statements should have the following form:
    try {
        statements
    } catch (variable) {
        statements
    }

    try {
        statements
    } catch (variable) {
        statements
   } finally {
        statements
    }

continue Statement

Avoid use of the continue statement. It tends to obscure the control flow of the function.

避免使用continue陳述 這很容易擾亂控制流

with Statement

The with statement should not be used.

Whitespace

Blank lines improve readability by setting off sections of code that are logically related.
Blank spaces should be used in the following circumstances:
  • A keyword followed by ( (left parenthesis) should be separated by a space.
        while (true) {
  • A blank space should not be used between a function value and its ( (left parenthesis). This helps to distinguish between keywords and function invocations.
  • All binary operators except . (period) and ( (left parenthesis) and [ (left bracket) should be separated from their operands by a space.
  • No space should separate a unary operator and its operand except when the operator is a word such as typeof.
  • Each ; (semicolon) in the control part of a for statement should be followed with a space.
  • Whitespace should follow every , (comma).

空白

空白行藉由設定邏輯上關聯的區塊增加了可讀性
空白應該被使用在下面的狀況
1.關鍵字跟從誇號應該用空白分隔
2.不要用在一個 function和他的參數括號之間
這幫助了區別關鍵字和函式祈使句

Bonus Suggestions

更多建議

{} and []

Use {} instead of new Object(). Use [] instead of new Array().
Use arrays when the member names would be sequential integers. Use objects when the member names are arbitrary strings or names.

{}和[]

使用{}代替new Object()
使用[]代替new Array()
使用陣列當成員名稱是有序數字
使用物件當成員名稱是任意文字

, (comma) Operator

Avoid the use of the comma operator except for very disciplined use in the control part of for statements. (This does not apply to the comma separator, which is used in object literals, array literals, var statements, and parameter lists.)

逗號 

避免使用逗號

Block Scope

In JavaScript blocks do not have scope. Only functions have scope. Do not use blocks except as required by the compound statements.

在javascript沒有block scope區域範圍這件事 只有函示範圍 不要使用blocks的特性除非混和陳述需要

Assignment Expressions

Avoid doing assignments in the condition part of if and while statements.
Is
    if (a = b) {
a correct statement? Or was
    if (a == b) {
intended? Avoid constructs that cannot easily be determined to be correct.

避免指派變數在if和while裡面

是故意的嗎?避免這種很難判斷正確與否的結構

=== and !== Operators.

It is almost always better to use the === and !== operators. The == and != operators do type coercion. In particular, do not use == to compare against falsy values.

=== 與 !-== 操作符

總是多多使用 === 還有!== 
== 和 != 會做型別轉換
尤其,不要使用 ==來比對易錯的值

Confusing Pluses and Minuses

Be careful to not follow a + with + or ++. This pattern can be confusing. Insert parens between them to make your intention clear.
    total = subtotal + +myInput.value;
is better written as
    total = subtotal + (+myInput.value);
so that the + + is not misread as ++.

小心不要使用+ 或是++在一個+後面
這種格式很容易被混淆
插入圓括弧在她們之間使你的意圖更明顯

eval is Evil

The eval function is the most misused feature of JavaScript. Avoid it.
eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.

eval是惡魔
eval函式是一個在javascript最常被誤用特性的函式,避免它
eval有化名的,不要使用function建構子 不要傳字串給setTimeout或是setInterval




延伸閱讀:http://blog.othree.net/log/2010/08/02/javascript-best-practice-1/