html5canvas integrated

HTML语言: html5canvas综合
<!DOCTYPE html>            <!--13.10.31  16:57-->
<html lang="zh">
<head>
<meta charset="gb2312" />
<title>canvas</title>
<meta name="keyword" content="canvas web" />
<meta name="description" content="" />
<meta name="generator" content="Notepad2" />
<meta name="author" content="Quentin" />
<meta name="robots" content="all" />
<meta http-equiv="windows-target" content="_top" />
<style>
canvas{border:2px solid red;}
</style>
<script>
function drawShape(){
 // get the canvas element using the DOM
 var canvas = document.getElementById('tutorial');

 // Make sure we don't execute when canvas isn't supported
 if (canvas.getContext){

   // use getContext to use the canvas for drawing
   var ctx = canvas.getContext('2d');

  // Draw shapes
   roundedRect(ctx,12,12,150,150,15);
   roundedRect(ctx,19,19,150,150,9);
   roundedRect(ctx,53,53,49,33,10);
   roundedRect(ctx,53,119,49,16,6);
   roundedRect(ctx,135,53,49,33,10);
   roundedRect(ctx,135,119,25,49,10);/*与下面的function roundedRect共同作用*/

   // Character 1/*黑方块*/
   ctx.beginPath();
   ctx.arc(37,37,13,Math.PI/7,-Math.PI/7,false);
   ctx.lineTo(34,37);
   ctx.fill();                        /*咬*/

   // blocks
   for(i=0;i<8;i++){
     ctx.fillRect(51+i*16,35,4,4);
   }
   for(i=0;i<6;i++){
     ctx.fillRect(115,51+i*16,4,4);
   }
   for(i=0;i<8;i++){
     ctx.fillRect(51+i*16,99,4,4);    
   }

   // character 2/*幽灵*/
   ctx.beginPath();
   ctx.moveTo(83,116);
   ctx.lineTo(83,102);
   ctx.bezierCurveTo(83,94,89,88,97,88);
   ctx.bezierCurveTo(105,88,111,94,111,102);
   ctx.lineTo(111,116);
   ctx.lineTo(106.333,111.333);
   ctx.lineTo(101.666,116);
   ctx.lineTo(97,111.333);
   ctx.lineTo(92.333,116);
   ctx.lineTo(87.666,111.333);
   ctx.lineTo(83,116);
   ctx.fill();                      
 
   /*白色的眼框*/
   ctx.fillStyle = "white";
   ctx.beginPath();
   ctx.moveTo(91,96);
   ctx.bezierCurveTo(88,96,87,99,87,101);
   ctx.bezierCurveTo(87,103,88,106,91,106);
   ctx.bezierCurveTo(94,106,95,103,95,101);
   ctx.bezierCurveTo(95,99,94,96,91,96);
   ctx.moveTo(103,96);
   ctx.bezierCurveTo(100,96,99,99,99,101);
   ctx.bezierCurveTo(99,103,100,106,103,106);
   ctx.bezierCurveTo(106,106,107,103,107,101);
   ctx.bezierCurveTo(107,99,106,96,103,96);
   ctx.fill();                          
 
   /*黑色的眼睛*/
   ctx.fillStyle = "black";
   ctx.beginPath();
   ctx.arc(101,102,2,0,Math.PI*2,true);
   ctx.fill();
   ctx.beginPath();
   ctx.arc(89,102,2,0,Math.PI*2,true);
   ctx.fill();
 } else {
   alert('You need Safari or Firefox 1.5+ to see this demo.');
 }
}


/*6个矩形圆角框一起画出*/
function roundedRect(ctx,x,y,width,height,radius){
 ctx.beginPath();
 ctx.moveTo(x,y+radius);
 ctx.lineTo(x,y+height-radius);
 ctx.quadraticCurveTo(x,y+height,x+radius,y+height);
 ctx.lineTo(x+width-radius,y+height);
 ctx.quadraticCurveTo(x+width,y+height,x+width,y+height-radius);
 ctx.lineTo(x+width,y+radius);
 ctx.quadraticCurveTo(x+width,y,x+width-radius,y);
 ctx.lineTo(x+radius,y);
 ctx.quadraticCurveTo(x,y,x,y+radius);
 ctx.stroke();
}

</script>
</head>
<body onload="drawShape()">
<canvas id="tutorial" width="400" height="400"></canvas>
</body>
</html>

Python : How Smart cars to find the path of plan

# Grid format:
#   0 = Navigable space
#   1 = Occupied space

grid = [[0, 0, 1, 0, 0, 0],
        [0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 1, 1, 1, 0],
        [0, 0, 0, 0, 1, 0]]

init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1] # Make sure that the goal definition stays in the function.

delta = [[-1, 0 ], # go up
        [ 0, -1], # go left
        [ 1, 0 ], # go down
        [ 0, 1 ]] # go right
delta_name = ['^', '<', 'v', '>']

cost = 1

def print_expand(expand):
    for i in range(len(expand)):
        print(expand[i])

def print_path(action):
    path = [[' ' for col in range(len(grid[0]))] for row in range(len(grid))]
    x, y = goal[0], goal[1]
    path[goal[0]][goal[1]] = '*'
    while x != init[0] or y != init[1]:
        # 下面x,y 都要变化,所以这里提取temp,delta_name取下标就不会错
        temp = action[x][y]
        opposite = (temp - 2) % len(delta)
        x += delta[opposite][0]
        y += delta[opposite][1]
        path[x][y] = delta_name[temp]
    for i in range(len(path)):
        print(path[i])

# breadth-first search shorest path, and print the track.
def search_breadth_first_1D():
    xboundary = len(grid) - 1
    yboundary = len(grid[0]) - 1
    search_list = [[0, init[0], init[1]]]
    result = []
    action = [[-1 for col in range(yboundary+1)] for row in range(xboundary+1)]
    closed = [[0 for col in range(yboundary+1)] for row in range(xboundary+1)]
    closed[init[0]][init[1]] = 1
    expand = [[-1 for col in range(yboundary+1)] for row in range(xboundary+1)]
    expand[init[0]][init[1]] = 0
    expand_count = 1
   
    while search_list:
        #search_list.sort() breadth-first 已经是按照g-value(距离Start点的距离) 排序好的。
        current = search_list.pop(0)
        for i in range(len(delta)):
            x1 = current[1] + delta[i][0]
            y1 = current[2] + delta[i][1]
            if x1 < 0 or x1 > xboundary or y1 <0 or y1 > yboundary or grid[x1][y1] or closed[x1][y1]:
                continue
            if x1 == goal[0] and y1 == goal[1]:
                result.append([current[0]+cost, x1, y1])
                # 终点赋值一次,expand和 action 就都不再赋值,这样能得到最短路径
                if expand[goal[0]][goal[1]] == -1: # 一般(expand[goal[0]][goal[1]] > expand_count) 条件不成立,因为短路径先到达终点,且expand_count 是递增赋值的
                    expand[x1][y1] = expand_count
                    expand_count += 1
                    action[x1][y1] = i # for back propagation
            else:
                search_list.append([current[0]+cost, x1, y1])
                closed[x1][y1] = 1
                expand[x1][y1] = expand_count
                expand_count += 1
                action[x1][y1] = i # for back propagation

    print_expand(expand)
    print_path(action)
    if result == []:
        return 'fail'
    else:
        result.sort()
        return result#.pop(0)
print(search_breadth_first_1D())
print('\n')


# compute the value,like heuristic.Then easily get the policy.
# dynamic programming
def compute_value():
    value = [[999 for row in range(len(grid[0]))] for col in range(len(grid))]
    closed = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
   
    x, y = goal[0], goal[1]
    value[x][y] = 0
    closed[x][y] = 1
    temp = [[x, y]]

    # 从后往前搜索,填写距离终点的距离数
    while temp:
        x, y = temp.pop(0)
        for i in range(len(delta)):
            x1 = x + delta[i][0]
            y1 = y + delta[i][1]
            if x1 < 0 or x1 >= len(grid) or y1 < 0 or y1 >= len(grid[0]) or grid[x1][y1] or closed[x1][y1]:
                continue
            v2 = value[x][y] + cost
            if v2 > value[x1][y1]:
                continue
            temp.append([x1, y1])
            closed[x1][y1] = 1
            value[x1][y1] = v2

    # 从前往后传播,得到每个点的周围四点中,距终点最近的一个,确认此点的方向
    policy = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]          
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if grid[i][j]:
                continue
            temp = []
            for k in range(len(delta)):
                x1 = i + delta[k][0]
                y1 = j + delta[k][1]
                if x1 >= 0 and y1 >= 0 and x1 < len(grid) and y1 < len(grid[0]) and grid[x1][y1] == 0:
                    temp.append([value[x1][y1], k])
            if temp == []:
                continue
            temp.sort()
            lowest = temp.pop(0)
            if value[i][j] > lowest[0]:
                policy[i][j] = delta_name[lowest[1]]
    policy[goal[0]][goal[1]] = '*'
    print_expand(policy)
    return value
   
a = compute_value()
for i in a:
    print(i)
print('\n')


# You are given a car in a grid with initial state
# init = [x-position, y-position, orientation]
# where x/y-position is its position in a given
# grid and orientation is 0-3 corresponding to 'up',
# 'left', 'down' or 'right'.
#
# Your task is to compute and return the car's optimal
# path to the position specified in `goal'; where
# the costs for each motion are as defined in `cost'.
#
# grid format:
#     0 = navigable space
#     1 = occupied space
grid = [[1, 1, 1, 0, 0, 0],
        [1, 1, 1, 0, 1, 0],
        [0, 0, 0, 0, 0, 0],
        [1, 1, 1, 0, 1, 1],
        [1, 1, 1, 0, 1, 1]]
goal = [2, 0] # final position
init = [4, 3, 0] # first 2 elements are coordinates, third is direction
cost = [2, 1, 20] # the cost field has 3 values: right turn, no turn, left turn

# there are four motion directions: up/left/down/right
# increasing the index in this array corresponds to
# a left turn. Decreasing is is a right turn.

forward = [[-1,  0], # go up
           [ 0, -1], # go left
           [ 1,  0], # go down
           [ 0,  1]] # do right
forward_name = ['up', 'left', 'down', 'right']

# the cost field has 3 values: right turn, no turn, left turn
action = [-1, 0, 1]
action_name = ['R', '#', 'L']

def optimum_policy2D():
    value = [[[999 for row in range(len(grid[0]))] for col in range(len(grid))], # 距终点的各个方向的距离
             [[999 for row in range(len(grid[0]))] for col in range(len(grid))],
             [[999 for row in range(len(grid[0]))] for col in range(len(grid))],
             [[999 for row in range(len(grid[0]))] for col in range(len(grid))]]
    policy = [[[' ' for row in range(len(grid[0]))] for col in range(len(grid))], # 距终点各个方向上的走向
             [[' ' for row in range(len(grid[0]))] for col in range(len(grid))],
             [[' ' for row in range(len(grid[0]))] for col in range(len(grid))],
             [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]]
    policy2D = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]

    change = True
    while change:
        change = False
        # go through all grid cells and calculate values
        for x in range(len(grid)):
            for y in range(len(grid[0])):
                for orientation in range(4):
                    if goal[0] == x and goal[1] == y:
                        if value[orientation][x][y] > 0:
                            value[orientation][x][y] = 0
                            policy[orientation][x][y] = '*'
                            change = True
                    elif grid[x][y] == 0:

                        # calculate the three ways to propagate value
                        for i in range(3):
                            o2 = (orientation + action[i]) % 4
                            x2 = x + forward[o2][0]
                            y2 = y + forward[o2][1]

                            if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]) and grid[x2][y2] == 0:
                                # 从后往前搜索,填写value的过程。可以把x2,y2,o2看成goal的位置和方向,x,y,orientation走一步后到2,所以1的值=2的值+转向的值
                                # 相当于从前往后,不断的减去转向的值,到终点时,相减的结果变成了0
                                v2 = value[o2][x2][y2] + cost[i] # tricky
                                if v2 < value[orientation][x][y]:
                                    value[orientation][x][y] = v2
                                    policy[orientation][x][y] = action_name[i]
                                    change = True
                                   
    x, y, orientation = init[0], init[1], init[2]
    policy2D[x][y] = policy[orientation][x][y]
    while policy[orientation][x][y] != '*':
        if policy[orientation][x][y] == '#':
            o2 = orientation
        elif policy[orientation][x][y] == 'R':
            o2 = (orientation - 1) % 4
        elif policy[orientation][x][y] == 'L':
            o2 = (orientation + 1) % 4
        x += forward[o2][0]
        y += forward[o2][1]
        orientation = o2
        policy2D[x][y] = policy[orientation][x][y]

    for i in range(len(policy2D)):
        print(policy2D[i])
       
def optimum_policy2D_abandon(): # 结果是一个一维的东西,不是三维的思维
    value = [[[999 for row in range(len(grid[0]))] for col in range(len(grid))],
             [[999 for row in range(len(grid[0]))] for col in range(len(grid))],
             [[999 for row in range(len(grid[0]))] for col in range(len(grid))],
             [[999 for row in range(len(grid[0]))] for col in range(len(grid))]]
    ori = [[[-1 for row in range(len(grid[0]))] for col in range(len(grid))],
           [[-1 for row in range(len(grid[0]))] for col in range(len(grid))],
           [[-1 for row in range(len(grid[0]))] for col in range(len(grid))],
           [[-1 for row in range(len(grid[0]))] for col in range(len(grid))]]
    policy2D = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]
    for i in range(len(value)):
        value[i][goal[0]][goal[1]] = 0
        ori[i][goal[0]][goal[1]] = i
    back_cost = cost[:]
    back_cost.reverse()

    # 4种在终点的初始回溯方向  
    for idx in range(len(value)):
        change = True
        while change:
            change = False
            for i in range(len(grid)):
                for j in range(len(grid[0])):
                    if grid[i][j] == 1 or ori[idx][i][j] == -1:
                        continue
                   
                    for k in range(len(action)):
                        direction = (ori[idx][i][j] + action[k]) % len(forward)
                        x1 = i + forward[direction][0]
                        y1 = j + forward[direction][1]
                        if x1 < 0 or x1 >= len(grid) or y1 < 0 or y1 >= len(grid[0]) or grid[x1][y1] == 1:
                            continue
                        else:
                            new_cost = back_cost[k] + value[idx][i][j]
                            if new_cost < value[idx][x1][y1]:
                                value[idx][x1][y1] = new_cost
                                ori[idx][x1][y1] = direction
                                change = True
    for idx in range(len(value)):
        # 逆溯时方向相反,需要反向
        ori[idx][init[0]][init[1]] = (ori[idx][init[0]][init[1]] + 2) % len(forward)
        direction_diff = (ori[idx][init[0]][init[1]] - init[2]) % len(forward)
        # 下面是不严格的推导,因为可能转向时遇到障碍物
        if direction_diff == 1:
            # 开始的方向加一个左转的cost,取代了原来直走一格的cost
            value[idx][init[0]][init[1]] += cost[2] - cost[1]
        elif direction_diff == 3:
            value[idx][init[0]][init[1]] += cost[0] - cost[1]
        elif direction_diff == 2:
            # 反向要左转三次、右转一次,或者相反,取代原来走的2格cost
            if (cost[0]*3 + cost[2]) > (cost[2]*3 + cost[0]):
                value[idx][init[0]][init[1]] += (cost[2]*3 + cost[0]) - 2*cost[1]
            else:
                value[idx][init[0]][init[1]] += (cost[0]*3 + cost[2]) - 2*cost[1]
        else:
            pass
    # 取出最小的一个
    temp = value[0][init[0]][init[1]]
    index = 0
    for idx in range(1, len(value)):
        if temp > value[idx][init[0]][init[1]]:
            temp = value[idx][init[0]][init[1]]
            index = idx

    for i in ori[index]:
        print(i)
    for i in value[index]:
        print(i)
   
    policy2D[goal[0]][goal[1]] = '*'
    x, y = goal[0], goal[1]
##    while x != init[0] or y != init[y]:
##        x = x + forward[ori[index][x][y]][0]
##        y = y + forward[ori[index][x][y]][1]
##        policy2D[x][y] = '#'
    return policy2D



success_prob = 0.5                    
failure_prob = (1.0 - success_prob)/2.0 # Probability(stepping left) = prob(stepping right) = failure_prob
collision_cost = 100                  
cost_step = 1

def stochastic_value():
    value = [[1000 for row in range(len(grid[0]))] for col in range(len(grid))]
    policy = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]
    value[goal[0]][goal[1]] = 0
    policy[goal[0]][goal[1]] = '*'
    change = True
    while change:
        change = False
        for x in range(len(grid)):
            for y in range(len(grid[0])):
                if grid[x][y]: continue
                for direct in range(len(delta)):
                    v2 = cost_step
                    for turn in range(-1, 2):
                        i = (direct + turn) % len(delta)
                        x1 = x + delta[i][0]
                        y1 = y + delta[i][1]
                        if turn == 0:
                            p2 = success_prob
                        else:
                            p2 = failure_prob
                        if x1 < 0 or x1 >= len(grid) or y1 < 0 or y1 >= len(grid[0]) or grid[x1][y1]:
                            v2 += p2 * collision_cost
                        else:
                            v2 += p2 * value[x1][y1]
                    if v2 < value[x][y]:
                        value[x][y] = v2
                        policy[x][y] = delta_name[direct]
                        change = True

    return value, policy
a,b = stochastic_value()
print_expand(a)
print_expand(b)

def stochastic_value_abandon():
    value = [[1000 for row in range(len(grid[0]))] for col in range(len(grid))]
    policy = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]
    value[goal[0]][goal[1]] = 0
    policy[goal[0]][goal[1]] = '*'
    change = True
    while change:
        change = False
        update = [[goal[0], goal[1]]]
        while update:
            x, y = update.pop(0)
            for i in range(len(delta)):
                x1 = x + delta[i][0]
                y1 = y + delta[i][1]
                if x1 < 0 or x1 >= len(grid) or y1 < 0 or y1 >= len(grid[0]) or grid[x1][y1]:
                    continue
                lvalue = (i - 1) % 4
                rvalue = (i + 1) % 4
                lx, ly = x1 + delta[lvalue][0], y1 + delta[lvalue][1]
                rx, ry = x1 + delta[rvalue][0], y1 + delta[rvalue][1]
                if lx < 0 or lx >= len(grid) or ly < 0 or ly >= len(grid[0]) or grid[lx][ly]:
                    lvalue = collision_cost
                else:
                    lvalue = value[lx][ly]
                if rx < 0 or rx >= len(grid) or ry < 0 or ry >= len(grid[0]) or grid[rx][ry]:
                    rvalue = collision_cost
                else:
                    rvalue = value[rx][ry]
                v2 = success_prob * value[x][y] + failure_prob * (lvalue + rvalue) + cost_step
                if v2 < value[x1][y1]:
                    value[x1][y1] = v2
                    update.append([x1, y1])
                    change = True
    return value, policy

# As you see, dynamic programming for planning is very inefficient.
# It has to go through the entire map to search whether there is a change.
# Google map search is split the entire map into pieces, then calculate
# each piece, this is a litter better.

Batchfile语言: weeinst

atchfile语言: weeinst
!BAT wee install script for grub4dos by chenall http://chenall.net/post/grub4dos_instwee/
debug off
checkrange 20101230:-1 read 0x8278 || goto :help
::对临时变量所使用的内存0x60000进行初始化(置0操作)
echo -n > (md)0x300+2
clear
write (md)0x300+1 %1 || goto :help
::检测第一个参数,如果是menu则跳到menu块执行.
checkrange 0x756e656d read 0x60000 && goto :menu
:0x30:0x39 是 0-9的ASCII码
checkrange 0x30:0x39 read 0x60000 || goto :help
cat (md)0x300+1,1 | call :confirm hd
exit

:menu
write (md)0x301+1 %2 || goto :Error
checkrange 0x30:0x39 read 0x60200 || goto :help
cat --locate=wee (hd%2)+1,0x1b0 || goto :failed
map --mem=0xf000 (hd%2)50+13 (rd)
:::自动检测菜单位置,注以下内容比较复杂,没有弄懂不要乱改,否则可能导致写盘出错.
debug 1
cat --locate=\xB0\x02\x1A\xCE --number=1 (rd)+1 > (md)0x300+1,8
debug off
cat (md)0x300+1,8 | echo -n | calc *0x60010=16+0x
calc *0x82d8=13<<9-*0x60010
calc *0x82d0=0x1E00000+*0x60010
::没有指定菜单文件参数显示当前菜单内容.
cat --length=0 %3 || goto :show_menu
echo Importing wee menu..
calc *0x82d8=*0x8290+0x1f&0xff0
cat %3 > (rd)+1
calc *0x82d0=0x1E00000+*0x60010-16
cat (md)0x300+1,5 | echo -n | dd if=(rd)+1 of=(hd%2)50+13 bs=1 seek=0x
echo succeeded!
exit

:show_menu
debug 1
cat --locate=\0 --number=1 (rd)+1 > (md)0x301+1,4
debug off
cat (md)0x301+1,4 | echo -n | calc *0x82d8=0x
clear
echo -P:0715 $[0104]wee menu export
echo -e -P:0408 $[0104]wee $[0003]install script for $[0106]grub4dos $[0105]by chenall
echo -P:0535 $[0003]http://chenall.net/post/grub4dos_instwee/
cat (rd)+1
exit

:confirm
checkrange 0xEE parttype (%1,0) && call :Err_msg Not support GPT DISK!
echo -e -P:0810 $[1104]Warning: $[0004]Will install wee63.mbr to %1 \n\n\n\t$[0003]Please press $[0002]'Y' $[0003]to confirm, any other keys to exit...
echo -e -P:0408 $[0104]wee $[0003]install script for $[0106]grub4dos $[0105]by chenall
echo -P:0535 $[0003]http://chenall.net/post/grub4dos_instwee/
checkrange 0x59,0x79 pause || call :Err_msg Cancelled.
:install
echo checking...
map --mem=0xF000 /boot/grub/wee63.mbr (rd) || call :Err_msg /boot/grub/wee63.mbr not found.
cat --locate=wee (rd)+1,0x1b8 || call :Err_msg wee63.mbr file.
::检测WEE63.MBR是否正确
dd if=(rd)+1 of=(md)0x300+1 bs=1 count=4 skip=0x86
checkrange 0xCE1A02B0 read 0x60000 || call :Err_msg wee63.mbr file.
call :check_installed %1
echo Installing...
::备份原来的MBR到第二扇区如果已经安装则直接备份第二扇区
checkrange 840202 read 0x60004 && dd if=(%1)1+1 of=(rd)1+1 ! dd if=(%1)+1 of=(rd)1+1
::复制分区表到第1扇区
dd if=(%1)+1 of=(rd)+1 skip=0x1b8 seek=0x1b8 bs=1
::检测是否有menu.wee文件
cat --length=0 /BOOT/GRUB/MENU.WEE && call :inst_menu
::写入硬盘前63扇区
dd if=(rd)+1 of=(%1) count=63
echo Good luck! succeeded!
exit

:inst_menu
::debug 1是必须的,因为我们要提取结果.
debug 1
::定位菜单开始位置
cat --locate=\xB0\x02\x1A\xCE --number=1 (rd)50+10 > (md)0x300+1,8
debug off
cat (md)0x300+1,5 | echo -n | calc *0x60010=50<<9+16+0x
::设置rd-base在菜单开始位置这样可以就直接用(rd)+1的方式来访问菜单内容.
calc *0x82D0=0x1E00000+*0x60010
::菜单长度,menu.wee文件长度,16字节对齐.最长不超过4KB
calc *0x82D8=*0x8290+0x1f&0xff0
::写入菜单
cat /BOOT/GRUB/MENU.WEE > (rd)+1
::重新计算rd-base和rd-size.
calc *0x82D8=*0x8290+0xf&0xff0+*0x60010
calc *0x82D0=0x1E00000
exit

:check_installed
cat --locate=wee (%1)+1,0x1b8 || exit
echo wee already installed,Press 'R' to reinstall.
checkrange 0x52,0x72 pause || exit 5
write 0x60004 840202
exit

:failed
echo failed!
exit 3

:Err_msg
echo
echo Error: %1 %2 %3 %4 %5 %6 %7 %8 %9
pause Press any key to continue . . .
exit 1

:Error
:help
echo -e Usage:\n Install wee\t instwee NUM\n show menu\t instwee menu NUM\n import menu\t instwee menu NUM weemenufile\ne.g.:\tinstall wee to (hd0)\n\tinstwee 0
echo Notes: You must use grub4dos-0.4.5b-2010-12-30 or later!
exit 1

batch scp

#!/bin/sh
if [ $# -ne 1 ]
then
echo "usage: $0 directory";
exit;
fi

list=$(cat ips | xargs)

for ip in $list
do
scp -r $1 root@$ip:$1
done

PHP Intercept robot

<?php

function getrobot() {
    if(!defined('IS_ROBOT')) {
        $kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
        $kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
        if(!strexists($_SERVER['HTTP_USER_AGENT'], 'http://') && preg_match("/($kw_browsers)/i", $_SERVER['HTTP_USER_AGENT'])) {
            define('IS_ROBOT', FALSE);
        } elseif(preg_match("/($kw_spiders)/i", $_SERVER['HTTP_USER_AGENT'])) {
            define('IS_ROBOT', TRUE);
        } else {
            define('IS_ROBOT', FALSE);
        }
    }
    return IS_ROBOT;
}
getrobot();
if(defined('NOROBOT') && IS_ROBOT) {
    exit(header("HTTP/1.1 403 Forbidden"));
}

C++ Recursive perfectionist array analysis

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int a[3]={1,2,3,};
inline void display()
{
    cout<<"交换中"<<endl;
    for (int i=0;i<3;i++)
    {
        cout<<a[i];
    }
    cout<<endl;
}
void Perm(int *a,int k,int m)
{
    display();
   
    if (k==m)
    {
        for (int i=0;i<m;i++)
        {
            cout<<a[i];
        }
        cout<<endl;
    }
    else
    {
        for (int i=0;i<m;i++)
        {
            swap(a[k],a[i]);
            Perm(a,k+1,m);
            swap(a[k],a[i]);
            cout<<"此时i的值是:"<<i<<endl;
        }
    }
}
int main()
{
   
    Perm(a,0,3);
    return 0;
}

C++ socket client side

#include<sys/socket.h> //for socket
#include<stdio.h>
#include<unistd.h> // for close
#include<stdlib.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<pthread.h> // for thread
#include<string.h>
#include<sys/stat.h> // for fstat
#include<sys/mman.h> //for mmap

#define PORT 5123
#define MAX_LEN 1500
#define EACH_DATA 1040
#define SERVER "127.0.0.1"

char sendbuff[MAX_LEN];
char recvbuff[10];

int main(int argc, char ** argv)
{
   
    int sockfd;
    struct sockaddr_in servaddr;
    int filesize = 0;
    int sendtime = 0;
    struct stat statbuf;
    FILE * fp = NULL;
    char * src= NULL;
    char * cur_src = NULL;
    char serverip[40]={'\0'};

    memcpy(serverip, SERVER, sizeof(SERVER));

    if(argc != 2)
    {
        fprintf(stderr, "usage client <filename>.");
        return 1;
    }

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(PORT);

    inet_pton(AF_INET, serverip, &servaddr.sin_addr);

    //printf("address =%s\n ",argv[1]);
    if(connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))==-1)
    {
        printf("client connect faliure.");
        return 1;
    }
   

    //first send filename
    char filename[100]={'\0'};
    int filenamelen = strlen(argv[1]);
    memcpy(filename, argv[1], filenamelen);

    char *p = (char *) &filenamelen;
    //memcpy(sendbuff+1, p, 4);
    memcpy(sendbuff, p, 4);
    memcpy(sendbuff+4,filename,filenamelen);

    printf("len =%d filename=%s\n",filenamelen, filename);

    send(sockfd, sendbuff, filenamelen+4, 0);
    //printf("here\n");

    //start to send file
    fp = fopen(filename, "rb+");
    if(fstat(fileno(fp), &statbuf) < 0)
    {
        fprintf(stderr,"fstate failure.");
        return 1;
    }

    filesize = statbuf.st_size;
    sendtime = filesize / EACH_DATA;
    if(filesize % EACH_DATA !=0)
        sendtime +=1;

    if((src = (char *)mmap(0, statbuf.st_size, PROT_READ, MAP_SHARED, fileno(fp), 0)) == MAP_FAILED)
    {
        fprintf(stderr, "mmap failure");
        fclose(fp);
        return 1;
    }
    fclose(fp);

    cur_src = src;
    int t_len =0;
    while(sendtime > 0)
    {
        if(sendtime > 1)
        {
            t_len = EACH_DATA;
            memcpy(sendbuff, cur_src, t_len);

            cur_src+=t_len;
        }
        else if(sendtime ==1)
        {
            t_len = filesize % EACH_DATA;
            if(t_len ==0)
                t_len = EACH_DATA;

            memcpy(sendbuff, cur_src, t_len);
            sendbuff[t_len] ='\r';
            sendbuff[t_len +1] ='\n';
            cur_src += t_len;
            t_len += 2;
        }

        sendtime --;
        send(sockfd, sendbuff, t_len, 0);
    }
    munmap(src, statbuf.st_size);
    printf("send over\n");

}

C++ UDP Client

#include <iostream>
#include <string>
#include <cstring>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>

using std::cout;
using std::endl;
using std::exception;

int main(int argc, char **argv)
{
   if(argc != 4)
   {  
       cout << "Usage: " << argv[0] << " Host Port String" << endl;
       return -1;
   }  

   try
   {  
       struct sockaddr_in serverAddr;
       struct sockaddr recvAddr;
       socklen_t iSockLen = 0; // mark
       //socklen_t iSockLen = sizeof(struct sockaddr_in); // mark
       char buf[128] = {0};
       int bufLen = snprintf(buf, sizeof(buf), "%s", argv[3]);

       int sockFd = socket(AF_INET, SOCK_DGRAM, 0);
       if (sockFd < 0)
           return -1;

       bzero(&serverAddr, sizeof(struct sockaddr_in));
       serverAddr.sin_family = AF_INET;
       serverAddr.sin_port = htons(atoi(argv[2]));
       serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
 
       int ret = sendto(sockFd, buf, bufLen, 0,
               (const struct sockaddr *)&serverAddr, sizeof(serverAddr));
       cout << "send count:" << ret << " data:" << buf << endl;

       bzero(buf, sizeof(buf));
       ret = recvfrom(sockFd, buf, sizeof(buf), 0,
               (struct sockaddr *)&recvAddr, (socklen_t *)&iSockLen); //mark
       cout << "recv count:" << ret << " data:" << buf
           << " errno:" << strerror(errno) << endl;

   }  
   catch(exception &e)
   {  
       cout << "SocketException: " << e.what() << endl;
   }  
   return 0;
}

Bulk text replaces + shell script to change the file name

Bash Language : batch text replace + shell script to change the file name
#! / Bin / bash

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Name: repren.sh
# Description:
# make the following order things:
... # 1 to find specific types of files, such as h, cpp
. # 2 The contents of the file text OLD_TEXT replaced New_text
. # 3 of the file name containing OLD_TEXT rename New_text
. # 4 of containing OLD_TEXT Rename the directory name New_text
#
# Author: Breaker <breaker.zy_AT_gmail>
# Date: 2011-10
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

# IFS said for the statement separator between
OLDIFS = $ IFS
IFS = $ '\ N'    # $ to start making literal escape, otherwise \ n literal rather than directly LF
SCRIPT_NAME = ` basename " $ 0 " `

# usage
usage () { echo "usage:" echo "$ SCRIPT_NAME old_text New_text" } if [ $ # -LT 2 ] ; Then     usage Exit -1 Fi text # replaces the front and rear of old_text = "$ 1" New_text = " $ 2 " OLD_TEXT_UPPER = ` echo $ old_text | TR '[AZ]' '[AZ]' ` # all uppercase old text OLD_TEXT_LOWER = ` echo $ old_text | TR '[AZ]' '[AZ]' ` # all-lowercase Old text NEW_TEXT_UPPER = ` echo $ New_text | TR '[AZ]' '[AZ]' ` # all uppercase new text NEW_TEXT_LOWER = ` echo $ New_text | TR '[AZ]' '[AZ]' ` # full lowercase The new text echo -e 'replace text & rename File ... \ N' # to find the specified file FIND_REGEX = '* (/ (Makefile |. readme) | \ (h |. Hxx | hpp | c | cpp | cxx | txt | mak | rc | x (ht) ml |? html |? sln | vcproj)) ' FILES = ` Find-type f-regextype POSIX-egrep-iregex "$ FIND_REGEX" ` replace text strings when the boundary # # SED_REGEX = '\ (\ b \ | _ \)' SED_REGEX = '\ (\ b \ | [0-9_] \)' # SED_REGEX = '\ (\ b \ | [0-9a-zA-Z_] \) ' # rename the file name of the boundary # GREP_REGEX = '(\ b | _)' GREP_REGEX = '(\ b | [0-9_])' # GREP_REGEX = '(\ b | [0-9a-zA-Z_ ]) ' # do find the file for each ... for EACH in $ FILES do # replace text in files OLD_TEXT is New_text     sed-i "s / $ SED_REGEX $ old_text $ SED_REGEX / \ 1 $ New_text \ 2 / g " $ EACH     sed-i "s / $ SED_REGEX $ OLD_TEXT_UPPER $ SED_REGEX / \ 1 $ NEW_TEXT_UPPER \ 2 / g" $ EACH     sed-i "s / $ SED_REGEX $ OLD_TEXT_LOWER $ SED_REGEX / \ 1 $ NEW_TEXT_LOWER \ 2 / g " $ EACH echo "$ EACH: replace: $ old_text => $ New_text" # rename a file containing OLD_TEXT called New_text OLD_FILE_0 = ` basename $ EACH | grep-E-i "$ GREP_REGEX $ old_text $ GREP_REGEX" ` # Only For the file name, regardless of the directory part if [ "$ OLD_FILE_0" ! = "" ] ; Then DIR = ` dirname $ EACH ` old_file = "$ DIR / $ OLD_FILE_0" NEW_FILE_0 = ` echo "$ OLD_FILE_0" | sed "s / $ old_text / $ New_text / gi " ` NEW_FILE = "$ DIR / $ NEW_FILE_0"         mv "$ old_file" "$ NEW_FILE" echo "rename: $ old_file => $ NEW_FILE" Fi echo '' DONE echo -e 'rename dir .. . \ N ' # change the directory name: Rename the directory name containing OLD_TEXT DIRS = ` Find-type d ` for EACH in $ DIRS ; do OLD_DIR_0 = ` basename $ EACH | grep-E-i "$ GREP_REGEX $ old_text $ GREP_REGEX " ` if [ "" $ OLD_DIR_0 ! = "" ] ; Then OLD_DIR_DIR = ` dirname $ EACH ` OLD_OLD_DIR = "$ OLD_DIR_DIR / $ OLD_DIR_0" NEW_DIR_0 = ` echo "$ OLD_DIR_0" | sed "s / $ old_text / $ New_text / gi " ` NEW_DIR_DIR = ` echo "$ OLD_DIR_DIR" | sed "s / $ old_text / $ New_text / gi" ` # Find the first output of the parent directory, then the parent directory has been renamed the # so OLD_DIR by the new parent directory name and OLD_DIR_0 spell, instead of the original OLD_OLD_DIR the OLD_DIR = "$ NEW_DIR_DIR / $ OLD_DIR_0" NEW_DIR = "$ NEW_DIR_DIR / $ NEW_DIR_0"         mv "$ OLD_DIR" "$ NEW_DIR" echo "rename: $ OLD_OLD_DIR => $ NEW_DIR" echo ' ' Fi DONE # Recovery Environment IFS = $ OLDIFS

With zeromq of PUB / SUB network model expansion python logging

import os, sys, types
import zmq, logging
import time

class ZMQPUBHandler(logging.Handler):
    def __init__(self, host, port):
        logging.Handler.__init__(self)
        ctx = zmq.Context(1,1)
        self.sock = ctx.socket(zmq.PUB)
        self.sock.bind('tcp://%s:%s' %(host, port))

    def emit(self, record):
        """
        Emit a record.

        If a formatter is specified, it is used to format the record.
        The record is then written to the stream with a trailing newline
        [N.B. this may be removed depending on feedback]. If exception
        information is present, it is formatted using
        traceback.print_exception and appended to the stream.
        """
        try:
            msg = self.format(record)
            fs = "%s\n"
            if not hasattr(types, "UnicodeType"): #if no unicode support...
                self.sock.send(fs % msg, zmq.NOBLOCK)
            else:
                try:
                    self.sock.send(fs % msg, zmq.NOBLOCK)
                except UnicodeError:
                    self.sock.send(fs % msg.encode("UTF-8"), zmq.NOBLOCK)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)


def main():
    #订阅
    host = sys.argv[1]
    ctx = zmq.Context(1, 1)
    sock = ctx.socket(zmq.SUB)
    sock.setsockopt(zmq.SUBSCRIBE, '')
    sock.connect('tcp://%s:55555' % host)

    while 1:
        msg = sock.recv(zmq.NOBLOCK)
        if msg:
            print msg,
        else:
            time.sleep(0.1)

if __name__ == '__main__':
    main()

C Language : fork () function

# Include <unistd.h>
<stdio.h> # include

int main ( void ) { int i = 0 ; printf ( "i Son / PA ppid pid FPID \ N " ); / / ppid parent process refers to the current process pid / / pid pid refers to the current process, / / FPID refers to fork back to the current process value for ( i = 0 ; i < 2 ; i + + ) { pid_t FPID = fork (); if ( FPID == 0 ) printf ( "% d% Child% 4D% 4D 4D \ N " , i , getppid (), getpid (), FPID ); else printf ( "% d parent% 4D% 4D% 4D \ N " , i , getppid () , getpid (), FPID ); } return 0 ; }

Lianliankan core code

Sub FindPath(ByVal pre_row As Integer, ByVal pre_col As Integer, ByVal cur_row As Integer, ByVal cur_col As Integer)
    Dim pre_left As Integer = pre_col
    Dim pre_right As Integer = pre_col
    Dim cur_left As Integer = cur_col
    Dim cur_right As Integer = cur_col
    For j As Integer = pre_col - 1 To 0 Step -1
        If Map(pre_row, j) <> -1 Then
            pre_left = j + 1
            Exit For
        End If
    Next
    For j As Integer = pre_col + 1 To MAP_SIZE + 1
        If Map(pre_row, j) <> -1 Then
            pre_right = j - 1
            Exit For
        End If
    Next
    For j As Integer = cur_col - 1 To 0 Step -1
        If Map(cur_row, j) <> -1 Then
            cur_left = j + 1
            Exit For
        End If
    Next
    For j As Integer = cur_col + 1 To MAP_SIZE + 1
        If Map(cur_row, j) <> -1 Then
            cur_right = j - 1
            Exit For
        End If
    Next
    Dim left As Integer = Math.Max(pre_left, cur_left)
    Dim right As Integer = Math.Min(pre_right, cur_right)
    For q As Integer = pre_col To left Step -1
        If LineConnect(pre_row, q, cur_row, q) = True Then
            Stage.Controls.Remove(Picture(pre_row - 1, pre_col - 1))
            Stage.Controls.Remove(Picture(cur_row - 1, cur_col - 1))
            Count = Count - 2
            Exit Sub
        End If
    Next
    For q As Integer = pre_col To right
        If LineConnect(pre_row, q, cur_row, q) = True Then
            Stage.Controls.Remove(Picture(pre_row - 1, pre_col - 1))
            Stage.Controls.Remove(Picture(cur_row - 1, cur_col - 1))
            Count = Count - 2
            Exit Sub
        End If
    Next
    Dim pre_top As Integer = pre_row
    Dim pre_bottom As Integer = pre_row
    Dim cur_top As Integer = cur_row
    Dim cur_bottom As Integer = cur_row
    For i As Integer = pre_row - 1 To 0 Step -1
        If Map(i, pre_col) <> -1 Then
            pre_top = i + 1
            Exit For
        End If
    Next
    For i As Integer = pre_row + 1 To MAP_SIZE + 1
        If Map(i, pre_col) <> -1 Then
            pre_bottom = i - 1
            Exit For
        End If
    Next
    For i As Integer = cur_row - 1 To 0 Step -1
        If Map(i, pre_col) <> -1 Then
            cur_top = i + 1
            Exit For
        End If
    Next
    For i As Integer = cur_row + 1 To MAP_SIZE + 1
        If Map(i, pre_col) <> -1 Then
            cur_bottom = i - 1
            Exit For
        End If
    Next
    Dim top As Integer = Math.Max(pre_top, cur_top)
    Dim bottom As Integer = Math.Min(pre_bottom, cur_bottom)
    For p As Integer = pre_col To left Step -1
        If LineConnect(p, pre_col, p, cur_col) = True Then
            Stage.Controls.Remove(Picture(pre_row - 1, pre_col - 1))
            Stage.Controls.Remove(Picture(cur_row - 1, cur_col - 1))
            Count = Count - 2
            PreClick = -1
            CurClick = -1
            Exit Sub
        End If
    Next
    For p As Integer = pre_col To right
        If LineConnect(p, pre_col, p, cur_col) = True Then
            Stage.Controls.Remove(Picture(pre_row - 1, pre_col - 1))
            Stage.Controls.Remove(Picture(cur_row - 1, cur_col - 1))
            Count = Count - 2
            PreClick = -1
            CurClick = -1
            Exit Sub
        End If
    Next
End Sub

Python : Fast row with class methods to find "n-small" number

#coding=utf-8
#
# from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269554
# 代码描述:
#  O(n) quicksort style algorithm for looking up data based on rank order.
#  Useful for finding medians, percentiles, quartiles, and deciles.
#  Equivalent to data[n] when the data is already sorted.

import random

def select(data, n):
    "Find the nth rank ordered element (the least value has rank 0)."
    data = list(data)
    if not 0 <= n < len(data):
        raise ValueError('not enough elements for the given rank')
    while True:
        pivot = random.choice(data)
        pcount = 0
        under, over = [], []
        uappend, oappend = under.append, over.append
        for elem in data:
            if elem < pivot:
                uappend(elem)
            elif elem > pivot:
                oappend(elem)
            else:
                pcount += 1
        if n < len(under):
            data = under
        elif n < len(under) + pcount:
            return pivot
        else:
            data = over
            n -= len(under) + pcount

C + + language : median filter

* # include < Algorithm >
using namespace STD ; IplImage * CDrawDlg :: MiddleProssing ( IplImage * img , IplImage * img1 ) { int i , J , k , t ; int Move [ 8 ] [ 2 ] = {{ 0 , 1 } { 1 , 0 }, { - 1 , 0 }, { 0 , - 1 }, { 1 , 1 }, { - 1 , - 1 }, { 1 , - 1 }, { - 1 , 1 }}; int P [ 9 ]; IplImage * tmp = detectanddraw ( img ); IplImage * tmp1 = detectanddraw ( img1 ); for ( i = 1 ; i < tmp -> height - 1 ; i + + ) { for ( J = 1 ; J < tmp -> width - 1 ; J + + ) { for ( t = 0 ; t < 3 ; t + + ) { int ii = i ; int JJ = J ;                 P [ 8 ] = (( UCHAR * ) ( img -> imageData + img -> widthStep * JJ )) [ ii * 3 + t ]; for ( k = 0 ; k < 8 ; k + + ) { ii = i + Move [ k ] [ 0 ]; JJ = J + Move [ k ] [ 1 ];                     P [ k ] = (( UCHAR * ) ( img -> imageData + img -> widthStep * JJ )) [ ii * 3 + t ]; } Sort (P , P + 9 );                 (( UCHAR * ) ( img1 -> imageData + img1 -> widthStep * J )) [ i * 3 + t ] = P [ 4 ]; } } } return img1 ; }

C Language : snprintf usage

<stdio.h> # Include
# include <stdlib.h>
/ *
int snprintf (char * restrict buf, size_t N, const char * restrict Format, ...);
Function Description: copy from the source string up to n-1 characters in the target string, and then later add a 0. Therefore, if the size of the target string is n
                 , it will not overflow.
Function return values: If successful, returns the length of the string to be written, if an error is returned negative.
* /
int main () { char str [ 10 ] = { 0 ,}; snprintf ( str , sizeof ( str ), "% s" , "0,123,456,789,012,345,678" ); printf ( "str =% s ​​\ N " , str ) ; return 0 ; }

c refreshing exception handling

int Function ( void )  { int Err ;  Err = operate1 ( ptr1 , "Skull" );  if ( Err )   GOTO fail_this ;  Err = operate2( ptr2 , "Skull" );  if ( Err )   GOTO fail_that ;  Err = operate3 ( ptr3 , "Skull" );  if ( Err )   GOTO fail_those;  return 0 ;  fail_those : unregister_that ( ptr2 , "Skull" );  fail_that : unregister_this ( ptr1 , "Skull" ); fail_this : return Err ;  }

Installation under CentOS Oracle 10g

# 挂载CentOS系统安装光盘
dvdFile="//FileServerIp/Share/CentOS-5.5-x86_64-bin-DVD.iso"
dvdDir="/mnt/CentOS_Final"
mount -t iso9660 -o loop "${dvdFile}" "${dvdDir}"
# 将安装光盘添加到安装源
cat >> /etc/yum.repos.d/CentOS-Media.repo <<_yumSource
[AutoInstaller]
name=CentOS-$releasever - Media
baseurl=file:///mnt/CentOS_Final/
gpgcheck=0
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5
_yumSource
# 使用光盘作安装源,安装依赖库
yum -y --disablerepo=\* --enablerepo=AutoInstaller --nogpgcheck --skip-broken install compat-db* compat-libc* compat-gcc* libXp.so.6 libc-* libaio* openmotif glibc-devel* libgcc* gnome-lib* libXtst vnc-server xterm xorg-x11-twm
# 创建安装目录,解压安装包
mkdir -p /data/setupfiles/Oracle /data/oracle
cd /data/setupfiles/Oracle/
zcat /mnt/wol-fileshare-s/OPVol/Oracle/10201_database_linux_x86_64.cpio.gz | cpio -idmv
# 添加用户,设定用户密码
/usr/sbin/groupadd oinstall
/usr/sbin/groupadd dba
/usr/sbin/useradd -m -g oinstall -G dba oracle -d /data/oracle/home
id oracle
passwd oracle
# 初始化安装目录
mkdir -p /data/oracle/app /data/oracle/data
chown -R oracle:oinstall /data/oracle/app /data/oracle/data
chmod -R 775 /data/oracle/app /data/oracle/data
# 设置oracle用户的环境变量
vim ~oracle/.bash_profile
    LANG=UTF-8
    ORACLE_SID=orcl
    ORACLE_BASE=/data/oracle/app
    ORACLE_HOME=/app/oracle/product/10.2.0/db_1
    JAVA_HOME=$ORACLE_HOME/jdk
    PATH=$ORACLE_HOME/bin:$PATH:$HOME/bin
    export LANG ORACLE_SID ORACLE_BASE ORACLE_HOME JAVA_HOME PATH
# 配置VNC登录选项,Oracle安装需要使用界面
vim /etc/sysconfig/vncservers
    VNCSERVERS="0:oracle"
    VNCSERVERARGS[2]="-geometry 1280x1024 -nolisten tcp -nohttpd -localhost"
su - oracle
vncserver
logout
vncserver -kill :1
service vncserver start
# 由于Oracle未对CentOS作支持,改用Redhat标识
vim /etc/redhat-release 
    Red Hat Enterprise Linux AS release 3 (higkoo)
# 修改内核参数
vim /etc/sysctl.conf
    kernel.shmall = 4294967296
    kernel.shmmax = 68719476736
    kernel.shmmni = 4096
    kernel.sem = 250 32000 100 128
    fs.file-max = 65536
    net.ipv4.ip_local_port_range = 1024 65000
sysctl -p
# 修改Oracle用户环境
vim /etc/security/limits.conf
    oracle               soft    nproc   2047
    oracle               hard    nproc   16384
    oracle               soft    nofile  1024
    oracle               hard    nofile  65536

Detection of browser and operating system JavaScript Advanced Programming

/ *
* detect browsers and operating systems
* Book: JavaScript Advanced Programming
* Author: Nicholas C. Zakas
* in the client browser detection is the most important object is the navigator object, which contains some of the browser can provide you with information property
* /
/ *
way * Detect Browser:
* an object / feature detection method: A common method to determine browser capabilities, involving the use of a given object before the first detection of its presence
* For example:
* if (document.getElementById) [If a property or method does not exist, it will return undefined, has been translated into Boolean is false
* {
* / / the method exists, so use it here
*} else {
* / / do something else
*}
* If you are more concerned about the browser and the ability to care about its real identity, you can use this detection method
*
* 2.user-agent string detection method
* user-agent string detection method is the oldest browser detection method Visit the website of each program must provide a user-agent string to determine its identity to the server.
* The introduction of the navigator object in JavaScript in the userAgent property to provide client access to user-agent string
* var sUserAgent = navigator.userAgent;
* on user-agent string between history and various browsers user- Differences agent string format details, see the contents of Chapter VIII of the
* /

/ / save user-agent string
var sUserAgent = window . Navigator . userAgent ; / / save the browser version var fAppVersion = parseFloat ( window . Navigator . appVersion ); / * * accept two versions of string as a parameter, returns 0 if they are equal, if the first is greater than the second returns 1, if the second is greater than the first return -1 * Parameters sVersion example: 0.9.2; 0.9; 1.13 .2; 1.14 * / Function compareVersions ( sVersion1 , sVersion2 ) { var aVersion1 = sVersion1 . Split ( "." ); var aVersion2 = sVersion2 . Split ( "." ); if ( aVersion1 . length < aVersion2 . length ) { for ( var i = 0 ; i < aVersion2 . length - aVersion1 . length ; i + + ) aVersion1 . PUSH ( "0" ); } else if ( aVersion2 . length < aVersion1 . length ) { for ( var i = 0 ; i < aVersion1 . length - aVersion2 . length ; i + + ) aVersion2 . PUSH ( "0" ); } for ( var i = 0 ; i < aVersion1 . length ; i + + ) { var iVal1 = parseInt ( aVersion1 [ i ] , 10 ); var ival2 = parseInt ( aVersion2 [ i ] , 10 ); if ( iVal1 < ival2 ) return - 1 ; else if ( iVal1 > ival2 ) return 1 ; } return 0 ; } / * Opera * detection * most convenient The judge is to search the user-agent string, there is no Opera * then continue to determine the version actually used * / var isOpera = sUserAgent . indexOf ( "Opera" ) > - 1 ; var isMinOpera4 = isMinOpera5 = isMinOpera6 = isMinOpera7 = isMinOpera7_5 = false ; if ( isOpera ) { var fOperaVersion ; if ( window . Navigator . appName == "Opera" ) { fOperaVersion = fAppVersion ; } else { var reOperaVersion = new RegExp ( . "Opera (\ \ d + \ \ \ \ d + ) " ); reOperaVersion . test ( sUserAgent ); fOperaVersion = parseFloat ( RegExp [ "$ 1" ]); } isMinOpera4 = fOperaVersion > = 4 ; isMinOpera5 = fOperaVersion > = 5 ; isMinOpera6 = fOperaVersion > = 6 ; isMinOpera7 = fOperaVersion > = 7 ; isMinOpera7_5 = fOperaVersion > = 7.5 ; } / * * Detection Konqueror / Safari * Konqueror / Safari is based on KHTML project * / var isKHTML = sUserAgent . indexOf ( "KHTML" ) > - 1               | | sUserAgent . indexOf ( "Konqueror " ) > - 1               | | sUserAgent . indexOf ( "AppleWebKit" ) > - 1 ; if ( isKHTML ) { isSafari = sUserAgent . indexOf ( "AppleWebKit" ) > - 1 ; isKonq = sUserAgent . indexOf ( "Konqueror" ) > - 1 ; var isMinSafari1 = isMinSafari1_2 = false ; var isMinKonq2_2 = isMinKonq3 = isMinKonq3_1 = isMinKonq3_2 = false ; if ( isSafari ) { var reAppleWebKit = new RegExp ( "AppleWebKit \ \ / (\ \ d + (:?. \ \ \ \ d * ))? " ); reAppleWebKit . test ( sUserAgent ); var fAppleWebKitVersion = parseFloat ( RegExp [ "$ 1" ]); isMinSafari1 = fAppleWebKitVersion > = 85 ; isMinSafari1_2 = fAppleWebKitVersion > = 124 ; } else if ( isKonq ) { var rekonq = new RegExp ( "Konqueror \ \ / (\ \ d + (: \ \ \ \ d + (:?.?.?? \ \ \ \ d)))" ); rekonq . test ( sUserAgent ); isMinKonq2_2 = compareVersions ( RegExp [ "$ 1" ] , "2.2" ) > = 0 ; isMinKonq3 = compareVersions ( RegExp [ "$ 1" ] , "3.0" ) > = 0 ; isMinKonq3_1 = compareVersions ( RegExp [ "$ 1" ] , "3.1" ) > = 0 ; isMinKonq3_2 = compareVersions ( RegExp [ "$ 1" ] , "3.2" ); } } / * * detect IE * / var isIE = sUserAgent . indexOf ( "compatible" ) > - 1 && sUserAgent . indexOf ( "MSIE" ) > - 1 && ! ​​isOpera ; var isMinIE4 = isMinIE5 = isMinIE5_5 = isMinIE6 = false ; if ( isIE ) { var REIE = new RegExp ( "MSIE (\ \ d + \ \ \ \ d +);." ); REIE . test ( sUserAgent ); var fIEVersion = parseFloat ( RegExp [ "$ 1" ]); isMinIE4 = fIEVersion > = 4 ; isMinIE5 = fIEVersion > = 5 ; isMinIE5_5 = fIEVersion > = 5.5 ; isMinIE6 = fIEVersion > = 6.0 ; } / * * Detection Mozilla * / var isMoz = sUserAgent . indexOf ( "Gecko" ) > - 1 && ! ​​isKHTML ; var isMinMoz1 = isMinMoz1_4 = isMinMoz1_5 = false ; if ( isMoz ) { var reMoz = new RegExp ( "RV: (\ \ d + \ \. \ \ d +? (:?. \ \ \ \ d +)) " ); reMoz . test ( sUserAgent ); isMinMoz1 = compareVersions ( RegExp [ "$ 1" ] , "1.0" ) > = 0 ; isMinMoz1_4 = compareVersions ( RegExp [ "$ 1" ] , "1.4" ) > = 0 ; isMinMoz1_5 = compareVersions ( RegExp [ "$ 1" ] , "1.5" ) > = 0 ; } / * Netscape Communicator 4.x * detection * Although Netscape Communicator outdated, but It's possible there are still some users * / var isNS4 = ! isIE && ! ​​isOpera && ! ​​isMoz && ! ​​isKHTML && ( sUserAgent . indexOf ( "Mozilla" ) == 0 ) && ( Navigator . appName == "Netscape" ) && ( fAppVersion > = 4.0 && fAppVersion < 5.0 ); var isMinNS4 = isMinNS4_5 = isMinNS4_7 = isMinNS4_8 = false ; if ( isNS4 ) { isNS4 = true ; isMinNS4_5 = fAppVersion > = 4.5 ; isMinNS4_7 = fAppVersion > = 4.7 ; isMinNS4_8 = fAppVersion > = 4.8 ; } / * * platform / operating system detection script * determine the operating system should start to find a platform to start, the platform is mainly divided into three categories: Windows, Macintosh, and Unix * / var isWin = ( window . Navigator . Platform == "Win32" ) | | ( window . Navigator . Platform == "Windows" ); var isMac = ( window . Navigator . Platform == "Mac68k" ) | | ( window . Navigator . Platform == "MacPPC" ); var isUnix = ( window . Navigator . Platform == "X11" ) && ! ​​isWin && ! ​​isMac ; var isWin95 = isWin98 = isWinNT4 = isWin2K = isWinME = isWinXP = false ; if ( isWin ) { isWin95 = sUserAgent . indexOf ( "Win95" ) > - 1 | | sUserAgent . indexOf ( "Windows 95" ) > - 1 ; isWin98 = sUserAgent . indexOf ( "Win98" ) > - 1 | | sUserAgent . indexOf ( "Windows 98" ) > - 1 ; isWinME = sUserAgent . indexOf ( "Win 9x 4.90" ) > - 1 | | sUserAgent . indexOf ( "Windows ME" ) > - 1 ; isWin2K = sUserAgent . indexOf ( "Windows NT 5.0" ) > - 1 | | sUserAgent . indexOf ( "Windows 2000" ) > - 1 ; isWinXP = sUserAgent . indexOf ( "Windows NT 5.1" ) > - 1 | | sUserAgent . indexOf ( "Windows XP" ) > - 1 ; isWinNT4 = sUserAgent . indexOf ( "WinNT" ) > - 1 | | sUserAgent . indexOf ( "Windows NT" ) > - 1 | | sUserAgent . indexOf ( "WinNT4.0" ) > - 1 | | sUserAgent . indexOf ( "Windows NT 4.0" ) > - 1 && ( ! isWinME && ! ​​isWin2K && ! isWinXP ); } var isMac68K = isMacPPC = false ; if ( isMac ) { isMac68K = sUserAgent . indexOf ( "Mac_68000" ) > - 1 | | sUserAgent . indexOf ( "68K" ) > - 1 ; isMacPPC = sUserAgent . indexOf ( " Mac_PowerPC " ) > - 1 | | sUserAgent . indexOf ( "PPC" ) > - 1 ; } / * Unix * There is considerable style, SunOS, HP-UX, AIX, Linux, etc., there are different versions of each as well as different user-agent string representation * here only concern and some versions of SunOS, you should have enough knowledge to be transformed into a script to detect other Unix platforms * / var isSunOS = isMinSunOS4 = isMinSunOS5 = isMinSunOS5_5 = false ; if ( isUnix ) { isSunOS = sUserAgent . indexOf ( "SunOS" ) > - 1 ; if ( isSunOS ) { var reSunOS = new RegExp ( .?. "SunOS (\ \ d + \ \ \ \ d + (: \ \ \ \ d +) ?) " ); reSunOS . test ( sUserAgent ); isMinSunOS4 = compareVersions ( RegExp [ "$ 1" ] , "4.0" ) > = 0 ; isMinSunOS5 = compareVersions ( RegExp [ "$ 1" ] , "5.0" ) > = 0 ; isMinSunOS5_5 = compareVersions ( RegExp [ "$ 1" ] , "5.5" ) > = 0 ; } }

Under the current directory txt extension changed to doc

.. # Change the extension, for example, the current directory is changed to doc txt extension: 
! # / bin / bash 
for f in * txt;. do mv "$ f" "$ {f / txt / doc} " ; DONE 
# util-linux software package with the rename can achieve the same purpose.

Microsoft elegant black font xterm set methods

通过如下方法可以将Linux 下xterm 终端的字体改为微软雅黑:
修改~/.Xresources就可以了(没有就自己创建一个)

xterm*locale: true
xterm.utf8: true
xterm*utf8Title: true
xterm*faceName: Monaco:pixelsize=14
xterm*faceNameDoublesize: Microsoft YaHei:pixelsize=15

对于系统装了微软雅黑的用户在注销重新登录后就可以发现xterm终端
的字体变成微软雅黑了。

Monitor web server and an alarm is sent to the phone

#this script can monitor webserver and send message to fanfou and your mobile phone.
#notice:
#1.change you phone number.
#2.the  program "sms" is fetion for linux.
server_list=(192.168.0.21:80 192.168.203.1:80)
date=`date +"%y%m%d-%H:%M:%S"`
okmsg=/var/log/okmsg
errormsg=/var/log/errormsg
lockfile=/usr/local/web.Lock
if [ "$UID" -ne 0 ]
then
        echo"must be root can run this script.!"
exit
fi
if [ -f $lockfile ]
then
        echo "script already runing."&&exit
else
        touch $lockfile
fi
send_msg_to_fetion()
{
/usr/local/bin/sms -f 138000000 -p password -t 138000000 -m "$date $msg" -d 1 >/dev/null 2>&1
}
send_msg_to_fanfou()
{
curl -u hackcrisman@gmail.com:password -d status="$date $msg" http://api.fanfou.com/statuses/update.xml >/dev/null 2>&1
}
server_all_num=${#server_list [*]}
i=0
while [ $i -lt $server_all_num ]
do
        server_ip=$(echo ${server_list[$i]}|awk -F':' '{print $1}')
        server_port=$(echo ${server_list[$i]}|awk -F':' '{print $2}')
        if curl -m 10 -G http://${server_list[$i]} > /dev/null 2>&1
        then
        status=1
        echo "服务器${server_ip},端口${server_port}可以正常访问。" >>$okmsg
        msg="服务器${server_ip},端口${server_port}可以正常访问。"
else
        if ping -c 1 $server_ip >/dev/null 2>&1
        then
        status=2
        echo "服务器${server_ip},端口${server_port}无法访问,但可以Ping 通" >>$errormsg
        msg="服务器${server_ip},端口${server_port}无法访问,但可以Ping 通"
else
        status=0
        echo "服务器${server_ip},端口${server_port}无法访问,且无法Ping 通" >>$errormsg
        msg="服务器${server_ip},端口${server_port}无法访问,且无法Ping 通"
fi
fi
send_msg_to_fanfou
send_msg_to_fetion
(( i++))
done
rm -rf $lockfile

Python command line: input method does not require the transport can be entered

Coding = utf-8 # 
# From: Python-CN Group: http://groups.google.com/group/python-cn/browse_thread/thread/bb729a571cd3b091 
# Q: # raw_input input will be needed to complete the transport input There is no need to enter a carriage return can input methods. 

# A: (by Leo Jay) 
# You do not say what platform you are, you want exhausted me :) 
on # windows platform is very simple, msvcrt library has a direct function getch can handle. 
The # linux on the tired, use the termios module, modify the properties of the terminal is non-canonical mode, giving you a look at some code to 
Import SYS 
Import termios 

fd SYS stdin fileno () old = termios . tcgetattr ( fd ) new = termios . tcgetattr ( fd ) new [ ] = new [ ] & ~ termios . ICANON TRY: termios . tcsetattr ( fd , termios . TCSADRAIN , new ) while True : input = SYS . stdin . Read ( 1 ) Print 'get' , input if input == 'q' :break finally : termios . tcsetattr ( fd , termios . TCSADRAIN , old )