import functools
## Check return type and value.
# @details The return value could be one following situation:
# 1. value type is specified in the \a cls;
# 2. None;
# 3. value type is not specified and not None.
#
# In the 1st situation, return original value.
# In the 2nd situation, if allow_none is true, return None; otherwise, return \a default.
# In the 3rd situation, raise SyntaxError.
# @param default is the default return value.
# @param cls is the specified return value type.
# @param allow_none - if true, the return value could be None; otherwise, the return value must be assigned.
# @exception SyntaxError
def checkReturn(default, allow_type = None, allow_none = False):
def check_decorator(function):
def decorator_wrapper(*args, **kwargs):
result = function(*args, **kwargs)
cls = allow_type
try:
if allow_type is None:
cls = (type(default),)
elif not issubclass(allow_type, tuple):
cls = (allow_type,)
except Exception as e:
raise
if type(result) in cls:
pass
elif result is None:
if allow_none:
pass
else:
result = default
else:
raise SyntaxError("The type of return value {0} is not in {1}.".format(result, cls))
return result
return decorator_wrapper
return check_decorator
2014年7月23日 星期三
Python - decorator運用(2)
在撰寫函式時,因為python的特性,不會去檢查回傳值的資料型態是否正確,也不會去檢查是否遺漏回傳值,這對於撰寫複雜一點的函式容易有疏忽的地方,這時候就能靠decorator做一些協助,例如遺漏回傳值時補上預設回傳值,或者回傳值型態錯誤時丟出例外錯誤。
Python - decorator運用(1)
在trace程式碼的時候,尤其是多執行緒的程式碼,想知道函式的呼叫情況,此時會記錄函式的進出資訊。在python,可以使用decorator幫助記錄。
另外,有時需要記錄函式的執行時間,一樣可以使用decorator幫助記錄。
在這裡的logger是指logging.logger。
decorator的使用方式為:
import functools
import time
def logFunc(logger = None):
def log_decorator(function):
@functools.wraps(function)
def decorator_wrapper(*args, **kwargs):
if logger is None:
print("{2} [Debug] Enter {0}.{1}".format(function.__module__, function.__name__, time.asctime()))
result = function(*args, **kwargs)
print("{2} [Debug] Exit {0}.{1}".format(function.__module__, function.__name__, time.asctime()))
else:
logger.debug("Enter {0}.{1}".format(function.__module__, function.__name__))
result = function(*args, **kwargs)
logger.debug("Exit {0}.{1}".format(function.__module__, function.__name__))
return result
return decorator_wrapper
return log_decorator
另外,有時需要記錄函式的執行時間,一樣可以使用decorator幫助記錄。
import functools
import time
def logTime(logger = None):
def time_decorator(function):
def decorator_wrapper(*args, **kwargs):
start = time.time()
result = function(*args, **kwargs)
end = time.time()
if logger is None:
print("{3} [Debug] {0}.{1} spent {2:.3f} seconds.".format(function.__module__, function.__name__, end - start, time.asctime()))
else:
logger.debug("{0}.{1} spent {2:.3f} seconds.".format(function.__module__, function.__name__, end - start))
return result
return decorator_wrapper
return time_decorator
在這裡的logger是指logging.logger。
decorator的使用方式為:
@logFunc(logger)
def foo1():
# expressions
@logTime(logger)
def foo2():
# expressions
2014年5月28日 星期三
C++ - 整數運算之溢位偵測
整數運算中,最容易產生溢位問題的估計是階層運算。設計一個factorial遞回函式來運算階層,輸入是一個整數N,輸出則為N!的結果,輸入和輸出的整數資料型態一致,假設使用unsigned int作為整數資料型態,該factorial函式表示如下:
如果是兩個整數相加,溢位會多增加一個位元,可以檢查兩個整數相加是否會有進位現象,進位後會不會超出資料型態的位元數,來判斷相加會不會產生溢位。
可是階層運算是乘法運算,無法用相加的溢位判斷方式,而要用其他的方式判斷。
方式一:溢位旗標的判斷。因為暫存器的關係,僅適用於int、unsigned int等32位元的整數資料型態,若用於其他位元數的整數資料型態會判斷錯誤。
方法二就已經足夠使用,方法三就留給以後需要的時候再來實作。
unsigned int factorial(unsigned int N)這是很簡單的一個寫法,用unsigned int是因為階層的定義要求為正整數或0。這個寫法並沒考量到溢位問題,當輸入的N為13時,就會產生溢位問題。
{
return (N == 0 || N == 1) ? 1 : N * factorial(N - 1);
}
如果是兩個整數相加,溢位會多增加一個位元,可以檢查兩個整數相加是否會有進位現象,進位後會不會超出資料型態的位元數,來判斷相加會不會產生溢位。
可是階層運算是乘法運算,無法用相加的溢位判斷方式,而要用其他的方式判斷。
方式一:溢位旗標的判斷。因為暫存器的關係,僅適用於int、unsigned int等32位元的整數資料型態,若用於其他位元數的整數資料型態會判斷錯誤。
unsigned int factorial(unsigned int N)方法二:除法運算檢查。適用各種整數資料型態。
{
unsigned int product = 0;
product = (N == 0 || N == 1) ? 1 : N * factorial(N - 1);
__asm jo overflowed;
if (0)
{
overflowed:
throw(std::out_of_range("Overflowed"));
}
return product;
}
int factorial(int N)方法三:自訂BigInteger的資料型態。 BigInteger的數字是使用字元陣列來表示,運算採取字元陣列的方式做運算,加減乘除也需要自訂,因為是用字元陣列來表示一個數字,所以該數字理論上可以無限大(實際上會受限字元陣列所能表示的最大長度)。
{
int product = 0;
if (N < 0) // 限定N為正整數或0
{
throw(std::out_of_range("Negative integer"));
}
if (N == 0 || N == 1)
{
product = 1;
}
else
{
int multiplicand = factorial(N - 1);
product = N * multiplicand;
if (product / N != multiplicand) throw(std::out_of_range("Overflowed"));
}
return product;
}
方法二就已經足夠使用,方法三就留給以後需要的時候再來實作。
2014年5月8日 星期四
Doxygen - 圖形化類別關聯性
Doxygen是一套利用程式註解的方式,建立出程式說明文件的軟體。
Graphviz是一套利用命令和參數畫出關係圖的軟體。
Doxygen產出文件時,可以透過參數設定,使用Graphviz來繪圖。操作步驟為:
最後,建立完文件,在類別分類中就可以看到關係圖了。
Graphviz是一套利用命令和參數畫出關係圖的軟體。
Doxygen產出文件時,可以透過參數設定,使用Graphviz來繪圖。操作步驟為:
最後,建立完文件,在類別分類中就可以看到關係圖了。
2013年12月6日 星期五
Python - 函示宣告與呼叫順序
Python因為是直譯式語言,函式必須要先宣告才能呼叫,所以很常看到main函式寫在程式檔案的後面。但是,如果想先寫呼叫再宣告函式,也是可以的,只要利用from import:(範例檔為test.py)
執行後的輸出為:
from test import *
if __name__ == "__main__":
main()
def main():
print("main")
sub()
def sub():
print("sub")
執行後的輸出為:
main
sub
2013年2月19日 星期二
C# - 表格排版與隱藏元件
想要的效果:
問題與解決方法:
- GUI呈現為表單輸入。
- 配合不同編譯版本,表單上的輸入控制項有一些需要被隱藏起來。
問題與解決方法:
- 同一份程式碼,要有不同編譯版本,採用Predefined macro(#if、#define、#elif……)。
- C#的GUI排版有FlowLayoutPanel和TableLayoutPanel。為了讓GUI呈現表單的整齊格式,採用TableLayoutPanel來排版。
- 要隱藏控制項,因為表單上的控制項是已知,所以要被隱藏的控制項設定狀態為Hide,包含相關的Label也要一併隱藏。
2013年1月22日 星期二
Windows - batch檔案的暫停執行
執行batch檔(.bat),若想讓指令暫緩執行,可以利用特殊技巧來實現,例如想要暫停10秒鐘,可以在想暫停的地方用ping指令來達到這個目的:
@ping 127.0.0.1 -n 10 -w 1000 > nul
訂閱:
文章 (Atom)