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/