Thursday, 17 May 2007

Applets and Graphics

CHAPTER 36—Applets
An applet usually is used as part of a Web page. The applet is responsible for the graphical components and user interaction in a rectangular section of the Web browser's screen. Applets are typically used for user interaction with the Web page.

An applet is an object that is used by another program, typically a Web browser. The Web browser is the application program and (at least conceptually) holds the main() method. The applet part of a Web page provides services (methods) to the browser when the browser asks for them.

To access these definitions, your program should import javax.applet.JApplet and java.awt.*.

drawString( String str, int x, int y)
str — a String to place into the drawing area
x — horizontal distance in pixels from the left edge
y — vertical distance in pixels from the top edge

Distance is measured in pixels. A pixel is one of the graph paper squares that the video screen has been (conceptually) divided into. If your monitor is set to a resolution of 800 by 600, then the whole screen is divided into 800 horizontal squares and 600 vertical squares. An applet will usually cover only part of that area, perhaps an area 300 horizontal by 150 vertical. It is the responsibility of the graphics card and its driver to implement this idea of graph paper on the actual electronics of you computer system.

An applet does not have a main() method and so cannot be started as an application.

appletviewer displays only the applet part of an HTML file. The other parts (if any) are omitted.
Appletviewer is run from the command prompt window. If javac and java have been working, then the following should work:

C:\>appletviewer AnotherHello.html

mark the START of a "html" file. These should be the FIRST characters in the file.
mark the END of a "html" file. These should be the LAST characters in the file.
mark the start of the head of the file. The head of the file contains descriptions and declarations that are not supposed to be directly visible on the Web page.
mark the end of the head of the file.
give a title to the entire page (the Web browser can use the title for whatever purpose it wishes.) This should be in the head section of the page. <br /> end of the title.
mark the start of the body of the file. The body of the file is the main part that is visible on the monitor screen.
mark the end of the body of the file.

a horizontal rule: a line completely across the screen. There is no matching tag.


class Circle
{
// variables



// constructors


// methods


}

Wednesday, 16 May 2007

jar

http://www.dedecms.com/web-art/JSPjiaocheng/20060330/23986.html
如何把java程序编译成.exe文件(就是制作可执行的JAR文件包)

作者:边城狂人

常常在网上看到有人询问:如何把 java 程序编译成 .exe 文件。通常回答只有两种,一种是制作一个可执行的 JAR 文件包,然后就可以像.chm 文档一样双击运行了;而另一种是使用 JET 来进行
编译。但是 JET 是要用钱买的,而且据说 JET 也不是能把所有的 Java 程序都编译成执行文件,性能也要打些折扣。所以,使用制作可执行 JAR 文件包的方法就是最佳选择了,何况它还能保持 Java 的跨平台特性。

下面就来看看什么是 JAR 文件包吧:

1. JAR 文件包

JAR 文件就是 Java Archive File,顾名思意,它的应用是与 Java 息息相关的,是 Java 的一种文档格式。JAR 文件非常类似 ZIP 文件——准确的说,它就是 ZIP 文件,所以叫它文件包。JAR 文件与 ZIP 文件唯一的区别就是在 JAR 文件的内容中,包含了一个 META-INF/MANIFEST.MF 文件,这个文件是在生成 JAR 文件的时候自动创建的。举个例子,如果我们具有如下目录结构的一些文件:

  ==

  `-- test

    `-- Test.class

把它压缩成 ZIP 文件 test.zip,则这个 ZIP 文件的内部目录结构为:

  test.zip

  `-- test

    `-- Test.class

如果我们使用 JDK 的 jar 命令把它打成 JAR 文件包 test.jar,则这个 JAR 文件的内部目录结构为:

  test.jar

  |-- META-INF

  |  `-- MANIFEST.MF

  `-- test

    `--Test.class

2. 创建可执行的 JAR 文件包

制作一个可执行的 JAR 文件包来发布你的程序是 JAR 文件包最典型的用法。

Java 程序是由若干个 .class 文件组成的。这些 .class 文件必须根据它们所属的包不同而分级分目录存放;运行前需要把所有用到的包的根目录指定给 CLASSPATH 环境变量或者 java 命令的 -cp 参数;运行时还要到控制台下去使用 java 命令来运行,如果需要直接双击运行必须写 Windows 的批处理文件 (.bat) 或者 Linux 的 Shell 程序。因此,许多人说,Java 是一种方便开发者苦了用户的程序设计语言。
其实不然,如果开发者能够制作一个可执行的 JAR 文件包交给用户,那么用户使用起来就方便了。在 Windows 下安装 JRE (Java Runtime Environment) 的时候,安装文件会将 .jar 文件映射给 javaw.exe 打开。那么,对于一个可执行的 JAR 文件包,用户只需要双击它就可以运行程序了,和阅读 .chm 文档一样方便 (.chm 文档默认是由 hh.exe 打开的)。那么,现在的关键,就是如何来创建这个可执行的 JAR 文件包。

创建可执行的 JAR 文件包,需要使用带 cvfm 参数的 jar 命令,同样以上述 test 目录为例,命令如下:

jar cvfm test.jar manifest.mf test

这里 test.jar 和 manifest.mf 两个文件,分别是对应的参数 f 和 m,其重头戏在 manifest.mf。因为要创建可执行的 JAR 文件包,光靠指定一个 manifest.mf 文件是不够的,因为 MANIFEST 是 JAR 文件包的特征,可执行的 JAR 文件包和不可执行的 JAR 文件包都包含 MANIFEST。关键在于可执行 JAR 文件包的 MANIFEST,其内容包含了 Main-Class 一项。这在 MANIFEST 中书写格式如下:

Main-Class: 可执行主类全名(包含包名)

例如,假设上例中的 Test.class 是属于 test 包的,而且是可执行的类 (定义了 public static void main(String[]) 方法),那么这个 manifest.mf 可以编辑如下:

Main-Class: test.Test <回车>

这个 manifest.mf 可以放在任何位置,也可以是其它的文件名,只需要有 Main-Class: test.Test 一行,且该行以一个回车符结束即可。创建了 manifest.mf 文件之后,我们的目录结构变为:

  ==

  |-- test

  |  `-- Test.class

  `-- manifest.mf

这时候,需要到 test 目录的上级目录中去使用 jar 命令来创建 JAR 文件包。也就是在目录树中使用“==”表示的那个目录中,使用如下命令:

jar cvfm test.jar manifest.mf test

之后在“==”目录中创建了 test.jar,这个 test.jar 就是执行的 JAR 文件包。运行时只需要使用 java -jar test.jar 命令即可。

需要注意的是,创建的 JAR 文件包中需要包含完整的、与 Java 程序的包结构对应的目录结构,就像上例一样。而 Main-Class 指定的类,也必须是完整的、包含包路径的类名,如上例的 test.Test;而且在没有打成 JAR 文件包之前可以使用 java <类名> 来运行这个类,即在上例中 java test.Test 是可以正确运行的 (当然要在 CLASSPATH 正确的情况下)。



http://sintra.blogbus.com/logs/2006/11/3868713.html

Java技术:生成可执行jar文件的教程
Time:2006年11月20日
若要生成一个名为 cal.jar 的可执行jar文件:(文件名可以是任意合法名字)
(这是我认为简单实用的一种方法,还有很多别的方法在此就不介绍了)
第一 把程序生成的所有字节码文件(即.class文件)放在同一个目录下(如:D:/chat/).
第二 在该目录下新建一个manifest.mf文件,文件内容格式如下(划线中内容):
manifest.mf文件中的格式:
--------------------------------
Main-Class: calDemo

--------------------------------
注意: calDemo代表主类名(即要运行的类名,只能有一个,不要文件扩展名)
Main与Class中间不是下划线,而是短横线
Main-Class:与calDemo中间必须要有空格
Main-Class: calDemo之后必须要回车


文件中还可以加入一些其他信息如:(先不要加,以免出错)

--------------------------------------------
Manifest-Version: 1.0
Created-By: 1.4.1_02 (Sun Microsystems Inc.)
--------------------------------------------

然后用jar命令生成可执行的jar文件,例如:
(执行该命令前先要转到该目录下 D:/chat/ )
jar cvfm cal.jar manifest.mf *.class

jar用法:(仅供参考,初学者可跳过这部分内容)
jar {ctxu}[vfm0Mi] [jar-文件] [manifest-文件] [-C 目录] 文件名 ...
选项:
-c 创建新的存档
-t 列出存档内容的列表
-x 展开存档中的命名的(或所有的〕文件
-u 更新已存在的存档
-v 生成详细输出到标准输出上
-f 指定存档文件名
-m 包含来自标明文件的标明信息
-0 只存储方式;未用ZIP压缩格式
-M 不产生所有项的清单(manifest〕文件
-i 为指定的jar文件产生索引信息
-C 改变到指定的目录,并且包含下列文件:
如果一个文件名是一个目录,它将被递归处理。
清单(manifest〕文件名和存档文件名都需要被指定,按'm' 和 'f'标志指定的相同顺序。

示例1:将两个class文件存档到一个名为 'classes.jar' 的存档文件中:
jar cvf classes.jar Foo.class Bar.class
示例2:用一个存在的清单(manifest)文件 'mymanifest' 将 foo/ 目录下的所有
文件存档到一个名为 'classes.jar' 的存档文件中:
jar cvfm classes.jar mymanifest -C foo/ .

Tuesday, 15 May 2007

常見程式演算

偶然在这里遇到一个关于一些算法问题的网站,里面提供了java的实现。
http://caterpillar.onlyfun.net/Gossip/AlgorithmGossip/AlgorithmGossip.htm

Gladder

Thanks Maro for him to tell me a trick about using Firefox to access some sits such as wikipedia, BBC news and nearly all webs which considered with little political reason, so we are allowed to open.

this technology is call gladder which I had heard before. if I want to access site A, I can land site B, then load A as a part of source B. so, it is not easy for government to filter.

there are many such services like:
proxyhub.co.uk
anonymous.com

here we can use GLADDER in firefox as plug-in

download it from http://gneheix.googlepages.com/gladder

Algorithm::Diff

before that, we need firstly to know something about metric,
here is document in chinese
http://www.core.org.cn/NR/rdonlyres/Sloan-School-of-Management/15-062Data-MiningSpring2003/78318536-A16C-4EC7-879F-C96C123AC7C4/0/linalg.pdf


Dynamic Programming
The following is an example of global sequence alignment using Needleman/Wunsch techniques. For this example, the two sequences to be globally aligned are

G A A T T C A G T T A (sequence #1)
G G A T C G A (sequence #2)

So M = 11 and N = 7 (the length of sequence #1 and sequence #2, respectively)

A simple scoring scheme is assumed where


* Si,j = 1 if the residue at position i of sequence #1 is the same as the residue at position j of sequence #2 (match score); otherwise
* Si,j = 0 (mismatch score)
* w = 0 (gap penalty)

Three steps in dynamic programming

1. Initialization
2. Matrix fill (scoring)
3. Traceback (alignment)

Initialization Step

The first step in the global alignment dynamic programming approach is to create a matrix with M + 1 columns and N + 1 rows where M and N correspond to the size of the sequences to be aligned.

Since this example assumes there is no gap opening or gap extension penalty, the first row and first column of the matrix can be initially filled with 0.

Matrix Fill Step

One possible (inefficient) solution of the matrix fill step finds the maximum global alignment score by starting in the upper left hand corner in the matrix and finding the maximal score Mi,j for each position in the matrix. In order to find Mi,j for any i,j it is minimal to know the score for the matrix positions to the left, above and diagonal to i, j. In terms of matrix positions, it is necessary to know Mi-1,j, Mi,j-1 and Mi-1, j-1.

For each position, Mi,j is defined to be the maximum score at position i,j; i.e.

Mi,j = MAXIMUM[
Mi-1, j-1 + Si,j (match/mismatch in the diagonal),
Mi,j-1 + w (gap in sequence #1),
Mi-1,j + w (gap in sequence #2)]


Note that in the example, Mi-1,j-1 will be red, Mi,j-1 will be green and Mi-1,j will be blue.

Using this information, the score at position 1,1 in the matrix can be calculated. Since the first residue in both sequences is a G, S1,1 = 1, and by the assumptions stated at the beginning, w = 0. Thus, M1,1 = MAX[M0,0 + 1, M1, 0 + 0, M0,1 + 0] = MAX [1, 0, 0] = 1.

A value of 1 is then placed in position 1,1 of the scoring matrix.

Since the gap penalty (w) is 0, the rest of row 1 and column 1 can be filled in with the value 1. Take the example of row 1. At column 2, the value is the max of 0 (for a mismatch), 0 (for a vertical gap) or 1 (horizontal gap). The rest of row 1 can be filled out similarly until we get to column 8. At this point, there is a G in both sequences (light blue). Thus, the value for the cell at row 1 column 8 is the maximum of 1 (for a match), 0 (for a vertical gap) or 1 (horizontal gap). The value will again be 1. The rest of row 1 and column 1 can be filled with 1 using the above reasoning.

Now let's look at column 2. The location at row 2 will be assigned the value of the maximum of 1(mismatch), 1(horizontal gap) or 1 (vertical gap). So its value is 1.

At the position column 2 row 3, there is an A in both sequences. Thus, its value will be the maximum of 2(match), 1 (horizontal gap), 1 (vertical gap) so its value is 2.

Moving along to position colum 2 row 4, its value will be the maximum of 1 (mismatch), 1 (horizontal gap), 2 (vertical gap) so its value is 2. Note that for all of the remaining positions except the last one in column 2, the choices for the value will be the exact same as in row 4 since there are no matches. The final row will contain the value 2 since it is the maximum of 2 (match), 1 (horizontal gap) and 2(vertical gap).

Using the same techniques as described for column 2, we can fill in column 3.

After filling in all of the values the score matrix is as follows:

Traceback Step

After the matrix fill step, the maximum alignment score for the two test sequences is 6. The traceback step determines the actual alignment(s) that result in the maximum score. Note that with a simple scoring algorithm such as one that is used here, there are likely to be multiple maximal alignments.

The traceback step begins in the M,J position in the matrix, i.e. the position that leads to the maximal score. In this case, there is a 6 in that location.

Traceback takes the current cell and looks to the neighbor cells that could be direct predacessors. This means it looks to the neighbor to the left (gap in sequence #2), the diagonal neighbor (match/mismatch), and the neighbor above it (gap in sequence #1). The algorithm for traceback chooses as the next cell in the sequence one of the possible predacessors. In this case, the neighbors are marked in red. They are all also equal to 5.

Since the current cell has a value of 6 and the scores are 1 for a match and 0 for anything else, the only possible predacessor is the diagonal match/mismatch neighbor. If more than one possible predacessor exists, any can be chosen. This gives us a current alignment of

(Seq #1) A
|
(Seq #2) A

So now we look at the current cell and determine which cell is its direct predacessor. In this case, it is the cell with the red 5.

The alignment as described in the above step adds a gap to sequence #2, so the current alignment is

(Seq #1) T A
|
(Seq #2) _ A

Once again, the direct predacessor produces a gap in sequence #2.

After this step, the current alignment is

(Seq #1) T T A
|
_ _ A

Continuing on with the traceback step, we eventually get to a position in column 0 row 0 which tells us that traceback is completed. One possible maximum alignment is :

Giving an alignment of :

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

An alternate solution is:

Giving an alignment of :

G _ A A T T C A G T T A
| | | | | |
G G _ A _ T C _ G _ _ A

There are more alternative solutions each resulting in a maximal global alignment score of 6. Since this is an exponential problem, most dynamic programming algorithms will only print out a single solution.

Now you are ready to explore an example using an advanced scoring scheme.
BL5495 Home Page
Eric C. Rouchka
ecr@ibc.wustl.edu


Advanced Dynamic Programming Tutorial
If you haven't looked at an example of a simple scoring scheme, please go to the simple dynamic programming example

The following is an example of global sequence alignment using Needleman/Wunsch techniques. For this example, the two sequences to be globally aligned are

G A A T T C A G T T A (sequence #1)
G G A T C G A (sequence #2)

So M = 11 and N = 7 (the length of sequence #1 and sequence #2, respectively)

An advanced scoring scheme is assumed where

* Si,j = 2 if the residue at position i of sequence #1 is the same as the residue at position j of sequence #2 (match score); otherwise
* Si,j = -1 (mismatch score)
* w = -2 (gap penalty)

Initialization Step

The first step in the global alignment dynamic programming approach is to create a matrix with M + 1 columns and N + 1 rows where M and N correspond to the size of the sequences to be aligned.

The first row and first column of the matrix can be initially filled with 0.

Matrix Fill Step

One possible (inefficient) solution of the matrix fill step finds the maximum global alignment score by starting in the upper left hand corner in the matrix and finding the maximal score Mi,j for each position in the matrix. In order to find Mi,j for any i,j it is minimal to know the score for the matrix positions to the left, above and diagonal to i, j. In terms of matrix positions, it is necessary to know Mi-1,j, Mi,j-1 and Mi-1, j-1.

For each position, Mi,j is defined to be the maximum score at position i,j; i.e.

Mi,j = MAXIMUM[
Mi-1, j-1 + Si,j (match/mismatch in the diagonal),
Mi,j-1 + w (gap in sequence #1),
Mi-1,j + w (gap in sequence #2)]

Note that in the example, Mi-1,j-1 will be red, Mi,j-1 will be green and Mi-1,j will be blue.

Using this information, the score at position 1,1 in the matrix can be calculated. Since the first residue in both sequences is a G, S1,1 = 2, and by the assumptions stated earlier, w = -2. Thus, M1,1 = MAX[M0,0 + 2, M1,0 - 2, M0,1 - 2] = MAX[2, -2, -2].

A value of 2 is then placed in position 1,1 of the scoring matrix. Note that there is also an arrow placed back into the cell that resulted in the maximum score, M[0,0].

Moving down the first column to row 2, we can see that there is once again a match in both sequences. Thus, S1,2 = 2. So M1,2 = MAX[M0,1 + 2, M1,1 - 2, M0,2 -2] = MAX[0 + 2, 2 - 2, 0 - 2] = MAX[2, 0, -2].

A value of 2 is then placed in position 1,2 of the scoring matrix and an arrow is placed to point back to M[0,1] which led to the maximum score.

Looking at column 1 row 3, there is not a match in the sequences, so S 1,3 = -1. M1,3 = MAX[M0,2 - 1, M1,2 - 2, M0,3 - 2] = MAX[0 - 1, 2 - 2, 0 - 2] = MAX[-1, 0, -2].

A value of 0 is then placed in position 1,3 of the scoring matrix and an arrow is placed to point back to M[1,2] which led to the maximum score.

We can continue filling in the cells of the scoring matrix using the same reasoning.

Eventually, we get to column 3 row 2. Since there is not a match in the sequences at this positon, S3,2 = -1. M3,2 = MAX[ M2,1 - 1, M3,1 - 2, M2,2 - 2] = MAX[0 - 1, -1 - 2, 1 -2] = MAX[-1, -3, -1].

Note that in the above case, there are two different ways to get the maximum score. In such a case, pointers are placed back to all of the cells that can produce the maximum score.

The rest of the score matrix can then be filled in. The completed score matrix will be as follows:

Traceback Step
After the matrix fill step, the maximum global alignment score for the two sequences is 3. The traceback step will determine the actual alignment(s) that result in the maximum score.

The traceback step begins in the M,J position in the matrix, i.e. the position where both sequences are globally aligned.

Since we have kept pointers back to all possible predacessors, the traceback step is simple. At each cell, we look to see where we move next according to the pointers. To begin, the only possible predacessor is the diagonal match.

This gives us an alignment of

A
|
A

Note that the blue letters and gold arrows indicate the path leading to the maximum score.

We can continue to follow the path using a single pointer until we get to the following situation.

The alignment at this point is

T C A G T T A
| | | |
T C _ G _ _ A

Note that there are now two possible neighbors that could result in the current score. In such a case, one of the neighbors is arbitrarily chosen.

Once the traceback is completed, it can be seen that there are only two possible paths leading to a maximal global alignment.

One possible path is as follows:

This gives an alignment of

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

The other possible path is as follows:

This gives an alignment of

G A A T T C A G T T A
| | | | | |
G G A T _ C _ G _ _ A

Remembering that the scoring scheme is +2 for a match, -1 for a mismatch, and -2 for a gap, both sequences can be tested to make sure that they result in a score of 3.

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

+ - + - + + - + - - +
2 1 2 2 2 2 2 2 2 2 2

2 - 1 + 2 - 2 + 2 + 2 - 2 + 2 - 2 - 2 + 2 = 3

G A A T T C A G T T A
| | | | | |
G G A T _ C _ G _ _ A

+ - + + - + - + - - +
2 1 2 2 2 2 2 2 2 2 2

2 - 1 + 2 + 2 - 2 + 2 - 2 + 2 - 2 - 2 + 2 = 3

so both of these alignments do indeed result in the maximal alignment score.
Eric C. Rouchka ecr@ibc.wustl.edu
Feb. 4, 1997
Compuational Molecular Biology Home Page

Kimberley Locke:Based On A True Story

a pop style, you can feel familiar quitly. here list first three songs in this album


歌词标题: Change

所属专辑:Based On A True Story

所属歌手:Kimberley Locke

Sorry for what I forgot to say
But you know how words get in the way baby, lately
Wasn't strong enough to cut right through
All the red tape between me and you, baby
Time escapes me

What's it gonna take to shake these blues
Pushin' through the clouds just to get to you
Can't hold back the storm that's blowin' through, yeah

(Chorus)
I feel a change, babe
Washin' over me
I feel the rains, babe
Comin' to set me free
It's a one way track
Ain't never comin' back
This trains about to leave
I feel a change comin' over me

Never noticed that it's kinda strange
Same story but a different day lately, baby
Gotta get up gotta change the scene
Gotta rip this page from the magazine

(Chorus)

I ain't tryin' to be difficult no, no
I ain't tryin' to be mean
I just gotta do right now
What's best for me, yeah

(Chorus)


CVS使用CVS进行版本管理

#////////////////////////////////////////////////////////////////////// 
# 使用CVS进行版本管理 
# 2000-6-30 
# CVS 1.10.7 
# 
# 
# 
# Per Cederqvist et al 著 
# 廖斌 译 
# 感谢黄箐的输入和排版工作 
# copyrigh: GPL 
# 
#////////////////////////////////////////////////////////////////////// 
  

快捷内容索引 
1. 概述.........................................................1 
2. 代码仓库.....................................................7 
3. 使用CVS开始一个项目..........................................29 
4. 主干版本(Revision).........................................33 
5. 分支与合并...................................................41 
6. Recarsive behavior...........................................49 
7. 增加,删除,更名文件和目录...................................51 
8. 回顾开发历史.................................................57 
9. 放置二进制文件...............................................59 
10 多个开发者的同时工作........................................61 
11 主干版本管理.............................................71 
12 关键字替代................................................73 
13 跟踪第三方代码...............................................77 
14 你的系统如何同CVS交互........................................81 
15 特殊文件.....................................................83 
16 附录 
1) CVS命令导向..................................................85 
2) CVS命令快速参考............................................115 
3) 管理文件的参考习册.........................................127 
4) 影响CVS的所有环境变量......................................141 
5) CVS各版本之间的兼容性......................................143 
6) 遇到的问题.................................................145 
7) Credits....................................................153 
8) 对CVS和这本手册的总是处理..................................155 

目录 ...........................................................157 
    
  

1 概论 

这一章为从未用过CVS的人写的,也许以前也从未用过任何版本控制工具。 

1.1 什么是CVS? 

CVS是个版本控制系统,使用它你可以记录你原代码文件的历史。例如,当软件修改时有时会产生问题(*bugs这里被译为问题),并且你可能在做这次修改后很长时间不会发现这些问题。使用CVS,你可以容易地回顾老的代码版本去发现哪一次的修改导致这些问题。有时候这样会非常有帮助。 
  

你可能会保留你每一次的代码版本,这可能会浪费你很多的代码空间。CVS使用一种聪明的办法保存你的多个版本在一个文件中。它仅仅保留版本间的不同内容。如果你是一个项目中的一组成员之一,CVS也能够帮助你。除非你特别仔细,你很容易覆盖其他人的工作。一些编辑器,例如GNUEmacs,试图去判定一个文件是否被两人同时修改.不幸的是,如果一个人使用其它的编辑器时,这个安全方式将不再有效。CVS使用让不同开发者独立工作的方式解决了这个问题。每一个开发者的工作都在他自己的目录内,并且CVS将在每个开发者的工作完成后进行合并工作。 

CVS是由Dick Grune作为Shell脚本的一个分支而创建的,1986年10月,在它的第6个发行卷时,它被投递到新闻组comp.soures.unix。然而现在的CVS冲突算法中没有任何代码是从这些脚本中来的。 

在1989年3月,Brian Berlinor设计并编写了CVS的代码。Jett.Polk在以后帮助 Brian 完成了CVS 
模型的设计和商业版本支持。 

你可以通过不同的方式得到CVS,包括在Internet上自由的下载。如果你想下载CVS和其它CVS 
文章以得到更多的信息,请看: 

http://www.cyxlic.com 
http://www.loria.fr/~molli/cvs-index.html. 
  

有一个叫 info-cvs 的邮件列表是有关CVS的内容。订阅或取消订阅这个列表请发邮件到 

info-cvs-request@gnu.org 

如果你更喜欢Usenet新闻组,CVS的讨论组为 

Comp.software.confg.mgmt. 

在将来也许会建一个 

Comp.software.confg.mgmt.cvs 

的新闻组, 

但也许这会是Comp.software.confg.mgmt在有太多讨论之后的事情吧。 

你也许想订阅bug-cvs的邮件列表,这在附录H[BUGS]中有更多的信息。订阅它请发Email到 

bug-cvs-reqnest@gnu.org. 

1.2 CVS不能做的事 
(未译) 
2 
  

3 使用CVS开始一个项目 
======================= 
  

因为更改文件名并且把它们移动到另一个目录中不是经常发生的,因此你在开始一个新项目时要做的第一件事是考虑你的文件组织。更改文件名或移动文件并非不可能,但增加了理解上潜在的费解,并且CVS在更改名字的目录上特别的敏感。请参见7.4节[移动文件]。 
(* 译者注: 在Unix中改名和移动是相同的)。 

下一步做的事取决于手中的情况。 

3.1 建立文件 

第一步是在仓库中建立文件。这可以使用多种不同的方法来完成。 

-------------------------------------------------------------------- 

3.1.1 建立一个目录树 

当你开始使用CVS时,你可能已经有几个项目可以使用CVS进行管理了。在这种情况下,最容易的方法就是使用: "import"命令。一个例子是最容易解释如何使用它的。假定你现在有一些你想放到CVS中的文件在"wdir"中,并且你想让它们放在数据仓库中的如下目录: 

"$CVSROOT/yoyodyne/rdir" 

你可以使用如下命令: 

$cd wdir 
$cvs inport -m "Inported Sources" yoyodyne/rdir yoyo start 

如果你没有使用"-m"参数记录一个日志信息,CVS将调用一个编辑器(*译者注:通常是vi)并且提示输入信息。"yoyo"字符串是开发者标笺,"start"是发行标笺。他们没有什么特别的意义,仅仅是因为CVS的需要才放在这里。 

请参见第13章[跟踪代码],得到更多的这方面信息。 

你现在可以检查一下它是否有效了,然后可以删除你原来的代码目录。 

$cd 
$mv dir dir.orig 
$cvs checkout yoyodyne/dir 
$diff -r dir.orig yoyodyne/dir 
$rm -r dir.orig. 

为了避免偶然进入到你原来的目录中去编辑文件,删除原来的代码是个好主意。当然,在你删除之前保留一份备份到其它地方也是明智之举。 

"checkout"命令能使用模块名作为参数(正如前面所有例子)或是一个相对于$CVSROOT的路 
径,如同上面的例子。你应当检查CVS目录中的权限情况是否合适,应当使它们属于某一个 
特定的组。请参见2.2.2.节[文件权限]。 

如果你想"import"的一些文件是二进制代码,你可以使用一些特殊的方法表明这些文件是否 
是二进制文件。请参见C.2节[Wrappers]。 
  

------------------------------------------------------------------------------------ 

3.1.2 从其它版本控制系统建立文件 

如果你有一个其它版本控制系统维护的项目,例如RCS,你也许希望把这些文件放到CVS中, 
并且要保留这些文件的历史。以下是一些讨论。 

从RCS: 
如果你使用RCS,找到RCS文件??通常一个文件名叫"foo.c"的文件会有"RCS/foo.c,v"的RCS文 
件。(但它有可能在其它地方,请看RCS的文档以得到相关信息)。如果文件目录在CVS中不存 
在,那在CVS中创建它。然后把这些文件拷贝到CVS的仓库目录中(在仓库中的名字必须是带 
",v"的原文件;这些文件直接放在CVS中的这个目录下,而非"RCS"子目录中)。这是在CVS中 
一个为数不多的直接进入CVS仓库直接操作的情况,而没使用CVS命令。然后你就可以把它们 
在新的目录下"checkout"了。 

当你把RCS文件移动CVS中时,RCS文件应在未被锁定的状态,否则移动操作时CVS 将会出 
现一些问题。 

从其它版本控制工具 

许多版本控制工具都可以输出"RCS"格式的标准文档。如果你的版本控制工具可以做到这一 
点,直接输出RCS文件,然后按照上面的例子做就可以了。 

如果你的版本工具不能输出RCS文件,那么你必需要写一个脚本文件来,每次取出一个版本 
然后把它放到CVS中去。下面提到的"sccsarcs"脚本就是一个很好的例子。 

从SCCS: 

有一个"sccsarcs"的脚本文件可以做把SCCS的文件转化成RCS文件,这个文件放在CVS原代码 
目录的"contrib"目录中。注意: 

你必须在一台同时安装了RCS和SCCS的机器上运行它。并且,正如其它在"contrib."目录中的 
其它脚本一样。(你的方法也许是变化多端的) 

(*译者注:我并未查看过CVS的contrib目录:-(,因此不知道这下面都有些什么)。 

从PVCS: 

在"contrb"中有一个叫"pves-to-rcs"的脚本可以转换PVCS到RCS文件。你必须在一台同时有 
PVCS和RCS的机器上运行它。 

请看脚本中的注释以得到更多细节。 

3.1.3从无到有建立一个目录树 

建立一个新的项目,最容易的方法是建立一个空的目录树,如下所示: 

$mkdir tc 
$mkdir tc/man 
$mkdir tc/testing 

在这之后,你可以"import"这个(空)目录到仓库中去。 

$cd tc 
$cvs import -m "created directory structure"yoyodyne/dir yoyo 
start 

然后,当新增一个文件时,增加文件(或目录)到仓库中。请检查$CVSROOT中的权限是否正确。 

------------------------------------------------------------------------------------------- 

3.2 定义模块 

下一步是在"moduyes"文件中定义模块。这不是严格需要的,但模块能把相关的目录和文件容易 
关联起来。下面的例子可以充分演示如何定义模块。 

1. 得到模块文件的工作拷贝。 

$cvs checkout CVSROOT/modules 
$cd CVSROOT 

2. 
编辑这个文件并写入定义模块的行。请参见2.4节[管理文件的介绍]。有一个简单介绍,参见C.1节 
[模块文件]。有它的详细描述。你可以使用下面的行定义模块"tc": 

tc yoyodyne/tc 

3. 提交你的更改到仓库 

$cvs commit -m "Added tc module." modules 

4. 发行模块文件 

$cd 
$cvs release -d CVSROOT 

4 
======= 
  

5 分支与合并 
================== 
CVS允许你独立出一个派生的代码到一个分离的开发版本---分支。当你改变一个分支中的文 
件时,这些更改不会出现在主开发版本和其它分支版本中。 

在这之后你可以使用合并(merging)把这些变更从一个分支移动到另一个分支(或主开发版 
本)。合并涉及到使用“cvs update -j”命令,合并这些变更到一个工作目录。你可以确认 
(commit)这次版本,并且因此影响到拷贝这些变更到其它的分支。 

----------------------------------------------------------------------------------- 

5.1 何时应当创建一个分支 

假定tc.c发行版已完成。你正在继续开发tc.c,计划在2个月后发行1.1的版本。在不久以后你的 
客户开始抱怨说代码有些问题,你检查了一下1.0的发行版(请参见4.4节[标笺])并且找到了这 
个错误(这将会有一个小小的更正)。但是,这个当前的版本是处于一个不稳的状态,并且在下 
一个月才能有希望稳定下来。这样就没有办法去发行一个最新的现有版本去更正问题。 

这时就可以去创建基于这棵版本树1.0版的分支。你可以修改这棵树的分支而不影响到主干。当 
修订完成时,你可以选定是否要把它同主干合并或继续保留在这个分支里。 

----------------------------------------------------------------------------------- 

5.2 建立一个分支 

你可以使用“tag -b”去建立一个分支。例如,假定你在工作于一个工作拷贝中: 

$cvs tag -b rel_1_0_patches 

这将基于当前的拷贝分离出一个分支,并分配“rel_1_0_patches”的名字。 

懂得分支是在CVS仓库中创建,而非在工作拷贝中创建的是非常重要的。正上面的例 
子,创建一个基于当前版本的分支不会自动把当前的工作拷贝转到新的分支上。欲知 
详情,请看5.3节[进入 一个分支]。你也可以不参考任何工作拷贝而建立一个分支。 
你可以使用rtag命令: 

cvs rtag -b -r rel-1-0 rel-1-0-patches tc. 

“-r rel-1-0”说明这个分支是基于标志了rel-1-0的版本文件,它不是从最新的版本 
开始分支.这对需要从老的版本进行分支很有用(例如:当修订一个过去的稳定版本时) 

当使用“tag”标志,这个“-b”标志告诉rtag去创建一个分支(而非是这个版本的符号 
连接)。注意标记“rel-1-0”可能对不同的文件有不同的版本数字。因此,这个命令的结果 
是为tc模块建立了一个命名为“rel-1-0-patches”的新版本分支,它是基于标记为“rel-1-0” 
的版本树。 

----------------------------------------------------------------------------------- 

5.3 进入分支 

你可以通过两种方式进入分支:重新checkout或是从现存的拷贝进入。重新checkout使用 
checkout命令并带上“-r”标识,后面是这个分支的标笺(tag)名。(请看5.2[创建一个分支]): 

$cvs checkout -r rel-1-0-patches tc. 

或者如果你已有了一个拷贝,你可以使用“update -r”命令转到这个分支。 

$cvs update -r rel-1-0-patches tc. 

或者使用另一个等同的命令: 

$cd tc 
$cvs update -r rel-1-0-patches 

这对现有拷贝为主干代码或是其它分支都是有效的.上面的命令将把它转到命 
名的分支。同“update”命令相类似。“update -r”合并你所做的任何改变,请注 
意是否有冲突出现。 

一但你的工作拷贝已经转向一个特定的分支。它将一直保持在这个分支内,除非你 
又做了其它的操作。这意味着从这个工作拷贝checkin的变更将加到这个分支的新版 
本中,而不影响到主干版本和其它分支代码。 

想看一个工作拷贝是基于哪一个分支,可以使用“status”命令。在它们输出中查找 
一个“sticky tag”的域(请参见4.9节["sticky tag"],第38页).那就是你的当前分支号。 

$cvs status -v driver.c backend.c 

==================================================================== 
File: driver.c Status: Up-to-date 

Version: 1.7 Sat Dec S 18:25:54 1992 
RCS version: 1.7 /u/cvsroot/yoyodyne/tc/driver.c,v 
Sticky Tag: rel-1-0-patches (branch: 1.7.2) 
Sticky Date: (none) 
Stick Option: (none) 

Existing Tag: 
rel-1-0-patches (branck: 1.7.2) 
rel-1-0 (revision: 1.7) 
  

==================================================================== 
File: backend.c status: Up-to-date 

Version: 1.4 Tue Dec 1 14:39:01 
Rcs Version: 1.4 /u/cvsroot/yoyodyne/tc/ 
Sticky Tag: rel-1-0patches(branch:1.4.2) 
Sticky Date: (none) 
Sticky Option: (none) 

Existing Tag: 
Rel-1-0-patches (branch: 1.4.2) 
Rel-1-0 (revision: 1.4) 
Rel-0-4 (revision: 1.4) 
  

请不要因为每个文件的分支是不同(“1.7.2”和1.4.2")而迷惑。分支的标笺(tag) 
是相同的:"rel-1-0-patches",这些相同标笺的文件是相同分支的。在以上的例子中,分支建 
立之前,"driver.c" 比 "backend.c"有更多的变更,因此它们的版本编号是不同的。请参见5.4节 
[分支和主干版本号]去了解分支如何构建原理的细节。 

-------------------------------------------------------------------------------------- 

5.4 分支与主干版本 

通常,一个文件的主干版本历史是一个增长线(请看4.1[主干版本]页): 
  
    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 !
    +-----+    +-----+    +-----+    +-----+    +-----+
    
然而,CVS并不局限于线性的开发。主干版本可以分为不同的分支,每一个分支可 
以是一个独立的自我维护的开发线。而在一个分支中的变更可以很容易的转移到主干中。 
每一个分支均有一个分支号,由一个“.”分离的十进制奇数组成,分支号的编排依 
赖于它分离出的主线版本。使用分支号允许从一个特定版本分离出多个分支。 

所有的分支版本都依赖于它的原始分离版本号。下面的例子将展示这一点。 

 
                                                         +-------------+

                       1.2.2.3.2  分支 ->             +--! 1.2.2.3.2.1 !

                                                      !  +-------------+

                                                      !
                     +---------+    +---------+    +---------+
    1.2.2 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !----! 1.2.2.2 !
                  !  +---------+    +---------+    +---------+
                  !
                  !
    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !
                  !
                  !  +---------+    +---------+    +---------+
    1.2.4 分支->  +--! 1.2.4.1 !----! 1.2.4.2 !----! 1.2.4.2 !
                     +---------+    +---------+    +---------+

  

你是如何创建具体的分支号的细节通常不是你需要考虑的,但这里谈谈它如何工作。 

当CVS建立一个分支号时,它先得到第一个未用的偶数,开始的数字是2,例如你 
从6.4的主干版本创建分支时,分支号为6.4.2所有分支号码末位为0的号码用于CVS内 
部,(例如6.4.0)。(请参见5.5节[内部分支号]44页)分支1.1.1有特别的含义,请看13章 
[跟踪代码]。 

----------------------------------------------------------------------------------- 

5.5 内部分支号码 

这一节描述CVS的内部分支(magic branches) (* 译者注:magic branch 译为内部分支) 
特性。在大多数情况下,你不用考虑内部分支号码,CVS将为你进行管理。然而,在 
一些特定条件下,它将显现出来,因此理解它如何工作将是有用的。一般的,分支号 
码将由奇数个 "."分隔的十进制整数组成。请看4.1节[版本号码]。然而那并非完全是这 
样的,由于效率的原因,CVS有时插入一个额外的“0”在右末的第二个位置(1.2.4 
变为1.2.0.4,8.9.10.11.12变为8.9.10.11.0.12等)。 

CVS将会很好的将这些变换隐蔽在背后进行,但在一些地方,这种隐蔽并不完全: 

* 内部分支编号会出现在CVS的日志(log)文件中。 
* 你不能够对 "cvs admin" 使用符号分支名。 
  

你可以使用admin命令去为一个分支重新分配一个RCS希望的那样的符号名。如果 
R4patches是一个分配给分支1.4.2(内部分支编号为1.4.0.2)的一个文件"numbers.c"的 
命名,你可以使用如下命令: 

$cvs admin -NR4patches:1.4.2 numbers.c 

它将只在至少一个版本已经提交到这个分支时才会有效。请非常小心不要把一个标 
笺(tag)分配给了一个错误标识号(现在没有看到昨天的一个标笺是如何分配的)。 

---------------------------------------------------------------------------------- 

5.6 合并一个整个分支 

你可以合并一个分支到你的工作目录在“update”命令中“-j 分支号”的标识。使 
用“-j 分支号”将合并这个派生分支点与原版本的最新版之间的变更到你的工作目录 
“-j”的意思是“join”。 

我们现在来考察下面这棵树: 


    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 ! <- 主干
    +-----+    +-----+    +-----+    +-----+
                  !
                  !
                  !  +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !
                     +---------+    +---------+
                     

分支1.2.2分配了一个Rifix的名字.下面的例子假定模块"mod"只包含一个文件"m.c" 

$cvs checkout mod                             # 得到最新的1.4版 
$cvs update -j R1fix m.c                   # 合并所有在分支中的改变,即:1.2与1.2.2.2 
                                                                  # 之间的变化到这个文件的工作目
录. 

$cvs commit -m "Included R1fix    # 建立1.5版 
  

在合并时可能会发生冲突,如果这种情况发生,你可以在提交新版本之前解决它。请 
参见10.3节[冲突的例子]。 

如果你的原文件中包含关键字(请看第12章[关键字替代])。你可能会得到比严格意义 
上的冲突更多的冲突信息。请参见5.10节[合并和关键字],去了解如何避免这个问题。 
"checkout"命令也支持使用"-j"参数。下面的例子同上面所用的例子有相的效果。 

$cvs checkout -j R1fix mod. 
$cvs commit -m "Included R1fix" 

--------------------------------------------------------------------------------- 

5.7 从一个分支多次合并。 


    继续我们上面的例子。现在这棵树看起来是这样的:

    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !                              *
                  !                            *
                  !  +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !
                     +---------+    +---------+


正如上面所讨论的,分支1.2.2.2所引导的“*”号表示从Rifix分支到主干的合并。

    现在我们继续开发Rifix分支:

    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !                              *
                  !                            *
                  !  +---------+    +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !----! 1.2.2.3 !
                     +---------+    +---------+    +---------+

然后你可能会希望合并新的变更到主干中去。如果你仍使用“cvs update -j Fifix m.c" 
cvs将试图合并你已经合并过的东西,这可能写导致一些不希望发生的东西。 
  

因此,你必须表达清楚你希望只合并未被合并的内容的意思。这样需要使用两个 
“-j“参数。CVS合并从第一个“-j”的版本到第二个“-j”版本的变化。例如,在我们上面 

的例子中: 

cvs update -j 1.2.2.2 -j R1fix m.c 

如果出现的问题是你需要手工指定1.2.2.2的版本号,一个更好的方法是使用: 

cvs update -j R1fix:yesterday -j R1fix m.c 

然而,更好的方式是在每一次合并后重新放一个标笺给Rifix分支,然后使用标 
笺做后的合并: 

cvs update -j merged_from_Rifix_to_trunk -j R1fix m.c 

---------------------------------------------------------------------------------- 

5.8 合并两个任意版本之间的不同 

使用两个“-j”标志,这个update(和checkout)命令能合并两个任意不同的版本 
到你的工作目录。 

$cvs update -j 1.3 backend.c 

将把1.5版本恢复到1.3版本,所以一定要注意版本的顺序。 

如果你在操作多个文件时使用这个选择项,你必须了解在不同的文件之间,版本的 
数字可能是完全不同的。你必须使用标笺(tag)而不是使用版本号来完成多个文件 
的操作。使用两个“-j”操作也能会恢复增加或删除的文件。例如,假定你有一个 
叫“file1”的文件在在于1.1版本中,然后你在1.2版本中删除了它,下面是如何操作的例子: 

$cvs update -j 1.2 -j 1.1 file1 
file1 
$cvs commit -m test 
checking in file1; 
/tmp/cvs-sanity/cvsroot/first-dir/file1 file1,v 
new revision:1.3; previous revision:1.2 done 
$ 

------------------------------------------------------------------------------------ 

5.9 合并能添加和删除文件 

如果你在合并时的改变涉及到添加或删除一些文件,“update -j”将反映这些变化。 
例如: 

cvs update -A 
touch a b c 
cvs add a b c ; cvs ci -m "added" a b c 
cvs tag -b branchtag 
cvs update -r branchtag 
touch d ; cvs add d 
rm a ; cvs rm a 
cvs ci -m "added d , removed a" 
cvs update -A 
cvs update -j branchtag 
  

在这些命令之后(注意要commit),文件'a'将被删除,而文件'd'将被加入到主干。 

------------------------------------------------------------------------------------- 

5.10 合并和关键词 
  

如果你合并的文件包含关键词(参见第12章[关键词替代],73页),你通常将会在 
合并时得到 无数个冲突报告,因为在不同版本中非常不同。 

因此,你常需要在合并时使用“-kk”(参见12.4节[替代模式],75页)选择项。使用 
关键字名字,而非去扩展关键字的值的方法,这个功能选择项确保你合并的版本之间互相相 
同,而避免了冲突。 

   例如:假设你有一个文件如下:

                     +---------+
        br1   ->  +--! 1.1.2.1 !
                  !  +---------+
                  !
                  !
    +-----+    +-----+
    ! 1.1 !----! 1.2 !
    +-----+    +-----+  
  
  

并且你的当前工作目录拷贝为主干(1.2版本)。那么对于以下的合并将会产生一个 
冲突的结果。请看例子: 

$cat file1 
Key $Revision: 1.3 $ 
... 
$cvs update -j br1 
U file1 
RCS file: /cvsroot/first-dir/file1,v 
retrieving revision 1.1 
retrieving revision 1.1.2.1 
Meging differences between 1.1 and 1.1.2.1 into file1 
rscmerge: warning: conflicts during merge 
$ cat file1 
$<<<<<<< file1 
Key $Revision: 1.3 $ 
======= 
Key $Rerision: 1.1.2.1 $ 
$>>>>>>> 1.1.2.1 
... 
  

冲突发生在试图将1.1和1.1.2.1合并到你的工作目录中去的时候。因此,当这个 
关键词从“Revision:1.1"到"Revision:1.1.2.1"时,CVS将试图合并这个变化到 
你工作目录, 这就同你的目录中的变更“Revision:1.2"发生了冲突。 

以下是使用了:“-kk”后的例子: 

$cat file1 
key $Revision: 1.3 $ 
... 
$cvs update -kk -j br1 
V file1 
RCS file: /cvsroot/first-dir/file1,v 
retrieving revision 1.1 
retrieving revision 1.1.2.1 
Merging differences between 1.1 and 1.1.2.1 into file1 
$ cat file1 
key $Revision: 1.3 $ 
... 

在这里版本“1.1”和“1.1.2.1"都扩展为单纯的 "Revision",因此,合并时就不会 
发生冲突了。 

然而,使用 "-kk" 参数还一个主要的问题。即,它使用了CVS通常使用的关 
键字扩展模式。在特殊情况下,如果模式使用针对二进制文件的 "-kb" 
参数。这将会产生问题。因此,如果你的数据库中包括有二进制文件,你将 
必须手工处理这些问题,而不能使用 "-kk"。 

10 多个开发者同时工作 
--------------------- 

当多个开发者同时参与一个项目时,常常会发生冲突。一般经常发生的情况是两个人想 
同时编辑一个文件的时候。它的解决方法之一是文件锁定或是使用保留式的checkout,这种 
方法允许一个文件一次只允许一个人编辑。这是一些版本控制系统的唯一解决方式,包括 
RCS和SCCS。现在在CVS通常使用保留式checkout的方法是使用"CVS admin-1"命令(参见A-6-1AB 
[admin选择项])。在下面将解释这不是一种好的智能的解决方式,当它是许多人喜欢使用的 
一种方式。下面也将讲述可以使用适当的方法来避免两个人同时编辑一个文件,而非使用软件 
的方式强迫达到这一点。 

在CVS中默认的方法是"unreserved checkout"--非保留式的导出。在这种方法下,开发者 
可以同时在他们的工作拷贝中编辑一个文件。第一个提交工作的没有一种自动的方法可以知道 
另一个人在编辑文件。另一个人可能会在试图提交时得到一个错误信息。他们必须使用CVS命令 
使他们的工作拷贝同仓库的内容保持更新。这个操作是自动的。 

CVS可以支持facilitate多种不同的通信机制,而不会强迫去遵守某种规则,如"resered 
checkouts"那样。以下的部分描述这些不同的方式是如何工作的,和选择多种方式之间涉及到 
的一些问题。 

10.1 文件状态 

基于你对导出的文件使用过的操作,和这些文件在仓库中的版本使用过的操作,我们可以 
把一个文件分为几个状态。这个状态可以由"status"命令得到,它们是: 

up-to-date: 
对于正在使用的这个分支,文件同仓库中的最后版本保持一致。 

Locally Modified: 
你修改过文件,但没有"commit"。 

Locally added: 
使用了"add"命令增加文件,但没有"commit" 

Locally Removed: 
你使用了"remove"命令,但没有"commit" 

Needs checkout: 

其他人提交了一个更新的版本。这个状态的名字有些误导,你应当使用"update"而非 

"checkout"来更新新的版本。 

Needs Patch: 
象"Needs checkout"一样,但CVS服务将只给出Patch(补丁)文件,而非整个文件。而 
给出Patch和给出整个文件的效果是相同的。 

Needs Merge: 
一些人提交了一个更新版本,而你却修改过这些文件。 

File had conflicts on merge: 

这同"Locally Modified"相象,只是"update"命令给出了一个冲突信息。如果你还没有 
解决冲突,那么你需要解这个问题,解决冲突的方法参见10.3节[冲突的例子]. 

Unkown: 

CVS不知道关于这个文件的情况.例如,你创建了一个新文件,而没有使用"add"命令 

为了帮助弄清楚文件的状态,"status"也报告工作版本(working 
vevision),这是这个文件是从哪个版本来的,另外还报告"仓库版本"(Repository 
vevision)。这是这个文件在仓库中的这个版本分支的最后版本。 

"status"命令的选择项例在附录B[invoking cvs]。有关"sticky tag"和"sticky 
date"输出内容的信息,参见4.9节[sticky tags]。有关"sticky options"输出内容参见"-k"选择项, 
A.16.1节[update选择项]。 

你应当把"update"和"status"命令放在一起来认识。你使用"update"使你的文件更新到最 
新状态,你使用"status"命令来得到"update"命令将会做何种操作。(当然,仓库中的状态将可 
能会在你运行update之前变化)。事实上,如果你想使用一个命令得到比使用"status"正式的状 
态信息,你可以使用: 

$cvs -n -q -update 

这里"-n"选择项表示不真正执行update,而只显示状态;"-q"选择项表示不打印每个目录的 
名字。有关更多的关于"update"命令的住处参见附录B[使用CVS]。 

10.2 使一个文件更新到最版本 

当你想更新或是合并一个,使用update命令。对于一个不是最新版本的文件,这个命令大略等 
同于"checkout"命令:最新版本从仓库中提出并放到工作目录中。 

当你使用"update"命令时,你修改过的文件在任何情况下不会受到损害。如果在仓库中没有更 
新的版本,"update"时你的代码没有任何影响。当你编辑过一个文件,并且仓库中有更新版本,那 
么"update"将合并所有的变更到你的工作目录。 

例如,想象一个你导出了一个1.4版的文件并且开始编辑它,在某一时候其他人提交了1.5版,然 
后又提交了1.6版,如果你运行update命令,CVS将把1.4版到1.6版之间的变更放到你的文件中。 
如果在1.4版和1.6版之间的改变太靠近于的你一些变更的话,那么一个"覆盖"("overlop")冲突 
就发生了。在这种情况下将输出一个警告信息,然后结果保留的文件中包含了有冲突代码的两个版 
本,由特别的符号所分隔开。请参见A.16节[更新],可以得到关于"update"命令的一个完全的描述。 (http://www.fanqiang.com) 进入【UNIX论坛】

Version Control Systems

Version Control Systems Support
Synchronisation
Rollback
Experimentation
Internationalisation
Historical Record

Version Graphs
Extension
Split
Merge

A Version Control System lets you “check out” versions of a version control file


Locking Vs. Version Tracking

Locking
prevents complicated conflict resolution problems arising
also prevents duplication of effort (two programmers both doing the same thing at the same time)
Version tracking
prevents one person’s work being held up because someone else is using the file they want - or worse still, has forgotten to check the file back in
allows two developers to work on different sections of the same file at once

Lecture 12: Interrupts, Exceptions and I/O

Exceptions are caused by program execution:
Integer arithmetic overflow – result outside [−231, +231)
Division by zero
Illegal instruction – machine code doesn’t make sense
Address error – access to unaligned address
Bus error – access to non-existent address
syscall instruction – when we need an OS request
brk (breakpoint) instruction – used by debuggers
Can be thought of as a synchronous software interrupt. . .

Interrupts arise from external devices:
Disk read complete (via DMA, say)
Memory error (but only with EEC RAM)
User pressed a key on console
Console ready to display another character
Hardware timer expired
Can be thought of as asynchronous hardware exception

Exception Handlers
Hardware saves current PC in a special register
CPU jumps to an exception handler, which
Saves the current processor state
Take appropriate internal action for an exception, or
Deal with the external source of the interrupt
Restores the previous processor state
Resumes user program execution, if possible

BadVAddr $8 offending memory reference
Count $9 current timer; incremented every 10ms
Compare $11 interrupt when Count = Compare
Status $12 controls which interrupts are enabled
Cause $13 exception type, and pending interrupts
EPC $14 PC where exception/interrupt occured


Interrupt mask which of the 8 interrupts are allowed
User mode not simulated by SPIM; always 1
Exception level automatically set during an exception; prevents handler itself being interrupted
Interrupt enable global interrupt enable (or disable)

Monday, 14 May 2007

Pointers and References, Arrays and Strings,Heap and Memory Management

References in Java
A reference is essentially an object’s memory address

Variables containing address are often termed ‘pointers’
A pointer can be thought of as a low-level reference
‘Pointer arithmetic’ – e.g. add offsets, indexing
A pointer is just another type, like an int or a float
Everything stored in memory, pointers included, has an
address: another pointer can even point to it

Arrays
Usually a block of consecutive elements in memory
All same size (s bytes); same offset from one to the next
The i th element is at offset i × s bytes from beginning
Looking up an element of the array is termed ‘indexing’
Assembly equivalent of an int[] in Java would be. . .
a consecutive block of word-sized signed integers
represented by its starting address and length

static data: Contents may change, but size and location doesn’t
In Java, "hello" + "world" contatenates two strings, But neither of the original strings are modified. Instead a new string is created on the heap
The heap is a much larger pool of memory than the stack
Java allocates storage on the heap with the new keyword
All Java objects live on the heap; only primitive types –ints, floats, doubles and references – on the stack
Storage allocated on the heap persist across procedures. Caller can’t access stack storage//-----?????????????

Lecture 10: MIPS Procedure Calling Convention and Recursion

A portion of code within larger program, typically called:
procedures or subroutines in imperative languages like C
methods in OO languages like Java
and functions in functional languages such as Haskell
Functions usually return a value; procedures don’t
Procedures can call other procedures; even themselves

What happens when we call a procedure?
Control hands over to the callee; the caller is suspended
Callee performs requested task
Callee returns control to the caller

Calling Procedures in MIPS Assembly
jal label – jump and link
$ra := PC + 4; PC := [label]-----??????????
Calls procedure at address label
jr src – jump register
PC := src
Issuing j $ra is the assembly equivalent of return

Register $ra contains the return address of the caller
Arguments are passed in registers $a0 to $a3
Results are left in registers $v0 and $v1

The Stack
The stack provides last-in, first out (LIFO) storage
Register $sp points to the topmost word on the stack
By convention, the stack grows downwards
Placing words onto the stack is termed pushing
Taking words off the stack is called popping

Calling Convention
Caller

Push any of $a0-3, $v0-1 and $t0-9 needed later
Place arguments in $a0 to $a3, and stack if necessary
Make the call using jal callee; result in $v0 and $v1
Pop saved registers and/or extra arguments off stack
Callee
Push any of $ra, $s0-$s1 that may be overwritten
Perform desired task; place result in $v0 and $v1
Pop above registers off the stack
Return to caller with jr $ra

The main label is just another procedure


Local Variables
Solution: save initial value of $sp in $fp //---------?????????
Hence local variables always have the same $fp-offset
Note callee must preserve previous value of $fp!

杀人游戏

An occasional chance wake me to search something about Mafia-game, because it seems to be not fashion as a teenage if you do not know it or you can not play。 So, wiki again can tell me much about it even I have no chance to through.


Mafia (game)

For the video game, see Mafia: The City of Lost Heaven.
Mafia

Players 4 or more
Age range 9 and up
Setup time < 6 minutes
Playing time 15-60 minutes2
Random chance Low
Skills required Strategic thought
Team play
Social skills
Roleplay
See Basic gameplay below.
Varies greatly with setting; see online play.
Mafia (also known under the variant Werewolf or Village) is a party game modeling a battle between an informed minority and an uninformed majority. Mafia is usually played in groups with at least five players. During a basic game, players are divided into two teams: 'Mafia members', who know each other; and 'honest people', who know only the number of Mafia amongst them. The goal of both teams is to eliminate each other; in more complicated games with multiple factions, this generally becomes "last side standing".

History
Mafia was created by Dimma Davidoff at the Psychological Department of Moscow State University, in spring of 1986, and the first players were playing in classrooms, dorms, and summer camps of Moscow University. The game become popular in other Soviet colleges and schools and in the 1990s it began to be played in Europe (Hungary, Poland, England, Norway) and then the United States. Mafia is considered to be one of "the 50 most historically and culturally significant games published since 1800" by about.com.

Andrew Plotkin gave the rules a Werewolf theme in 1997 [1] - Looney Labs have sold this version of the game as Are You a Werewolf?, as have Asmodée Éditions under the title Werewolves of Millers Hollow.

David and Jon Huston created another version in the theme of H. P. Lovecraft's Cthulhu Mythos called Do You Worship Cthulhu, published by Toy Vault, Inc. The main card art was completed by Ron Spencer and Walt Howington designed the Instruction graphics.

A variation of Mafia was used in the movie Cry_Wolf. The game involves one wolf, one shepherd, and a number of sheep, with no day and night phases.

Adam Gopnik devotes a chapter to describing the game in "Through the The Children's Gate: at home in New York" (Knopf, 2006).


Basic gameplay

Roles

Players make themselves comfortable in a space such that every player can see every other player. Roles are assigned by a method which is both confidential and verifiable, often by dealing cards; a red or black card signifies the role as either:

Mafia (alternatively, Werewolves or Worshipers)
Innocents (alternatively, Villagers, Townspeople, or Citizens).
Other roles are possible (see Variants).

Generally, gameplay also requires a Narrator (alternatively, Dealer, Don, God, Host, Mayor, Moderator, Proctor, or Storyteller), a person not playing, but moderating the game. The Narrator knows the roles of each of the players and effectively narrates gameplay. However it is possible to have the first dead player become the Narrator when starting with the day phase.


Night
The Narrator tells everyone to close their eyes and lower their heads ("Go to sleep...", "It is now nighttime and all the villagers are asleep...", etc.). This can optionally be accompanied by all players tapping gently to mask the sounds of player movement. On the first night, the Narrator tells the Mafia to open their eyes and acknowledge their fellow Mafia members. Variations at this point:

The Mafia may have a chance to kill off one of the Innocents by show of hands.
On the first night, the Mafia may "kill" the Narrator so that every Innocent gets a chance to participate in at least one execution decision. The Narrator then says in the Morning that he was killed and gameplay continues as usual.
After the first night, Mafia members must secretly communicate during the daytime and then unanimously agree to kill someone during the nighttime without opening their eyes to communicate (i.e., Narrator calls out the names of each player and Mafia must raise a hand to signify a kill). This rule is optional; if it's not included, the Mafia may kill an Innocent in the same method as they did the first night.
In large groups, each Mafia member can kill one person per night.
Other variant characters may have turns to open their eyes to do "business" during the night also (before or after the Mafia).


Day
The Narrator tells everyone to wake up and announces the Mafia's victim. Usually this involves the Narrator telling a story about the murder scene that the remaining players wake up to, and/or a story of how the victim was killed. For example, "The police chief said, 'Bob was shot seven times, stabbed three times and drowned in the river. This is the worst case of suicide I've ever seen.'" This player is "dead" and may no longer participate in the game in any way, and is thus permitted to keep their eyes open at night.

Depending on the variant, The Narrator may reveal the identity of dead players, dead players may reveal themselves by flipping their cards face up (most common version), or the identity of dead players may be left unrevealed. Typically, prematurely revealing one's identity by flipping one's card face up while still alive is considered suicide; in single-execution-per-day variants, this may count as the execution for that day.

During the daytime phase, the players deliberate over which suspected Mafia member they wish to nominate for execution. The Innocents want to execute a Mafia member but all players are allowed to vote. Generally, The Narrator will administer the election, the nominee may be given a chance to defend themselves and a majority is required for the execution to be carried out, although voting variants abound. The same rules apply to players who are executed as to players killed by the Mafia. In some variants, multiple players may be killed during the same day.


Win condition
The game ends either when the last Mafia member is killed (Innocent victory) or the Mafia members gain a majority during the day (Mafia victory). Ties go to the Mafia. The innocents have no way of voting off mafia members at this point, but the mafia can still kill each night. Other variants have different victory conditions.

Note that in a situation of Mafia and Innocent left after a lynching or a morning, the Mafia character usually automatically wins.


Number of Mafia
A game with just one more innocent player than Mafia players during the day phase can still be won by the innocent players (if you start with a night kill, you need two more innocent players than mafia). However, if they make any mistake (i.e. killing an innocent player during the day), they lose.

So the number of "extra villagers" needs to be adjusted to how many mistakes the innocent players are allowed to make during the game. If you have highly skilled players, play with a small difference, if your players tend to just kill random people during the day, increase it. For large parties, kills tend to be much more random, too.

You can start playing mafia with just 3 players, one of which is Mafia (4 if you kill in the first night). This situation however is extremely hard to play lacking any previous knowledge. If the mafia player convinces one of the other two players he wins (draw rule), if he makes both of them suspect him, he loses.

A 5 player setup with just 1 mafia (6 if you kill in the first night) is a bit more interesting. If the innocent players don't happen to identify the mafia player in the first day (which isn't easy), they end up with the same 3 player setup as explained above (or win, if they managed to identify the mafia player), but the remaining players do now have extra information from the behaviour in that previous round.

Empiric values such as 1/3 or 1/4 of players being mafia are common, but again, this depends on the skill of your players. Other players recommend certain combinations such as 2 mafia and 4-5 innocent players, 3 mafia and 6-8 innocent players (and/or discourage larger rounds). There is no mathematically sound 'optimal' value except above "n mafia, n+1 innocent players during the day can still be won by the innocent players" statement.

(Mathematically speaking, this game is not fair. Assuming that all players could read minds, the mafia only wins if they are at least 1/2 of the players in the game. Fortunately, most people can't read minds; but they do usually perform better than a randomizer.)

Variant character roles and rules can change this setup significantly and usually increase or reduce the need for having extra innocent players. But others are targeted at giving the players more data for the 1 mafia vs. 2 innocent "end game"; this data doesn't need to be reliable, but just to give the players more information to base their judgement upon. So when playing with variant character roles, you might or might not have to modify your game parameters.


Variations
Over the years, players have created Mafia variants which utilize alternative names for characters, additional characters, and different methods for conducting deliberation, voting and killing.


Optional roles
Due to the informal nature of the game, roles can be named differently due to cultural differences, thematic flavor, or other reasons. What follows is a general list of types of roles that can be found in Mafia and Werewolf games; it is by nature non-exhaustive.

Protective roles - "Guardian Angel", "Doctor", "Healer", "Archangel", "Bodyguard", "Sorcerer", "Priest", "Protector", "Highlander", "Nurse", etc.
Allied with the Innocents, this person can protect other roles at night. Depending on the variant, they may know the identities of the Mafia and may attempt to persuade the townspeople to kill the members of the mafia rather than another innocent. Sometimes they are allowed to protect themselves. In some games the Nurse obtains the Doctor's abilities if that role dies. Another variant is the "Bulletproof" innocent, who cannot be killed at night by anyone. (In Werewolf, for example, this person could have wolfsbane.)
Investigative roles - "Detective", "Commandant/Super Commandant", "Cop", "Seer", "Spy", "Angel", "Sheriff", "Psychic", "Inspector", "Cattani", "Devil", "Tracker", "Prophet", "Little Girl", etc.
Allied with the Innocents, this person can detect the alignment of other players at night. Occasionally the role will be themed to reveal the role, instead of the alignment. In some variants, the Narrator may lie to the Detective by showing all players as Innocent, all as Guilty, giving reversed results, or random information; these can be termed as "Naïve", "Paranoid", "Insane", or "Random" respectively. A "Tracker" may see what someone's night action was, or the target of their action, and have to deduce information from that. When the Devil exists, he works for the Mafia/Werewolves, trying to discover Innocents with night actions (usually the Angel/investigative roles). The Commandant is equivalent to the detective, though the Super Commandant has an additional protective feature which allows the inspected person (who can be the Commandant, himself) to survive an attempted Mafia killing in the night. The Little Girl in Werewolf is allowed to secretly peek and watch as the werewolves choose their victim.
Killing roles - "Vigilante", "Rambo", "Crazy Veteran", "Bomb", "Terrorist", "Gravedigger", "Hunter", "Village Bicycle", etc.
Aside from Mafia, Werewolves, and Serial Killers (solitary guilty parties), the Innocents may have some roles with the ability to kill at night. The method varies: the Vigilante may have one or more "bullets" for the entire game, or the Bomb/Crazy Vet may only trigger if targeted at night (not necessarily for death) by another role. Variants exist where this person can kill during the daytime cycle (e.g., the Terrorist / Gravedigger), sometimes only if executed during the daytime (eg. the Hunter / Village Bicycle).
Alignment roles - "Miller", "Godfather", "Alpha Wolf", "Traitor", "Village Idiot", "Undercover Cop", "Rat", etc.
Some roles can fool investigations to determine their alignments: the Miller is an Innocent who appears guilty (usually because they are an outsider); the Godfather, on the other hand, appears innocent despite being the leader of the Mafia. The Alpha Wolf is analogous to the Godfather, while the Traitor works with their vote during the day cycle to protect Mafia and hamper the town. The Village Idiot's objective is to get the town to kill him. The Rat or Undercover Cop is a mole within the Mafia group.
Role manipulators - "Role-blocker", "Godfather", "Prostitute", "National Guardsman", "Switcher", "Bus Driver", "Thief", "Witch", "Sorcerer", "Barman", etc.
These roles can stop or alter the night actions of others; for instance, they may prevent a protection or investigation from occurring, or they may change the target. Not all of these roles will be on the side of the Innocents. The Thief may remove the person's role entirely (for instance, by stealing a Vigilante's gun). The Godfather has the ability to recruit innocent players to become Mafia under certain circumstances. This role differs from the Alignment Role of Godfather above.
Association roles - "Freemasons (Masons)", "Siblings", "Cult Leader and Followers", "Cupid", "Lovers" etc.
These roles, usually on the side of the Innocents, know who each other are and what their roles are. Freemasons (Masons) may talk at night, and confirm each other should one become the target of a murder. Siblings typically consist of one Mafia and one Innocent who are related by blood; if one dies, the other commits suicide shortly thereafter. Cult Leaders can recruit at night instead of kill; therefore they act as an independent faction from both the Innocents and Mafia, usually with the ability to talk at night. Cupid can create a Sibling-like relationship between two random players of his/her choosing (called the Lovers) the first night of the game. In this variant, the Lovers can also win the game (regardless of whether they are Mafia, Innocents, or both) by being the last two standing.
Power roles - "Mayor", "Judge", etc.
This role is taken in addition to the assigned role, and it endows the character with additional power over the game (particularly during the daytime). The character could be chosen by random or selected by vote (which could take place before or after roles are assigned). For instance, a Mayor could possess two votes, or a Judge could moderate discussion in parliamentary fashion (to the advantage of their "team"). If the Power character is also an Innocent (and particularly if they have a helpful role), they aid the town. If they are Mafia, this character aids the Mafia.
Additional variations exist, sometimes with even more specialized or complicated abilities.


Optional rules
Mafia killing methods - some variants require all Mafia members to choose the same victim independently for a kill to succeed. Theoretically, this requires them to "communicate" in some way during the daytime and thus increases the chances of detection. This can be achieved either by waking the Mafia members up separately or by having them write their kills. Under this variant, Innocent players write the word 'honest' on a piece of paper; Mafia members write down the name of a player for elimination. If all the mafia notes have the same name on them, that player is considered killed by the Mafia. In some online versions of the game, a particular player (the Godfather, or a designated member of the group) must send in or execute the kill.
Voting variants - some variants have a more complicated process of selecting players to be executed. One variant allows multiple simultaneous nominations and only requires a plurality. Another requires the vote to be unanimous but allows multiple players to be added to the execution queue to ensure unanimity.
"No lynch" or "No kill" - sometimes the Innocents are allowed to vote not to kill anyone on a particular daytime cycle. In general, although the Townspeople will often feel they do not have enough information to kill someone, this is a bad choice because the Townspeople are more likely to vote off a Mafia member than the Mafia are to kill a Mafia member. Furthermore, because a player's role is generally revealed when that player is executed, it provides the Townspeople with reliable and irrefutable information. However, when there are an even number of Townspeople, this can be a good choice. For example, when there are four Townspeople remaining (including one Mafia), voting not to kill someone will result in a 1/3 chance to kill the Mafia the next day as opposed to a 1/4 chance. Note that voting incorrectly in either situation will end the game (resulting in a 1 Mafia/1 Innocent standoff, which is almost always resolved by the Narrator in favor of the Mafia).
Random narrator - to eliminate the inconvenience (especially in large games) of being killed on the first day, this variant has the Innocent who is killed on the first night become the Narrator. The Mafia, of course, has to find a way of informing this person that they are dead without revealing their identities. The writing variant works best. Some players complain that this variant is biased toward eliminating those who are skilled at narrating. This also works the other way round -- there is no kill in the first night (or a fictious player such as the Major or Kenny is killed), but the mafia still wakes up just to learn their identies; the player killed at day becomes the real narrator.
Multiple families - this variant has multiple Mafia families (or a Mafia group and a Werewolf group) who act and win independently of each other. This allows more kills and thus a faster gameplay and also creates the potential for "cross-fire" between the factions.
Imprisonment - this variant allows players to be sent to prison as an alternative to execution. Depending on the variant they can either be sent there by vote or at the discretion of an optional character. Players in prison exist in the separate room possibly with a separate narrator. Murders can happen in prison and certain roles or events have the ability to bring characters back from prison.
Kidnapping - like imprisonment, this variant allows for a Kidnapper character to remove individuals from the game temporarily. If the kidnapper is killed (or, in some cases, investigated by an Investigative role), all kidnapped individuals (whether Mafia or Innocent) return to the game. While kidnapped, characters are considered "dead." However, they can not watch nighttime events because of the possibility of returning.
Wrath of God - this variant allows the Narrator to select in a random and verifiable manner one or more Innocents, (depending on how many total players are in the game) to carry a cost for their death(s). If for example, the Mafia selects said Innocent during the night round, then the Mafia who selected the "protected" player will also die as a result. If during the day round any player leads an accusation towards the "protected" player and that player is voted out, then the original accusor shall die as well. This variant adds to the confusion by allowing players to claim "divine protection" and also makes selecting players to die during the day or night a much more cautious process.
Plague - this variant allows the Narrator to select in a random and verifiable manner one player who dies of plague in the morning. This can occur at set time intervals, or at random, and the player killed in this manner is revealed at the beginning of the next day. A player who targets the plagued player at night may then become plagued as a result of the contact.
Punishment - this variant is generally used as a drinking or risk based game. When a person is killed in the game they are made to take a punishment. In Drinking circles this may be a shot of a spirit such as Gin or Vodka. The punishment is usually decided at the start of the game. A Final punishment could also be added for the losing team too.

Online play
Although Mafia is usually played face to face, playing it online is also common. This adds a new dimension to the game, making it last longer and allowing people to have a record of what others have said and how they have voted. There are many forms of online play: as part for the promotion of the film Cry_Wolf a website was set up to play a similar game using AIM Instant Messenger, pitching wolves against sheep.

Online forum play was first known to be run on the Internet forum Grey Labyrinth by a regular poster from that site. The game requires 1 or 2 moderators to control. A sign up thread is created announcing the game. The game usually starts in the night phase with players messaging the moderator with their choices, and the mafia teams communicating via email before submitting their kill. The moderator will process the choices, write the appropriate death scene for those that were eliminated, and post a dawn scene. Then the players will vote for who they think is mafia. Generally speaking the first day of the online game is very random in nature, but as the game progresses the lynching becomes more strategic and planned.

Themes are the most common method of online play. Any group of well known characters or groups will work. The Simpsons, Hanna Barbera, The Lord of the Rings for example have been used because of their extensive character sets. In themed games, Roles tend to be more creative and relate to the scenes in which they are set. It is not uncommon for major characters to be left out of the balance of roles to allow the mafia teams to lie about who they are. Themes can also be Types - such as a Werewolf-themed game, or more extreme such as Time Travel Mafia or Deep South (a variant with no night phase).

Moderating online play generally requires you to attempt to balance the game well so any team or group has an even chance of winning. This is even more pertinent when using powerful creative roles. The balance is usually 25% mafia - so a 12 player game would entail 3 or 4 mafia depending on the balance of the remainder of the game. A brief listing of the known online variants follows (some would be near impossible to play in real life).

Deep South Mafia - also known as nightless mafia. The game is broken into choice blocks which last a set amount of real life time. During a choice block, players can vote to lynch and/or submit their choices to the moderator. The moderator will action them at a set time. If a player is lynched during that time, the choice block will end immediately, and all votes are nullified and the next block begins. Choices are always made first as part of an update, and then voting. Some moderators may care to flip this rule around. Choices are made in the order received. Common roles for this variant are "Lie Detector" who can detect a lie in a role claim by a player. "Mafia/Serial Killers" who kill during the day at any time. "Advance doctors" who can protect one choice block in advance. "Chef" who can call lunch and end a choice block once.
Grey Labyrinth's Designer Mafia is to have all prospective players invent a role and submit it to the moderator. The moderator tones the roles down to make them playable and then shuffles them up amongst the players.
Location-based games often have maps involved in which players have to travel to different destinations.
MafiaScum.net's Time Travel mafia allows players to alter history with their night choices. Roles are not revealed on death in this variation because players can be brought back to life at any stage. Time travelling roles are usually restricted to prevent chaos. Standard roles are "Coroner" who can investigate a corpse at night. "Blocker" who can prevent a player time travelling. "Serial Killer" who can travel back 1 or 2 nights to kill someone. One of the major changes in Time Travel mafia is that the person with the most votes at the end of a set time is lynched. This means that if a player votes and then dies on a previous night due to a history change, the vote is effectively nullified.
Romanian Mafia Club's Ebony and Ivory mafia games give every player a black ebony ball and a white ivory ball which stand for votes, and the players can effectively work towards lynching or saving others, because every white ball (a vote in favor of that player) takes out a black ball (a vote against him) that he received. The end of the day brings death to the role that has the most black votes.
Mafiascum is an Internet forum where registered members can play a game of Mafia with other people over a message board. Mafiascum has been around since March 2002 and is a direct descendant of the Grey Labyrinth, an Internet forum dedicated to all types of puzzles and games; when Mafia began to dominate the site's traffic and player base, one of the administrators set up a separate forum specifically for those games. Since its creation, membership has grown and diversified, with games now played under different rulesets, in different languages, and at different skill levels. Recently the gamesite moved to an independent server to accommodate these levels of growth. Players have also contributed to a Mafia-specific wiki about game play, strategy, roles, and local players.




http://www.psytopic.com/mag/post/513.html关键词:谎言

杀人游戏最饱受质疑的地方,就是谎言。想在游戏中获胜,关键是不管真话假话,都要说得“理直气壮”。你不能相信其他任何玩家,必须不断制造谎言或者戳穿谎言。

杀手说:一位从事警察工作的玩家对其体会是三个字:可信度。他说,就是简简单单的三个字,可它却成为如今人与人之间最难以把握和捉摸的一种情愫。而“杀人”游戏虽然明里是一个人骗人的游戏,而实则是在教我们如何学会信任。

关键词:友情

“和朋友,可以喝酒,可以旅行,可以逛街,可以结死党,可以相互吹吹牛,拍拍马……但就是不能一起玩‘杀人游戏’。因为,‘杀人游戏’就是一个凶险江湖缩影,一不小心,就暴露了你隐藏很深的底牌,得不偿失。”这是很多人都信奉的一句话。

杀手说:很多圈中人“每次去杀人吧,像回到了家”。他们在游戏中达成默契,结下友谊。这些互为“老朋友”的人,也许不会主动询问你的职业、你的手机号,甚至对你的姓名和年龄都一无所知,但是需要的时候,会给予热情的帮助。

关键词:沉迷

湖南师范大学社会学教授陈成文指出,这类游戏属于心理暗示游戏,游戏者追求游戏的快感和刺激程度往往容易沉迷其中,这对培养一个健康的心态是非常不利,过分沉迷此类游戏必将对身心带来损害。

杀手说:杀手们通常丝豪不掩饰自己对杀人吧的狂热,大部分人都是“一玩就爱上了。这种感觉可能就像吸鸦片。”杀手吴新说:“我知道这样对工作和身体都不好,但就是欲罢不能。”

关键词:过瘾

社会学家仇立平认为,在杀人游戏的过程中,玩家需要根据不同角色或自我辩白或诬陷他人,它让人们有机会在虚拟的游戏世界里扮演“杀手”,过上一把坏人的瘾。

杀手说:徐小姐坦言“喜欢做杀手的感觉,可以主宰其他人的命运,然而,在现实中这是不可能的。”也有人认为,游戏就是游戏,这种模式在现实生活不具备可移植性。“如果像讨伐小学生玩电游一样,批判这个游戏群体,无异于把高理性群体降低成感性人群。”

游戏是一个客观的东西,关键在于游戏者的自控能力。杀人吧受到高知识层的青睐,毕竟对社会危害性不大,存在有合理性,但是也不能排除,游戏过度会产生的心理问题,大脑长期处于兴奋状态,容易造成失衡。
也许,杀人吧的充实,正好填补了现实生活的虚无……

来源: 国际在线
“杀人游戏” 超越游戏

据说“杀人游戏”的雏形源自格林童话:很久以前,一群骑士通过玩纸牌来决定命运,胜者过关,负者葬身毒龙口中。后来,硅谷人由此创立了游戏,并把它作为一种培训工具,用来测评人的心理素质与潜能,培养团队精神。一些敏感的同行们往往只知道这游戏由“海归”们带回,却不知它正是网络人套搬国外商业模式的产物。这个游戏往往能在新员工培训和客户交往时收到奇效,因为它迅速地把陌生的人们挤压到一个封闭的圈子里,让他们休戚与共,大家能迅速熟悉,并了解每个人的个性。虽然它强大的娱乐性掩盖了工具的本质,但究其根源,我们不难理解这种对心理素质和判断力的考验,决不仅仅是在虚拟世界中“发泄”、“减压”那么简单。

“杀人游戏”的参与者面对的是一个信息残缺,虚实难辨的局面,敌友与将来都存在不可预知性,由此,参与者人性的本质和弱点也会不自觉的暴露出来。人的行为模式表现为金字塔形,而塔底则是主导行为的心理动机。据此我们可以把参与游戏者分为这几种类型:

权力型:力图保持权威,充当意见领袖者;

协作型,缺乏主见,追随意见领袖;

控制型:无论成功与否,只求游戏继续,乐于操盘;

成就型,把游戏当作工作,苛求成功,从中获得成就感。

当然还有一种,不擅言辞,容易紧张,往往惨遭错杀者,我们称之“无辜型”。

回头看看,人们在游戏中的表现不正与事业中的表现相符吗?现代人力资源理论认为,苛求人不断发现自己的弱点并不断克服是事业误区,人只有找到自己的核心竞争力并集中发展才不会造成资源浪费。据统计,即便美国也只有1/3受过高等教育的人能找准自己的定位,能通过简单的游戏为人生定位提供参考,游戏的意义早已超越了游戏本身。

林林总总“游戏民”

既然有“股民”、“彩民”世象百态,“游戏民”也不例外。一旦你成为“游戏民”,你就会发现,原来自己如此多疑,记者冷眼旁观了一番“游戏民”们的种种表现。

先看看我们的同行,记者们接近于SOHO一族的生活方式和定题采访的工作习惯造就了强烈的主观意识。他们玩游戏时往往先设立出假想敌,不停搜集素材佐证自己的判断,直觉往往让他们忽略了一些真实的信息。有口舌伶俐的本钱,他们还很容易成为意见领袖,这种领袖往往会误导无辜者,实战中记者就在“老陆”和“老孙”两位胖同行身上证实了这一点。

相比而言技术人员就可信得多,与机器常打交道令他们理性思维极佳,判断时很少感情色彩,“冷酷无情”,评判均衡,误差较小。另外一种IT人则全然把它当作工作,属于成就型,拼命想当法官,而当了良民往往“闹情绪”,常被当奸细“干掉”。

公司领导和下属一同玩游戏不是好事,领导往往会不自觉的成为下属们的意见领袖。尤其是对于规模不大的私企,盲从比率异常的高,而大公司则好得多,“斗争” 也会更有趣。最后给您提供一点秘技:老练的杀手虽然很冷静,少有小动作,但眼神多少会有些惶恐不安或志得意满,盯着他们的眼睛吧,成功率超过60%。

Minutes To Midnight

these days, I am enjoying from Linkin Park's new album Minutes to Midnight. from its introduction, I learn a new phrase named Doomsday Clock
, then I search the web and catch some brief intr from WikiPedia. the singer in introduction was said to be changed but I can not find, however, it is easy to chack out there are several soft songs, it is great different from former ones.



Doomsday Clock
From Wikipedia, the free encyclopedia
(Redirected from Doomsday clock)
The Doomsday Clock now stands at five minutes to midnight.The Doomsday Clock is a symbolic clockface maintained since 1947 by the Board of Directors of the Bulletin of the Atomic Scientists at the University of Chicago. It uses the analogy of the human race being at a time that is "minutes to midnight" where midnight represents destruction by nuclear war. Since its introduction, the clock has appeared on the cover of each issue of the Bulletin of the Atomic Scientists. The first representation of the clock was produced in 1947, when artist Martyl Langsdorf, the wife of physicist, Alexander Langsdorf, Jr., who worked on the Manhattan Project, was asked by magazine cofounder Hyman Goldsmith to design a cover for the June issue.

The number of minutes before midnight, a measure of the degree of nuclear, environmental, and technological threats, is updated periodically. The clock is currently set to five minutes to midnight, having been advanced by two minutes on January 17, 2007.
Time changes
The clock was started at seven minutes to midnight during the Cold War in 1947, and has subsequently been advanced or rewound at intervals, depending on the state of the world and the prospects for nuclear war. Its setting is relatively arbitrary, set by the Board of Directors at the Bulletin of the Atomic Scientists in response to global affairs. The setting of the clock has not always been fast enough to cope with the speed of global events, either; one of the closest periods to nuclear war, the Cuban Missile Crisis in 1962, reached its head and resolution in a number of weeks, and the clock either could not be changed or was not changed to reflect any of this at the time. Nevertheless, the changing of the clock usually does provoke attention.

The clock's hands have been moved 19 times in response to international events since its initial start at seven minutes to midnight in 1947:

1949 - The Soviet Union tests its first atomic bomb. Clock changed to three minutes to midnight (four minutes closer to midnight).
1953 - The United States and the Soviet Union test thermonuclear devices within nine months of one another. Clock changed to two minutes to midnight (one minute closer, its closest approach to midnight to date).
1960 - In response to a perception of increased scientific cooperation and public understanding of the dangers of nuclear weapons, clock is changed to seven minutes to midnight (five minutes further from midnight).
1963 - The United States and Soviet Union sign the Partial Test Ban Treaty, limiting atmospheric nuclear testing. Clock changed to twelve minutes to midnight (another five minutes further).
1968 - France and China acquire and test nuclear weapons (1960 and 1964 respectively), wars rage on in the Middle East, Indian subcontinent, and Vietnam. Clock changed to seven minutes to midnight (five minutes closer to midnight).
1969 - The U.S. Senate ratifies the Nuclear Non-Proliferation Treaty. Clock changed to ten minutes to midnight (three minutes further from midnight).
1972 - The United States and the Soviet Union sign the SALT I (Strategic Arms Limitation Treaty) and the Anti-Ballistic Missile Treaty. Clock changed to twelve minutes to midnight (two minutes further).
1974 - India tests a nuclear device (Smiling Buddha), SALT II talks stall. Clock changed to nine minutes to midnight (three minutes closer to midnight).
1980 - Further deadlock in US-USSR talks, increase in nationalist wars and terrorist actions. Clock changed to seven minutes to midnight (two minutes closer).
1981 - Arms race escalates, conflicts in Afghanistan, South Africa, and Poland
Cover of a 2002 Bulletin of the Atomic Scientists with the famous Doomsday Clock set at seven minutes to midnight. The clock can be seen in the "o" of Atomic in the title.add to world tension. Clock changed to four minutes to midnight (three minutes closer).
1984 - Further escalation of the arms race under the U.S. policies of Ronald Reagan. Clock changed to three minutes to midnight (one minute closer).
1988 - The U.S. and the Soviet Union sign treaty to eliminate intermediate-range nuclear forces, relations improve. Clock changed to six minutes to midnight (three minutes further from midnight).
1990 - Fall of the Berlin Wall, success of anti-communist movements in Eastern Europe, Cold War nearing an end. Clock changed to ten minutes to midnight (four minutes further).
1991 - United States and Soviet Union sign the Strategic Arms Reduction Treaty. Clock changed to seventeen minutes to midnight (seven minutes further, its greatest distance from midnight so far).
1995 - Global military spending continues at Cold War levels; concerns about post-Soviet nuclear proliferation of weapons and brainpower. Clock changed to fourteen minutes to midnight (three minutes closer to midnight).
1998 - Both India and Pakistan test nuclear weapons in a tit-for-tat show of aggression; the United States and Russia run into difficulties in further reducing stockpiles. Clock changed to nine minutes to midnight (five minutes closer).
2002 - Little progress on global nuclear disarmament; United States rejects a series of arms control treaties and announces its intentions to withdraw from the Anti-Ballistic Missile Treaty; terrorists seek to acquire nuclear weapons. Clock changed to seven minutes to midnight (two minutes closer).
2007 - North Korea’s recent test of a nuclear weapon, Iran’s nuclear ambitions, a renewed U.S. emphasis on the military utility of nuclear weapons, the failure to adequately secure nuclear materials, and the continued presence of some 26,000 nuclear weapons in the United States and Russia.[1] Experts assessing the dangers posed to civilization have added climate change to the prospect of nuclear annihilation as the greatest threats to humankind. Clock changed to five minutes to midnight (two minutes closer).
The official announcement of the most recent change to five minutes to midnight took place on January 17, 2007 at 14:30 hours GMT.


In popular culture

In fiction
The Doomsday Clock is referenced in Piers Anthony's novel, Wielding A Red Sword, in which the mythical Incarnation of War can control the position of the hands up to midnight and thereby bring about World War III.
The clock illustrations used in the Watchmen graphic novel series is a reference to The Doomsday Clock. On page 18 of issue #1, a newspaper on Adrian Veidt's desk bears the headline "Nuclear Doomsday Clock Stands At Five To Twelve, Warn Experts".
The Doomsday Clock was used in the game Empire Earth II during a United States mission, featuring a battle on the Bering Sea. The Soviet Union was provoking America to war by attacking Alaska, while the United States was doing everything possible to prevent the clock from reaching midnight.
A similar game, Rise of Nations, has an Armageddon counter that goes down with every nuclear launch. All players will receive an Armageddon ending (automatic lose) if the counter reaches zero.
In the video game Duke Nukem: Zero Hour for the Nintendo 64 the name Zero Hour refers to the Doomsday Clock.
In the book by John Bellairs, The House with a Clock in Its Walls, the mystery involves a clock that is ticking down toward doomsday.
In the comic "Stormwatch PHD". In issue #4 it is explained that the "original" clock gained magical powers, and if the hands were forcefully turned to 12, it would cause nuclear war.

In music
The Doomsday Clock is alluded to throughout "2 Minutes to Midnight", a single from Iron Maiden's album Powerslave. In the cover of the band's single, the mascot Eddie is sitting in chair, with nuclear explosion behind his back.
The song "Def. Con. One." by the band Pop Will Eat Itself includes the lyric "Ten to doomsday, moving fast... Heads up! Mind that blast. No time to sleep, it's Def. Con. One. Can't get no sleep as the ticking ticks on."
The song "Why Did I Fall For That" by The Who has the lines "Four minutes to midnight on a sunny day/Maybe if we smile the clock'll fade away/Maybe we can force the hands to just reverse/'Maybe' is a word, maybe 'maybe's' a curse... We simply believe that we'd remain intact/But history is asking why did you fall for that."
The song "Easy/Lucky/Free" by Bright Eyes contains the lyrics, "I set my watch to the atomic clock. I hear the crowd count down 'til the bomb gets dropped. I always figured there'd be time enough; I never let it get me down."
The Doomsday Clock is directly mentioned in the Ozzy Osbourne song "Thank God for the Bomb" on the album The Ultimate Sin. It is, however, cited in a manner that is inconsistent with the clock's purpose. "The face of the doomsday clock / Has launched a thousand wars / As we near the final hour / Time is the only foe we have."
Australian band Midnight Oil discuss the Doomsday Clock and the threat of nuclear war in their song "Minutes to Midnight" from the album Red Sails in the Sunset. The album cover depicted the disturbing scene of the city of Sydney after a fictional nuclear attack.
"Midnight in a Perfect World" by DJ Shadow, featuring Gift of Gab (from group Blackalicious), alludes to nuclear war and that we are "now approaching midnight", especially in the full lyrical "Gab Mix" off the Endtroducing..... reissue from 2005.
The song "Five Minutes to Midnight" by Boys Like Girls may be a reference to the Doomsday Clock.
On the cover of American band Alive's album 11:59, the Trinity test's rising fireball can be seen with the text "It's later than we thought..." written at the bottom.
Chaos Theory by Jumpsteady makes mention of the Doomsday Clock in the opening song "Outcha Mouth", saying "I'm the last second, sound of doomsday clock, like an open box of anthrax...".
Industrial band Funker Vogt refers heavily to the Doomsday Clock during the chorus of their track "History", a single from the album Survivor, which follows the themes of apocalyptic warfare. Specifically with the lines "The war will soon begin. It's already ten to twelve".
In the music video for "Russians" by Sting, the Doomsday Clock is represented by the clock ticking over the main doorway.
In ABC's music video "S.O.S", the Doomsday Clock was used as the main theme throughout the video.
Linkin Park's album Minutes to Midnight is said to be a reference to the Doomsday Clock.[4]
Zeitgeist, an upcoming Smashing Pumpkins album, includes a song entitled "Doomsday Clock".

In television
Gummi Bears Season 4 Episode 4 "A Knight to Remember" The ghost of a Gummi knight helps Cubbi destroy the mysterious Doomsday Clock.
Glenn Beck had a large Doomsday Clock on the set of his CNN Headline News television show, and he would occasionally adjust the time based on the news of the day.
The title of the Venture Brothers episode "Twenty Years to Midnight" is a reference to the Doomsday clock.
The eighth episode of the series Heroes is titled "Seven Minutes to Midnight", which was the time on the clock at the release of the episode. Also, the villain Sylar wears a watch that stopped at seven minutes to midnight. The series was filmed and began to air prior to the 2007 adjustment of the Doomsday clock, which until then did indeed read seven minutes to midnight.
Adult Swim's night time lineup recently gave reference to the Doomsday clock, by saying sarcastically how we now have five more minutes to do what we want till we die...giving further reference to the recent clock change to five minutes till midnight.
The Doctor Who episode "Four to Doomsday" was first aired in 1982, when the clock was at four minutes to midnight.

In games
In Magic the Gathering 4th edition, there is an artifact called Armageddon Clock that deals increasing damage to each player, speeding up the game's current outcome if left unattended.

Inner Class 嵌套式类

什么是嵌套式类?

顾名思义,Java 语言中的嵌套式类 是在另一个类中声明的类。以下是一个简单的例子:


public class EnclosingClass {
...
public class NestedClass {
...
}
}

通常,好的编程人员会在嵌套式类只在封闭类的上下文中有意义的时候定义嵌套式类。常见的一些例子如下所示:

* UI 类中的事件处理程序。
* 用于组件中的那些 UI 组件的辅助类。
* 适配器类,将某一个类的内部结构转换成其他一些用于该类的用户的形式。

可以将嵌套式类定义为 public、private 或 protected。还可以将嵌套式类定义为 final(以便保护它,使它免受更改)、abstract(意味着它不能被继承)或 static。

当在另一个类中创建 static 类时,将相应地创建一个称为嵌套式类的类。嵌套式类是在另一个类中定义的,但它可以存在于封闭类的实例之外。如果嵌套式类不是 static,那么它只能存在于封闭类的实例中,并且它有一个更适当的称呼,称为内部类。换句话说,所有内部类都是嵌套式类,但并不是所有的嵌套式类都是内部类。在您的工作中遇到的大多数嵌套式类都将是内部类,而不是只是嵌套式类。

任何嵌套式类都可以访问封闭类的所有成员,即使没有将它们声明为 private 也是如此。



定义嵌套式类

定义嵌套式类就像定义非嵌套式类那样,但这项操作是在封闭类中完成的。举一个稍微有点假的例子:在 Adult 内部定义一个 Wallet 类。尽管除了 Adult 之外,实际上还可以拥有一个 Wallet 类,但它并不总是一直有用,所以让每个 Adult 拥有一个 Wallet(或者至少有一个地方存放钱,MoneyContainer 听起来有点怪)是很有道理的。Wallet 并没有存在于 Person 之上也是有一定道理的,因为 Baby 不需要用钱包,如果 Person 上存在 Wallet,那么 Person 的所有子类都将继承它。

这里的 Wallet 将非常简单,因为只有服务器说明了嵌套式类的定义:


protected class Wallet {
protected ArrayList bills = new ArrayList();

protected void addBill(int aBill) {
bills.add(new Integer(aBill));
}

protected int getMoneyTotal() {
int total = 0;
for (Iterator i = bills.iterator(); i.hasNext(); ) {
Integer wrappedBill = (Integer) i.next();
int bill = wrappedBill.intValue();
total += bill;
}
return total;
}
}

我们将定义 Adult 中的类,如下所示:


public class Adult extends Person {
protected Wallet wallet = new Wallet();
public Adult() {
}
public void talk() {
System.out.println("Spoke.");
}
public void acceptMoney(int aBill) {
this.wallet.addBill(aBill);
}
public int moneyTotal() {
return this.wallet.getMoneyTotal();
}
protected class Wallet {
...
}
}

注意,我们添加了 acceptMoney() 来允许 Adult 接受更多的钱。(也可以随意地扩展这个例子,强迫 Adult 给出一些钱,这在现实生活中是很常见的事。)

一旦拥有了自己的嵌套式类和新的 acceptMoney() 方法,就可以使用它们,如下所示:


Adult anAdult = new Adult();
anAdult.acceptMoney(5);
System.out.println("I have this much money: " + anAdult.moneyTotal());

执行以下代码应该报告说 anAdult 的总钱数为 5。



过分简单事件的处理

Java 语言定义了一个事件处理方法,该方法包含相关的类,它允许您创建和处理自己的事件。但事件处理可能比这更简单。实际上,所有您需要的只是一些生成“事件” 的逻辑(该逻辑事实上根本不必是事件类),以及监听该事件并随后相应地给出响应的逻辑。例如,假设无论何时移动 Person,系统都会生成(或者激活)一个 MoveEvent,我们可以选择是处理这个事件,还是不处理这个事件。这要求对系统做一些更改。必须进行以下操作:

* 创建一个“应用程序”类来启动系统,并使用匿名内部类进行说明。
* 创建一个应用程序可以实现的 MotionListener,然后在监听器中处理事件。
* 添加一个监听器的 List 到 Adult 中。
* 添加一个 addMotionListener() 方法到 Adult 中,以便注册一个监听器。
* 添加一个 fireMoveEvent() 方法到 Adult中,这样就可以告诉监听器何时处理事件。
* 添加代码到应用程序中,以便创建一个 Adult 并将其注册为处理程序。

所有这些都很简单。以下是包含新的材料的 Adult:


public class Adult extends Person {
protected Wallet wallet = new Wallet();
protected ArrayList listeners = new ArrayList();
public Adult() {
}
public void move() {
super.move(); fireMoveEvent();
}
...
public void addMotionListener(MotionListener aListener) {
listeners.add(aListener);
}
protected void fireMoveEvent() {
Iterator iterator = listeners.iterator();
while(iterator.hasNext()) {
MotionListener listener = (MotionListener) iterator.next();
listener.handleMove(this);
}
}
protected class Wallet {
...
}
}

注意,我们现在要重写 move(),先调用 Person 上的 move(),然后调用 fireMoveEvent() 告诉监听器作出响应。我们还添加了一个 addMotionListener(),以便将 MotionListener 添加到监听器的运行列表中。以下是一个 MotionListener:


public interface MotionListener {
public void handleMove(Adult eventSource);
}

所有剩下要做的事就是创建应用程序类:


public class CommunityApplication implements MotionListener {
public void handleMove(Adult eventSource) {
System.out.println("This Adult moved:
" + eventSource.toString());
}
public static void main(String[] args) {
CommunityApplication application = new CommunityApplication();
Adult anAdult = new Adult();
anAdult.addMotionListener(application);
anAdult.move();
}
}

这个类实现了 MotionListener 接口,这意味着它实现了 handleMove()。在这里,我们要做的所有事情就是输出一条消息,以说明事件是何时激发的。



匿名内部类

匿名内部类允许在适当的位置定义一个类,而不用命名这个类,以便提供一些特定于上下文的行为。在用户界面中,这是一种用于处理程序的常见方法,这个主题超出了本教程的讨论范围。我们甚至可以在过于简单的事件处理示例中使用匿名内部类。

通过更改对 CommunityApplication.main() 中 addMotionListener() 的调用,可以将前面使用的例子转换成使用匿名内部类,如下所示:


anAdult.addMotionListener(new MotionListener() {
public void handleMove(Adult eventSource) {
System.out.println("This Adult moved:
" + eventSource.toString());
}
});

我们宁愿让 CommunityApplication 实现 MotionListener,也不愿意声明类型 MotionListener 的未指定(因而匿名)的内部类,并为它提供 handleMove() 的实现。事实上,MotionListener 是一个接口,而不是一个类,但是没关系,无论哪种情况都可以接受。

这个代码产生的结果与前面版本产生的结果完全相同,但它使用了一个更常见的并且人们期望使用的方法。几乎总是可以看见用匿名内部类实现的事件处理程序。



使用嵌套式类


嵌套式类可能非常有用,但它们也可能会带来一些痛苦。

当在封闭类之外定义类不那么合理的时候,可以使用嵌套式类。在这个例子中,我们可以拥有在 Adult 之外定义的 Wallet,感觉不错。但是,请设想一下 Personality 这样的类。您曾经有一个位于 Person 实例之外的类吗?没有吧,所以,将这个类定义为嵌套式类是很合理的。一条好的经验法则是:除非显然应该将类定义为嵌套式类,然后重构这个类来实现其嵌套,否则应该将该类定义为非嵌套式类。

匿名内部类是用于事件处理程序的标准方法,因此,可以将它们用于这些方面。在其他情况下,要小心使用它们。除非匿名内部类很小、很集中并且是人们惯用的,否则这些类会弄乱代码。它们还会使调试更加困难,虽然 Eclipse IDE 有助于减轻这种痛苦。通常,除了对事件处理程序使用匿名内部类,绝对不要尝试在其他情况下使用匿名内部类。