December 18, 2010

Reply: 这七个月

  
其实我应该好好享受最后一个人过的日子
me: 嗯,其实我也是。

参加不靠谱的活动
me: ok~

读不靠谱的书
me: of course, you can

穿不靠谱的衣服
me: 好吧……

学不靠谱的知识。
me: 没问题~

勾引可爱的小学弟
me: 不行!

然后再勾引学长
me: 不行!!

再勾引单身的男老师
me: 必然不行!!!

或者,只是一个人安静一会儿不去想你。
me: 嗯:)

嗯哼~

c/c++ input/ouput functions

int open(char * filename, int flags)
int open(char * filename, int flags, int mode)

include: fcntl.h
flags = bitwise | or of any of the following:
     O_RDONLY      Only read operations permitted
     O_WRONLY      Only write operations permitted
     O_RDWR        Read and Write operations both permitted
     O_NONBLOCK    Non-blocking, applies to open operation only
     O_APPEND      All writes go to end of file
     O_CREAT       Create file if it doesn't already exist
     O_TRUNC       Delete existing contents of file
     O_EXCL        Open fails if file already exists
     O_SHLOCK      Get a "shared lock" on the file
     O_EXLOCK      Get an "exclusive lock" on the file
     O_DIRECT      Try to avoid all caching of operations
     O_FSYNC       All writes immediately effective, no buffering
     O_NOFOLLOW    If file is symbolic link, open it, don't follow it
mode required if file is created, ignored otherwise.
mode specifies the protection bits, e.g. 0644 = rw-r--r--
returns <0 for error, or integer file descriptor.

int close(int fd)
include: unistd.h
fd = file descriptor as returned by open
returns <0 for error, 0 for success.

int read(int fd, void * ptr, int numbytes)
include: unistd.h
fd = file descriptor as returned by open
ptr = address in memory where data is to be stored;
      may be a pointer of any type.
numbytes = number of bytes to attempt to read
returns <0 for error, 0 for end-of-file,or number of bytes successfully read. (for a non-blocking interactive file, that may be zero).

int write(int fd, void * ptr, int numbytes)
include: unistd.h
fd = file descriptor as returned by open
ptr = address in memory where data already is;
      may be a pointer of any type.
numbytes = number of bytes to attempt to write
returns <=0 for error, or number of bytes successfully written. (for a non-blocking file, that may be less than the number attempted without any errors having occurred).

int lseek(int fd, int position, int startpoint)
include: unistd.h
Sets the file position effective for the next read or write operation.
fd = file descriptor as returned by open
position = position within file: number of bytes between startpoint and the desired position, may be negative.
startpoint = location in file that position is relative to, one of:
     SEEK_SET: Position is number of bytes from beginning of file
     SEEK_END: Position is number of bytes after end of file
     SEEK_CUR: Position is number of bytes after current position
returns <0 for error, or resulting file position relative to beginning of file. Moving beyond the end of the file is permitted; the file is extended in length only if a write occurs beyond the current end of file. Moveing before the beginning of a file is not permitted. A write operation after a move only overwrites the number of bytes actually written.

int stat(char * file, struct stat * info)
include: sys/types.h
include: sys/stat.h
Finds information about a file.
file = The name (or path) for the file.
info = A pointer to an uninitialised stat structure. Even in C++, the type must be "struct stat *" because of the name clash. Information about the file is stored in the info object.
returns <0 for error (including file does not exist), or 0  for success.
The useful fields of a stat object are as follows. All have types that behave like ints, although they may be 16, 32, or 64 bits long.
     st_size: size in bytes
     st_ino: inode number
     st_mode: protection or mode (see below)
     st_nlink: number of hard links
     st_uid: file's owner's identification number
     st_gid: file's group identification number
     st_birthtime: date and time of file creation (see below)
     st_mtime: date and time of last modification (see below)
     st_atime: date and time of last access (see below)
All times are stored as time_t values, as described here. Mode and Protection. st_mode is the logical-or of a number of bits each representing different properties. The named constants for these bits, and their values in octal are:
     S_ISUID  0004000  set user id on execution
     S_IRUSR  0000400  protection: readable by owner
     S_IWUSR  0000200  writable by owner
     S_IXUSR  0000100  executable by owner
     S_IRGRP  0000040  readable by group
     S_IWGRP  0000020  writable by group
     S_IXGRP  0000010  executable by group
     S_IROTH  0000004  readable by all
     S_IWOTH  0000002  writable by all
     S_IXOTH  0000001  executable by all
Four bits of the mode give the file type. The mask for type is S_IFMT = 0170000
if (mode & S_IFMT) is S_IFREG = 0100000,  type = perfectly ordinary file
if (mode & S_IFMT) is S_IFDIR = 0040000,  type = directory
if (mode & S_IFMT) is S_IFLNK = 0120000,  type = symbolic link
if (mode & S_IFMT) is S_IFIFO = 0010000,  type = named pipe
if (mode & S_IFMT) is S_IFSOCK = 0140000,  type = named socket

File Mode or Protection Bits

A file's mode or protection is usually specified visually by 9 characters, for example rw-r--r-- or rwxr-x--x. Each of the letters are (nearly always) 'r' for read permitted, 'w' for write permitted, or 'x' for execute permitted.

The letters always appear in groups of three. Within a group, the order is always 'rwx'. The first group of three indicate operations permitted to the owner of the file; the second group of three indicates operations permitted to other users in the same group as the owner; the third group of three indicates operations permitted to all users who can access the file.

If the file is a directory, 'x' means that files in the directory may be accessed if referred to directly by name, but wildcard substitutions ('*') and ls operations will not be permitted.

Modes are usually represented inside programs by a sequence of three octal digits. each octal digit represents one of the groups of three characters, 4 for 'r' plus 2 for 'w' plus 1 for 'x'. In C and C++ programs remember that numbers with leading zeros are always assumed to be in octal, so the mode 0751 represents rwxr-x--x.

vim setup

The configuration should be done in the file named "vimrc".

For linux os, the directory should be: /etc/vim/vimrc. For Unix, without root privilege, just as I am..., it needs to make a new file named ".vimrc" in the $HOME/ directory. As the vim starting, it will automatically read this file for configuration. And, the punctuation quotes " is the sign for comment.

" syntax highlighting
syntax on
" automatic indentation
set autoindent
" specifically c/c++ indentation
set cindent
" to show the line number for each line
set nu

Have fun:)

December 12, 2010

为什么Lisp语言如此先进?(译文)

作者: 阮一峰
日期: 2010年10月14日
上周,《黑客与画家》总算翻译完成,已经交给出版社了。
翻译完这本书,累得像生了一场大病。把书稿交出去的时候,心里空荡荡的,也不知道自己得到了什么,失去了什么。
希望这个中译本和我的努力,能得到读者认同和肯定。
下面是此书中非常棒的一篇文章,原文写于八年前,至今仍然具有启发性,作者眼光之超前令人佩服。由于我不懂Lisp语言,所以田春同学帮忙校读了一遍,纠正了一些翻译不当之处,在此表示衷心感谢。

============================

为什么Lisp语言如此先进?
作者:Paul Graham
译者:阮一峰
英文原文:Revenge of the Nerds
(节选自即将出版的《黑客与画家》中译本)

一、
如果我们把流行的编程语言,以这样的顺序排列:Java、Perl、Python、Ruby。你会发现,排在越后面的语言,越像Lisp。
Python模仿Lisp,甚至把许多Lisp黑客认为属于设计错误的功能,也一起模仿了。至于Ruby,如果回到1975年,你声称它是一种Lisp方言,没有人会反对。
编程语言现在的发展,不过刚刚赶上1958年Lisp语言的水平。

二、
1958年,John McCarthy设计了Lisp语言。我认为,当前最新潮的编程语言,只是实现了他在1958年的设想而已。
这怎么可能呢?计算机技术的发展,不是日新月异吗?1958年的技术,怎么可能超过今天的水平呢?
让我告诉你原因。
这是因为John McCarthy本来没打算把Lisp设计成编程语言,至少不是我们现在意义上的编程语言。他的原意只是想做一种理论演算,用更简洁的方式定义图灵机。
所以,为什么上个世纪50年代的编程语言,到现在还没有过时?简单说,因为这种语言本质上不是一种技术,而是数学。数学是不会过时的。你不应该把 Lisp语言与50年代的硬件联系在一起,而是应该把它与快速排序(Quicksort)算法进行类比。这种算法是1960年提出的,至今仍然是最快的通 用排序方法。

三、
Fortran语言也是上个世纪50年代出现的,并且一直使用至今。它代表了语言设计的一种完全不同的方向。Lisp是无意中从纯理论发展为编程语 言,而Fortran从一开始就是作为编程语言设计出来的。但是,今天我们把Lisp看成高级语言,而把Fortran看成一种相当低层次的语言。
1956年,Fortran刚诞生的时候,叫做Fortran I,与今天的Fortran语言差别极大。Fortran I实际上是汇编语言加上数学,在某些方面,还不如今天的汇编语言强大。比如,它不支持子程序,只有分支跳转结构(branch)。
Lisp和Fortran代表了编程语言发展的两大方向。前者的基础是数学,后者的基础是硬件架构。从那时起,这两大方向一直在互相靠拢。Lisp 刚设计出来的时候,就很强大,接下来的二十年,它提高了自己的运行速度。而那些所谓的主流语言,把更快的运行速度作为设计的出发点,然后再用超过四十年的 时间,一步步变得更强大。
直到今天,最高级的主流语言,也只是刚刚接近Lisp的水平。虽然已经很接近了,但还是没有Lisp那样强大。

四、
Lisp语言诞生的时候,就包含了9种新思想。其中一些我们今天已经习以为常,另一些则刚刚在其他高级语言中出现,至今还有2种是Lisp独有的。按照被大众接受的程度,这9种思想依次是:

1. 条件结构(即"if-then-else"结构)。现在大家都觉得这是理所当然的,但是Fortran I就没有这个结构,它只有基于底层机器指令的goto结构。
2. 函数也是一种数据类型。在Lisp语言中,函数与整数或字符串一样,也属于数据类型的一种。它有自己的字面表示形式(literal representation),能够储存在变量中,也能当作参数传递。一种数据类型应该有的功能,它都有。
3. 递归。Lisp是第一种支持递归函数的高级语言。
4. 变量的动态类型。在Lisp语言中,所有变量实际上都是指针,所指向的值有类型之分,而变量本身没有。复制变量就相当于复制指针,而不是复制它们指向的数据。
5. 垃圾回收机制。
6. 程序由表达式(expression)组成。Lisp程序是一些表达式区块的集合,每个表达式都返回一个值。这与Fortran和大多数后来的语言都截然不同,它们的程序由表达式和语句(statement)组成。
区分表达式和语句,在Fortran I中是很自然的,因为它不支持语句嵌套。所以,如果你需要用数学式子计算一个值,那就只有用表达式返回这个值,没有其他语法结构可用,因为否则就无法处理这个值。
后来,新的编程语言支持区块结构(block),这种限制当然也就不存在了。但是为时已晚,表达式和语句的区分已经根深蒂固。它从Fortran扩散到Algol语言,接着又扩散到它们两者的后继语言。
7. 符号(symbol)类型。符号实际上是一种指针,指向储存在哈希表中的字符串。所以,比较两个符号是否相等,只要看它们的指针是否一样就行了,不用逐个字符地比较。
8. 代码使用符号和常量组成的树形表示法(notation)。
9. 无论什么时候,整个语言都是可用的。Lisp并不真正区分读取期、编译期和运行期。你可以在读取期编译或运行代码;也可以在编译期读取或运行代码;还可以在运行期读取或者编译代码。
在读取期运行代码,使得用户可以重新调整(reprogram)Lisp的语法;在编译期运行代码,则是Lisp宏的工作基础;在运行期编译代码, 使得Lisp可以在Emacs这样的程序中,充当扩展语言(extension language);在运行期读取代码,使得程序之间可以用S-表达式(S-expression)通信,近来XML格式的出现使得这个概念被重新"发 明"出来了。

五、
Lisp语言刚出现的时候,它的思想与其他编程语言大相径庭。后者的设计思想主要由50年代后期的硬件决定。随着时间流逝,流行的编程语言不断更新换代,语言设计思想逐渐向Lisp靠拢。
思想1到思想5已经被广泛接受,思想6开始在主流编程语言中出现,思想7在Python语言中有所实现,不过似乎没有专用的语法。
思想8可能是最有意思的一点。它与思想9只是由于偶然原因,才成为Lisp语言的一部分,因为它们不属于John McCarthy的原始构想,是由他的学生Steve Russell自行添加的。它们从此使得Lisp看上去很古怪,但也成为了这种语言最独一无二的特点。Lisp古怪的形式,倒不是因为它的语法很古怪,而 是因为它根本没有语法,程序直接以解析树(parse tree)的形式表达出来。在其他语言中,这种形式只是经过解析在后台产生,但是Lisp直接采用它作为表达形式。它由列表构成,而列表则是Lisp的基 本数据结构。
用一门语言自己的数据结构来表达该语言,这被证明是非常强大的功能。思想8和思想9,意味着你可以写出一种能够自己编程的程序。这可能听起来很怪异,但是对于Lisp语言却是再普通不过。最常用的做法就是使用宏。
术语"宏"在Lisp语言中,与其他语言中的意思不一样。Lisp宏无所不包,它既可能是某样表达式的缩略形式,也可能是一种新语言的编译器。如果你想真正地理解Lisp语言,或者想拓宽你的编程视野,那么你必须学习宏。
就我所知,宏(采用Lisp语言的定义)目前仍然是Lisp独有的。一个原因是为了使用宏,你大概不得不让你的语言看上去像Lisp一样古怪。另一 个可能的原因是,如果你想为自己的语言添上这种终极武器,你从此就不能声称自己发明了新语言,只能说发明了一种Lisp的新方言。
我把这件事当作笑话说出来,但是事实就是如此。如果你创造了一种新语言,其中有car、cdr、cons、quote、cond、atom、eq这 样的功能,还有一种把函数写成列表的表示方法,那么在它们的基础上,你完全可以推导出Lisp语言的所有其他部分。事实上,Lisp语言就是这样定义 的,John McCarthy把语言设计成这个样子,就是为了让这种推导成为可能。


六、
就算Lisp确实代表了目前主流编程语言不断靠近的一个方向,这是否意味着你就应该用它编程呢?
如果使用一种不那么强大的语言,你又会有多少损失呢?有时不采用最尖端的技术,不也是一种明智的选择吗?这么多人使用主流编程语言,这本身不也说明那些语言有可取之处吗?
另一方面,选择哪一种编程语言,许多项目是无所谓的,反正不同的语言都能完成工作。一般来说,条件越苛刻的项目,强大的编程语言就越能发挥作用。但 是,无数的项目根本没有苛刻条件的限制。大多数的编程任务,可能只要写一些很小的程序,然后用胶水语言把这些小程序连起来就行了。你可以用自己熟悉的编程 语言,或者用对于特定项目来说有着最强大函数库的语言,来写这些小程序。如果你只是需要在Windows应用程序之间传递数据,使用Visual Basic照样能达到目的。
那么,Lisp的编程优势体现在哪里呢?

七、
语言的编程能力越强大,写出来的程序就越短(当然不是指字符数量,而是指独立的语法单位)。
代码的数量很重要,因为开发一个程序耗费的时间,主要取决于程序的长度。如果同一个软件,一种语言写出来的代码比另一种语言长三倍,这意味着你开发 它耗费的时间也会多三倍。而且即使你多雇佣人手,也无助于减少开发时间,因为当团队规模超过某个门槛时,再增加人手只会带来净损失。Fred Brooks在他的名著《人月神话》(The Mythical Man-Month)中,描述了这种现象,我的所见所闻印证了他的说法。
如果使用Lisp语言,能让程序变得多短?以Lisp和C的比较为例,我听到的大多数说法是C代码的长度是Lisp的7倍到10倍。但是最 近,New Architect杂志上有一篇介绍ITA软件公司的文章,里面说"一行Lisp代码相当于20行C代码",因为此文都是引用ITA总裁的话,所以我想这 个数字来自ITA的编程实践。 如果真是这样,那么我们可以相信这句话。ITA的软件,不仅使用Lisp语言,还同时大量使用C和C++,所以这是他们的经验谈。
根据上面的这个数字,如果你与ITA竞争,而且你使用C语言开发软件,那么ITA的开发速度将比你快20倍。如果你需要一年时间实现某个功能,它只需要不到三星期。反过来说,如果某个新功能,它开发了三个月,那么你需要五年才能做出来。
你知道吗?上面的对比,还只是考虑到最好的情况。当我们只比较代码数量的时候,言下之意就是假设使用功能较弱的语言,也能开发出同样的软件。但是事 实上,程序员使用某种语言能做到的事情,是有极限的。如果你想用一种低层次的语言,解决一个很难的问题,那么你将会面临各种情况极其复杂、乃至想不清楚的 窘境。
所以,当我说假定你与ITA竞争,你用五年时间做出的东西,ITA在Lisp语言的帮助下只用三个月就完成了,我指的五年还是一切顺利、没有犯错误、也没有遇到太大麻烦的五年。事实上,按照大多数公司的实际情况,计划中五年完成的项目,很可能永远都不会完成。
我承认,上面的例子太极端。ITA似乎有一批非常聪明的黑客,而C语言又是一种很低层次的语言。但是,在一个高度竞争的市场中,即使开发速度只相差两三倍,也足以使得你永远处在落后的位置。
附录:编程能力
为了解释我所说的语言编程能力不一样,请考虑下面的问题。我们需要写一个函数,它能够生成累加器,即这个函数接受一个参数n,然后返回另一个函数,后者接受参数i,然后返回n增加(increment)了i后的值。
Common Lisp的写法如下:
(defun foo (n)
(lambda (i) (incf n i)))
Ruby的写法几乎完全相同:
def foo (n)
lambda {|i| n += i } end
Perl 5的写法则是:
sub foo {
my ($n) = @_;
sub {$n += shift}
}
这比Lisp和Ruby的版本,有更多的语法元素,因为在Perl语言中,你不得不手工提取参数。
Smalltalk的写法稍微比Lisp和Ruby的长一点:
foo: n
|s|
s := n.
^[:i| s := s+i. ]
因为在Smalltalk中,局部变量(lexical variable)是有效的,但是你无法给一个参数赋值,因此不得不设置了一个新变量,接受累加后的值。
Javascript的写法也比Lisp和Ruby稍微长一点,因为Javascript依然区分语句和表达式,所以你需要明确指定return语句,来返回一个值:
function foo (n) {
return function (i) {
return n += i } }
(实事求是地说,Perl也保留了语句和表达式的区别,但是使用了典型的Perl方式处理,使你可以省略return。)
如果想把Lisp/Ruby/Perl/Smalltalk/Javascript的版本改成Python,你会遇到一些限制。因为Python并 不完全支持局部变量,你不得不创造一种数据结构,来接受n的值。而且尽管Python确实支持函数数据类型,但是没有一种字面量的表示方式 (literal representation)可以生成函数(除非函数体只有一个表达式),所以你需要创造一个命名函数,把它返回。最后的写法如下:
def foo (n):
s = [n]
def bar (i):
s[0] += i
return s[0]
return bar
Python用户完全可以合理地质疑,为什么不能写成下面这样:
def foo (n):
return lambda i: return n += i
或者:
def foo (n):
lambda i: n += i
我猜想,Python有一天会支持这样的写法。(如果你不想等到Python慢慢进化到更像Lisp,你总是可以直接......)
在面向对象编程的语言中,你能够在有限程度上模拟一个闭包(即一个函数,通过它可以引用由包含这个函数的代码所定义的变量)。你定义一个类 (class),里面有一个方法和一个属性,用于替换封闭作用域(enclosing scope)中的所有变量。这有点类似于让程序员自己做代码分析,本来这应该是由支持局部作用域的编译器完成的。如果有多个函数,同时指向相同的变量,那 么这种方法就会失效,但是在这个简单的例子中,它已经足够了。
Python高手看来也同意,这是解决这个问题的比较好的方法,写法如下:
def foo (n):
class acc:
def _ _init_ _ (self, s):
self.s = s
def inc (self, i):
self.s += i
return self.s
return acc (n).inc
或者
class foo:
def _ _init_ _ (self, n):
self.n = n
def _ _call_ _ (self, i):
self.n += i
return self.n
我添加这一段,原因是想避免Python爱好者说我误解这种语言。但是,在我看来,这两种写法好像都比第一个版本更复杂。你实际上就是在做同样的 事,只不过划出了一个独立的区域,保存累加器函数,区别只是保存在对象的一个属性中,而不是保存在列表(list)的头(head)中。使用这些特殊的内 部属性名(尤其是__call__),看上去并不像常规的解法,更像是一种破解。
在Perl和Python的较量中,Python黑客的观点似乎是认为Python比Perl更优雅,但是这个例子表明,最终来说,编程能力决定了优雅。Perl的写法更简单(包含更少的语法元素),尽管它的语法有一点丑陋。
其他语言怎么样?前文曾经提到过Fortran、C、C++、Java和Visual Basic,看上去使用它们,根本无法解决这个问题。Ken Anderson说,Java只能写出一个近似的解法:
public interface Inttoint {
public int call (int i);
}
public static Inttoint foo (final int n) {
return new Inttoint () {
int s = n;
public int call (int i) {
s = s + i;
return s;
}};
}
这种写法不符合题目要求,因为它只对整数有效。
当然,我说使用其他语言无法解决这个问题,这句话并不完全正确。所有这些语言都是图灵等价的,这意味着严格地说,你能使用它们之中的任何一种语言, 写出任何一个程序。那么,怎样才能做到这一点呢?就这个小小的例子而言,你可以使用这些不那么强大的语言,写一个Lisp解释器就行了。
这样做听上去好像开玩笑,但是在大型编程项目中,却不同程度地广泛存在。因此,有人把它总结出来,起名为"格林斯潘第十定律"(Greenspun's Tenth Rule):
"任何C或Fortran程序复杂到一定程度之后,都会包含一个临时开发的、只有一半功能的、不完全符合规格的、到处都是bug的、运行速度很慢的Common Lisp实现。"
如果你想解决一个困难的问题,关键不是你使用的语言是否强大,而是好几个因素同时发挥作用(a)使用一种强大的语言,(b)为这个难题写一个事实上 的解释器,或者(c)你自己变成这个难题的人肉编译器。在Python的例子中,这样的处理方法已经开始出现了,我们实际上就是自己写代码,模拟出编译器 实现局部变量的功能。
这种实践不仅很普遍,而且已经制度化了。举例来说,在面向对象编程的世界中,我们大量听到"模式"(pattern)这个词,我觉得那些"模式"就 是现实中的因素(c),也就是人肉编译器。 当我在自己的程序中,发现用到了模式,我觉得这就表明某个地方出错了。程序的形式,应该仅仅反映它所要解决的问题。代码中其他任何外加的形式,都是一个信 号,(至少对我来说)表明我对问题的抽象还不够深,也经常提醒我,自己正在手工完成的事情,本应该写代码,通过宏的扩展自动实现。
(完)

What are the differences between a union and a structure in C?

original webpage click


Answer

A union is a way of providing an alternate way of describing the same memory area. In this way, you could have a struct that contains a union, so that the "static", or similar portion of the data is described first, and the portion that changes is described by the union. The idea of a union could be handled in a different way by having 2 different structs defined, and making a pointer to each kind of struct. The pointer to struct "a" could be assigned to the value of a buffer, and the pointer to struct "b" could be assigned to the same buffer, but now a->somefield and b->someotherfield are both located in the same buffer. That is the idea behind a union. It gives different ways to break down the same buffer area.

Answer:

The difference between structure and union in c are: 1. union allocates the memory equal to the maximum memory required by the member of the union but structure allocates the memory equal to the total memory required by the members. 2. In union, one block is used by all the member of the union but in case of structure, each member have their own memory space

Difference in their Usage:

While structure enables us treat a number of different variables stored at different in memory , a union enables us to treat the same space in memory as a number of different variables. That is a Union offers a way for a section of memory to be treated as a variable of one type on one occasion and as a different variable of a different type on another occasion.

There is frequent rwquirement while interacting with hardware to access access a byte or group of bytes simultaneously and sometimes each byte individually. Usually union is the answer.

=======Difference With example***** Lets say a structure containing an int,char and float is created and a union containing int char float are declared. struct TT{ int a; float b; char c; } Union UU{ int a; float b; char c; }

sizeof TT(struct) would be >9 bytes (compiler dependent-if int,float, char are taken as 4,4,1)

sizeof UU(Union) would be 4 bytes as supposed from above.If a variable in double exists in union then the size of union and struct would be 8 bytes and cumulative size of all variables in struct.

Detailed Example:

struct foo 
{ 
char c; 
long l; 
char *p; 
}; 

union bar 
{ 
char c; 
long l; 
char *p; 
}; 

A struct foo contains all of the elements c, l, and p. Each element is separate and distinct. 

A union bar contains only one of the elements c, l, and p at any given time. Each element is stored in the same memory location (well, they all start at the same memory location), and you can only refer to the element which was last stored. (ie: after "barptr->c = 2;" you cannot reference any of the other elements, such as "barptr->p" without invoking undefined behavior.) 

Try the following program. (Yes, I know it invokes the above-mentioned "undefined behavior", but most likely will give some sort of output on most computers.) 

========== 
#include 

struct foo 
{ 
char c; 
long l; 
char *p; 
}; 

union bar 
{ 
char c; 
long l; 
char *p; 
}; 

int main(int argc,char *argv[]) 
{ 
struct foo myfoo; 
union bar mybar; 

myfoo.c = 1; 
myfoo.l = 2L; 
myfoo.p = "This is myfoo"; 

mybar.c = 1; 
mybar.l = 2L; 
mybar.p = "This is mybar"; 

printf("myfoo: %d %ld %s\n",myfoo.c,myfoo.l,myfoo.p); 
printf("mybar: %d %ld %s\n",mybar.c,mybar.l,mybar.p); 

return 0; 
} 

========== 

On my system, I get: 

myfoo: 1 2 This is myfoo 
mybar: 100 4197476 This is mybar

December 4, 2010

140 Google Interview Questions

original site:click

Google Interview Questions: Product Marketing Manager

  • Why do you want to join Google?
  • What do you know about Google's product and technology?
  • If you are Product Manager for Google's Adwords, how do you plan to market this?
  • What would you say during an AdWords or AdSense product seminar?
  • Who are Google's competitors, and how does Google compete with them?
  • Have you ever used Google's products? Gmail?
  • What's a creative way of marketing Google's brand name and product?
  • If you are the product marketing manager for Google's Gmail product, how do you plan to market it so as to achieve 100 million customers in 6 months?
  • How much money you think Google makes daily from Gmail ads?
  • Name a piece of technology you've read about recently. Now tell me your own creative execution for an ad for that product.
  • Say an advertiser makes $0.10 every time someone clicks on their ad. Only 20% of people who visit the site click on their ad. How many people need to visit the site for the advertiser to make $20?
  • Estimate the number of students who are college seniors, attend four-year schools, and graduate with a job in the United States every year.
  • How would you boost the GMail subscription base?
  • What is the most efficient way to sort a million integers?
  • How would you re-position Google's offerings to counteract competitive threats from Microsoft?
  • How many golf balls can fit in a school bus?
  • You are shrunk to the height of a nickel and your mass is proportionally reduced so as to maintain your original density. You are then thrown into an empty glass blender. The blades will start moving in 60 seconds. What do you do?
  • How much should you charge to wash all the windows in Seattle?
  • How would you find out if a machine's stack grows up or down in memory?
  • Explain a database in three sentences to your eight-year-old nephew.
  • How many times a day does a clock's hands overlap?
  • You have to get from point A to point B. You don't know if you can get there. What would you do?
  • Imagine you have a closet full of shirts. It's very hard to find a shirt. So what can you do to organize your shirts for easy retrieval?
  • Every man in a village of 100 married couples has cheated on his wife. Every wife in the village instantly knows when a man other than her husband has cheated, but does not know when her own husband has. The village has a law that does not allow for adultery. Any wife who can prove that her husband is unfaithful must kill him that very day. The women of the village would never disobey this law. One day, the queen of the village visits and announces that at least one husband has been unfaithful. What happens?
  • In a country in which people only want boys, every family continues to have children until they have a boy. If they have a girl, they have another child. If they have a boy, they stop. What is the proportion of boys to girls in the country?
  • If the probability of observing a car in 30 minutes on a highway is 0.95, what is the probability of observing a car in 10 minutes (assuming constant default probability)?
  • If you look at a clock and the time is 3:15, what is the angle between the hour and the minute hands? (The answer to this is not zero!)
  • Four people need to cross a rickety rope bridge to get back to their camp at night. Unfortunately, they only have one flashlight and it only has enough light left for seventeen minutes. The bridge is too dangerous to cross without a flashlight, and it's only strong enough to support two people at any given time. Each of the campers walks at a different speed. One can cross the bridge in 1 minute, another in 2 minutes, the third in 5 minutes, and the slow poke takes 10 minutes to cross. How do the campers make it across in 17 minutes?
  • You are at a party with a friend and 10 people are present including you and the friend. your friend makes you a wager that for every person you find that has the same birthday as you, you get $1; for every person he finds that does not have the same birthday as you, he gets $2. would you accept the wager?
  • How many piano tuners are there in the entire world?
  • You have eight balls all of the same size. 7 of them weigh the same, and one of them weighs slightly more. How can you find the ball that is heavier by using a balance and only two weighings?
  • You have five pirates, ranked from 5 to 1 in descending order. The top pirate has the right to propose how 100 gold coins should be divided among them. But the others get to vote on his plan, and if fewer than half agree with him, he gets killed. How should he allocate the gold in order to maximize his share but live to enjoy it? (Hint: One pirate ends up with 98 percent of the gold.)
  • You are given 2 eggs. You have access to a 100-story building. Eggs can be very hard or very fragile means it may break if dropped from the first floor or may not even break if dropped from 100th floor. Both eggs are identical. You need to figure out the highest floor of a 100-story building an egg can be dropped without breaking. The question is how many drops you need to make. You are allowed to break 2 eggs in the process.
  • Describe a technical problem you had and how you solved it.
  • How would you design a simple search engine?
  • Design an evacuation plan for San Francisco.
  • There's a latency problem in South Africa. Diagnose it.
  • What are three long term challenges facing Google?
  • Name three non-Google websites that you visit often and like. What do you like about the user interface and design? Choose one of the three sites and comment on what new feature or project you would work on. How would you design it?
  • If there is only one elevator in the building, how would you change the design? How about if there are only two elevators in the building?
  • How many vacuum's are made per year in USA?
  • Why are manhole covers round?
  • What is the difference between a mutex and a semaphore? Which one would you use to protect access to an increment operation?
  • A man pushed his car to a hotel and lost his fortune. What happened?
  • Explain the significance of "dead beef".
  • Write a C program which measures the the speed of a context switch on a UNIX/Linux system.
  • Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.
  • Describe the algorithm for a depth-first graph traversal.
  • Design a class library for writing card games.
  • You need to check that your friend, Bob, has your correct phone number, but you cannot ask him directly. You must write a the question on a card which and give it to Eve who will take the card to Bob and return the answer to you. What must you write on the card, besides the question, to ensure Bob can encode the message so that Eve cannot read your phone number?
  • How are cookies passed in the HTTP protocol?
  • Design the SQL database tables for a car rental database.
  • Write a regular expression which matches a email address.
  • Write a function f(a, b) which takes two character string arguments and returns a string containing only the characters found in both strings in the order of a. Write a version which is order N-squared and one which is order N.
  • You are given a the source to a application which is crashing when run. After running it 10 times in a debugger, you find it never crashes in the same place. The application is single threaded, and uses only the C standard library. What programming errors could be causing this crash? How would you test each one?
  • Explain how congestion control works in the TCP protocol.
  • In Java, what is the difference between final, finally, and finalize?
  • What is multithreaded programming? What is a deadlock?
  • Write a function (with helper functions if needed) called to Excel that takes an excel column value (A,B,C,D…AA,AB,AC,… AAA..) and returns a corresponding integer value (A=1,B=2,… AA=26..).
  • You have a stream of infinite queries (ie: real time Google search queries that people are entering). Describe how you would go about finding a good estimate of 1000 samples from this never ending set of data and then write code for it.
  • Tree search algorithms. Write BFS and DFS code, explain run time and space requirements. Modify the code to handle trees with weighted edges and loops with BFS and DFS, make the code print out path to goal state.
  • You are given a list of numbers. When you reach the end of the list you will come back to the beginning of the list (a circular list). Write the most efficient algorithm to find the minimum # in this list. Find any given # in the list. The numbers in the list are always increasing but you don't know where the circular list begins, ie: 38, 40, 55, 89, 6, 13, 20, 23, 36.
  • Describe the data structure that is used to manage memory. (stack)
  • What's the difference between local and global variables?
  • If you have 1 million integers, how would you sort them efficiently? (modify a specific sorting algorithm to solve this)
  • In Java, what is the difference between static, final, and const. (if you don't know Java they will ask something similar for C or C++).
  • Talk about your class projects or work projects (pick something easy)… then describe how you could make them more efficient (in terms of algorithms).
  • Suppose you have an NxN matrix of positive and negative integers. Write some code that finds the sub-matrix with the maximum sum of its elements.
  • Write some code to reverse a string.
  • Implement division (without using the divide operator, obviously).
  • Write some code to find all permutations of the letters in a particular string.
  • What method would you use to look up a word in a dictionary?
  • Imagine you have a closet full of shirts. It's very hard to find a shirt. So what can you do to organize your shirts for easy retrieval?
  • You have eight balls all of the same size. 7 of them weigh the same, and one of them weighs slightly more. How can you fine the ball that is heavier by using a balance and only two weighings?
  • What is the C-language command for opening a connection with a foreign host over the internet?
  • Design and describe a system/application that will most efficiently produce a report of the top 1 million Google search requests. These are the particulars: 1) You are given 12 servers to work with. They are all dual-processor machines with 4Gb of RAM, 4x400GB hard drives and networked together.(Basically, nothing more than high-end PC's) 2) The log data has already been cleaned for you. It consists of 100 Billion log lines, broken down into 12 320 GB files of 40-byte search terms per line. 3) You can use only custom written applications or available free open-source software.
  • There is an array A[N] of N numbers. You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1] will be multiplication of A[0] and from A[2] to A[N-1]. Solve it without division operator and in O(n).
  • There is a linked list of numbers of length N. N is very large and you don't know N. You have to write a function that will return k random numbers from the list. Numbers should be completely random. Hint: 1. Use random function rand() (returns a number between 0 and 1) and irand() (return either 0 or 1) 2. It should be done in O(n).
  • Find or determine non existence of a number in a sorted list of N numbers where the numbers range over M, M>> N and N large enough to span multiple disks. Algorithm to beat O(log n) bonus points for constant time algorithm.
  • You are given a game of Tic Tac Toe. You have to write a function in which you pass the whole game and name of a player. The function will return whether the player has won the game or not. First you to decide which data structure you will use for the game. You need to tell the algorithm first and then need to write the code. Note: Some position may be blank in the game। So your data structure should consider this condition also.
  • You are given an array [a1 To an] and we have to construct another array [b1 To bn] where bi = a1*a2*...*an/ai. you are allowed to use only constant space and the time complexity is O(n). No divisions are allowed.
  • How do you put a Binary Search Tree in an array in a efficient manner. Hint :: If the node is stored at the ith position and its children are at 2i and 2i+1(I mean level order wise)Its not the most efficient way.
  • How do you find out the fifth maximum element in an Binary Search Tree in efficient manner. Note: You should not use use any extra space. i.e sorting Binary Search Tree and storing the results in an array and listing out the fifth element.
  • Given a Data Structure having first n integers and next n chars. A = i1 i2 i3 ... iN c1 c2 c3 ... cN.Write an in-place algorithm to rearrange the elements of the array ass A = i1 c1 i2 c2 ... in cn
  • Given two sequences of items, find the items whose absolute number increases or decreases the most when comparing one sequence with the other by reading the sequence only once.
  • Given That One of the strings is very very long , and the other one could be of various sizes. Windowing will result in O(N+M) solution but could it be better? May be NlogM or even better?
  • How many lines can be drawn in a 2D plane such that they are equidistant from 3 non-collinear points?
  • Let's say you have to construct Google maps from scratch and guide a person standing on Gateway of India (Mumbai) to India Gate(Delhi). How do you do the same?
  • Given that you have one string of length N and M small strings of length L. How do you efficiently find the occurrence of each small string in the larger one?
  • Given a binary tree, programmatically you need to prove it is a binary search tree.
  • You are given a small sorted list of numbers, and a very very long sorted list of numbers - so long that it had to be put on a disk in different blocks. How would you find those short list numbers in the bigger one?
  • Suppose you have given N companies, and we want to eventually merge them into one big company. How many ways are theres to merge?
  • Given a file of 4 billion 32-bit integers, how to find one that appears at least twice?
  • Write a program for displaying the ten most frequent words in a file such that your program should be efficient in all complexity measures.
  • Design a stack. We want to push, pop, and also, retrieve the minimum element in constant time.
  • Given a set of coin denominators, find the minimum number of coins to give a certain amount of change.
  • Given an array, i) find the longest continuous increasing subsequence. ii) find the longest increasing subsequence.
  • Suppose we have N companies, and we want to eventually merge them into one big company. How many ways are there to merge?
  • Write a function to find the middle node of a single link list.
  • Given two binary trees, write a compare function to check if they are equal or not. Being equal means that they have the same value and same structure.
  • Implement put/get methods of a fixed size cache with LRU replacement algorithm.
  • You are given with three sorted arrays ( in ascending order), you are required to find a triplet ( one element from each array) such that distance is minimum.
  • Distance is defined like this : If a[i], b[j] and c[k] are three elements then distance=max(abs(a[i]-b[j]),abs(a[i]-c[k]),abs(b[j]-c[k]))" Please give a solution in O(n) time complexity
  • How does C++ deal with constructors and deconstructors of a class and its child class?
  • Write a function that flips the bits inside a byte (either in C++ or Java). Write an algorithm that take a list of n words, and an integer m, and retrieves the mth most frequent word in that list.
  • What's 2 to the power of 64?
  • Given that you have one string of length N and M small strings of length L. How do you efficiently find the occurrence of each small string in the larger one?
  • How do you find out the fifth maximum element in an Binary Search Tree in efficient manner.
  • Suppose we have N companies, and we want to eventually merge them into one big company. How many ways are there to merge?
  • There is linked list of millions of node and you do not know the length of it. Write a function which will return a random number from the list.
  • You need to check that your friend, Bob, has your correct phone number, but you cannot ask him directly. You must write a the question on a card which and give it to Eve who will take the card to Bob and return the answer to you. What must you write on the card, besides the question, to ensure Bob can encode the message so that Eve cannot read your phone number?
  • How long it would take to sort 1 trillion numbers? Come up with a good estimate.
  • Order the functions in order of their asymptotic performance: 1) 2^n 2) n^100 3) n! 4) n^n
  • There are some data represented by(x,y,z). Now we want to find the Kth least data. We say (x1, y1, z1) > (x2, y2, z2) when value(x1, y1, z1) > value(x2, y2, z2) where value(x,y,z) = (2^x)*(3^y)*(5^z). Now we can not get it by calculating value(x,y,z) or through other indirect calculations as lg(value(x,y,z)). How to solve it?
  • How many degrees are there in the angle between the hour and minute hands of a clock when the time is a quarter past three?
  • Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. Do this in sub-linear time. I.e. do not just go through each element searching for that element.
  • Given two linked lists, return the intersection of the two lists: i.e. return a list containing only the elements that occur in both of the input lists.
  • What's the difference between a hashtable and a hashmap?
  • If a person dials a sequence of numbers on the telephone, what possible words/strings can be formed from the letters associated with those numbers?
  • How would you reverse the image on an n by n matrix where each pixel is represented by a bit?
  • Create a fast cached storage mechanism that, given a limitation on the amount of cache memory, will ensure that only the least recently used items are discarded when the cache memory is reached when inserting a new item. It supports 2 functions: String get(T t) and void put(String k, T t).
  • Create a cost model that allows Google to make purchasing decisions on to compare the cost of purchasing more RAM memory for their servers vs. buying more disk space.
  • Design an algorithm to play a game of Frogger and then code the solution. The object of the game is to direct a frog to avoid cars while crossing a busy road. You may represent a road lane via an array. Generalize the solution for an N-lane road.
  • What sort would you use if you had a large data set on disk and a small amount of ram to work with?
  • What sort would you use if you required tight max time bounds and wanted highly regular performance.
  • How would you store 1 million phone numbers?
  • Design a 2D dungeon crawling game. It must allow for various items in the maze - walls, objects, and computer-controlled characters. (The focus was on the class structures, and how to optimize the experience for the user as s/he travels through the dungeon.)
  • What is the size of the C structure below on a 32-bit system? On a 64-bit?
struct foo {
char a;
char* b;
};

  • Efficiently implement 3 stacks in a single array.
  • Given an array of integers which is circularly sorted, how do you find a given integer.
  • Write a program to find depth of binary search tree without using recursion.
  • Find the maximum rectangle (in terms of area) under a histogram in linear time.
  • Most phones now have full keyboards. Before there there three letters mapped to a number button. Describe how you would go about implementing spelling and word suggestions as people type.
  • Describe recursive mergesort and its runtime. Write an iterative version in C++/Java/Python.
  • How would you determine if someone has won a game of tic-tac-toe on a board of any size?
  • Given an array of numbers, replace each number with the product of all the numbers in the array except the number itself *without* using division.
  • Create a cache with fast look up that only stores the N most recently accessed items.
  • How to design a search engine? If each document contains a set of keywords, and is associated with a numeric attribute, how to build indices?
  • Given two files that has list of words (one per line), write a program to show the intersection.
  • What kind of data structure would you use to index annagrams of words? e.g. if there exists the word "top" in the database, the query for "pot" should list that.
  • What is the yearly standard deviation of a stock given the monthly standard deviation?
  • How many resumes does Google receive each year for software engineering?
  • Anywhere in the world, where would you open up a new Google office and how would you figure out compensation for all the employees at this new office?
  • What is the probability of breaking a stick into 3 pieces and forming a triangle?
  • You're the captain of a pirate ship, and your crew gets to vote on how the gold is divided up. If fewer than half of the pirates agree with you, you die. How do you recommend apportioning the gold in such a way that you get a good share of the booty, but still survive?
  • How would you work with an advertiser who was not seeing the benefits of the AdWords relationship due to poor conversions?
  • How would you deal with an angry or frustrated advertisers on the phone?
Sources

Programmer Competency Matrix

here

it really does not matter for choosing among languages

the original webpage: click

Lisp被许多资深程序员视为编程语言中的圣杯,因为学起来很难。著名程序员、最热门的技术问答网站StackOverflow创始人Joel Spolsky曾经在"Java语言学校的危险性"一 文中说,自己当年在大学里学习用Lisp的导论课程也是苦不堪言,而Lisp这样的函数式语言实际开发中并不常用,但是一旦到了体现优势的时候,你如果不 懂,将失之千里。他还认为,Google的核心技术之一MapReduce就来自函数式语言,而且使Google领先微软多年。请注意,Spolsky曾 经1990年代微软的Excel项目经理,VBA的主要创造者。

《Unix编程艺术》的作者Eric Raymond也在"如何成为黑客"(英文版)中说过,Lisp是对黑客特别重要的语言,"掌握了之后,你会得到丰富的启迪和经验。 即使实际上很少使用Lisp,这些经验也会使你在以后的日子里成为更好的程序员。"

而Paul Graham更是Lisp的头号吹鼓手,他曾与蠕虫病毒发明者Robert Morris一起,成功地用Lisp开发历史上第一个Web应用――ViaWeb,并高价卖给Yahoo致富。他在2001年写了一篇宣传Lisp的名文"Beating the Averages"(英文),其中说到:"Lisp之所以极为优秀,并不是因为只有铁杆粉丝才知道的某些魔术般的性质,而在于它确实是最强大的编程语言。大家不用它的原因,在于编程语言不只是技术,而且也是思维习惯,这是改变起来最慢的东西。"

有意思的是,美国时间10月18日,著名技术新闻网站Hacker News上,名为kung-fu-master的用户发了一篇名为"问PG: Lisp与Python (2010)"的帖子,内容很简单:"好像许多Lisp老枪都开始转而用Python的(比如Peter Norvig)。今天你怎么看Lisp与Python?"

这里的PG就是指Hacker News的创始人、著名Lisp程序员与吹鼓手Paul Graham。而其中提到的Peter Norvig则是另一个著名Lisp程序员,现任Google研发总监。他有一篇经典的文章"十年学会编程"(英文版),相信大家都已经看过,他的首选推荐语言当然也是Lisp(更准确的说是Lisp的方言Scheme)。

面对这样直接的问题,专家们是怎么回答的呢?
Paul Graham说:
这问题好像来自2005年而不是2010年。Lisp现在由于Clojure(Lisp的现代方言,可以运行在JVM和.NET上――CSDN编者注)的出现,已经又变得时髦了。当然Python也有很好的库,但是我觉得用缺乏宏的语言编程很受局限。

许多网友对Python没有宏的问题进行了讨论。有人说不支持宏是出于代码可读性的考虑。而更多的人则认同宏是一种抽象工具,任何工具都会被误用、滥用,但并不表示工具本身有问题。

另一Lisp专家,《Coder at Work》和《Practical Common Lisp》作者>Peter Seibel也加入了讨论(他最近忙于编辑一种杂志Code Quarterly)。他说:自己与Peter Norvig有类似的体验。虽然自己Lisp非常熟练,但是在表达算法方面Python是最佳选择。不过,相比Lisp实现,CPython的运行速度慢得惊人,甚至差5-10倍。

而Peter Norvig也罕见地现出真身,给出了自己的回答,内容一如既往地经典:
我 是Peter Norvig。我转向Python不是因为它比Lisp更好、更令人满意、更实用,而是因为它用作伪代码更合适。许多学生说,在《人工智 能》(Norvig与Russell合著的经典教材)一书中的伪代码与我们在网上提供的Lisp代码之间进行转换太难了。于是我要寻找一种更近似伪代码的 语言,发现Python是最合适的。然后我就自学了Python,熟练到足以实现教材中示例的地步。我发现Python对于一些类型的小问题非常合适,有 些库也是我与其他的一些代码(包括在Google内和网上其他地方的代码)集成非常需要的。 我认为Lisp对更大的项目和编译速度很重要的应用而言仍然具有优势。但是在主要目的是交流而非编程的时候(比如针对数量众多的学生),Python更有 优势。

就更一般意义上的编程而言,在Google和其他地方,我认为语言的选择并不如其他方面的选择那么重要:如果你有了正确的总体架构、正确的程序员团队、正确的开发过程(能够快速开发、持续改善),那么很多语言都能胜任;但如果以上的东西你没有,那无论选择什么语言,你都会陷入一团糟。

还有人找出今年2月Norvig在一次采访(无法直接访问)中类似的话,透露了Google内部的一些信息:
(1) Google最开始似乎核心程序员都是用C++的,效率很高。这部分形成了公司的文化。
(2) Google早期的Lisp程序员(Erann Gat) 注意到其他程序员和自己的效率差不多,甚至更好。关键还是在人,与20年前相比,现在语言的选择不那么重要了。
(3) Lisp是为单个程序员或者一小组程序员进行探索性工作而专门设计的……如果我想自己在周末修改代码,会更愿意用Lisp,但是如果有几百个程序员一起改代码,那就不是编程语言的问题,而是社会问题了。
(4) 库。

其他人举出的材料中,最有意思的应该来自Lisp之父、计算机科学巨人约翰麦卡锡。这篇博客(无法直接访问)里生动讲述了这位图灵奖得主在某次听Peter Norvig改而鼓吹Python的演讲后的情景:
Norvig 演讲后,进入提问环节。出乎我的意料,他点了一位皱巴巴的老头。老头的胡子和头发都花白了,而且乱糟糟的,看上去像是来此参观但是迷路了,到这里来休息一 下,好奇地听听我们在说什么。我第一个念头是,估计他已经被这么艰深的话题弄晕了。但是马上想到,不对啊,这里离斯坦福很近,这老头的年纪也对,难道 是……
只听Norvig说:"是,John,你有什么问题?"我记不清Lisp之父当时怎么问的了,但不超过十 个词,就是问Python是否能如Lisp那样优雅地像数据一样处理代码。"不,John,不行。"Norvig回答,然后静等麦卡锡继续发问。但是,老 人什么也没有再说。此时真是无言胜千语啊……

看来,在大师眼中,数据与代码等同处理是最重要的语言特性之一。他还曾经在访谈中这样评价Ruby(提问者说Ruby从Lisp中借鉴了很多):"Ruby能像数据那样使用列表结构吗?那每次算加和减的时候,都得进行解析?这方面Ruby还不如1960年的Lisp。"

November 19, 2010

coding advices

After decades of programming I do not even think about these three ways to read code. I just glance at it and know what it means, and I can even glance at a whole screen of code, and all the bugs and errors jump out at me. That took an incredibly long time and quite a bit more study than is sane. To get that way, I learned these three ways of reading most any programming language:

1. Front to back.
2. Back to front.
3. Counter-clock-wise.

Try them out when you have a difficult statement to figure out. When you type the next block of your code, go over it in these ways. This one is gonna be fun.

......

I am warning you, this will be frustrating. In the business we call this "yak shaving". Yak shaving is any activity that is mind numblingly irritatingly boring and tedious that you have to do before you can do something else that's more fun. You want to create cool Python projects, but you can't do that until you setup a skeleton directory, but you can't setup a skeleton directory until you install some packages, but you can't install pacakages until you install package installers, and you can't install package installers until you figure out how your system installs software in general, and so on.

Struggle through this anyway. Consider it your trial-by-annoyance to get into the programmer club. Every programmer has to do these annoying tedious tasks before they can do something cool.

......

What I discovered after this journey of learning is that the languages did not matter, it's what you do with them. Actually, I always knew that, but I'd get distracted by the languages and forget it periodically. Now I never forget it,
and neither should you.

Which programming language you learn and use does not matter. Do not get sucked into the religion surrounding programing languages as that will only blind you to their true purpose of being your tool for doing interesting things.

Programming as an intellectual activity is the only art form that allows you to create interactive art. You can create projects that other people can play with, and you can talk to them indirectly. No other art form is quite this  interactive. Movies flow to the audience in one direction. Paintings do not move. Code goes both ways.

Programming as a profession is only moderately interesting. It can be a good job, but if you want to make about the same money and be happier, you could actually just go run a fast food joint. You are much better off using code as
your secret weapon in another profession.

People who can code in the world of technology companies are a dime a dozen and get no respect. People who can code in biology, medicine, government, sociology, physics, history, and mathematics are respected and can do amazing things to advance those disciplines.

Of course, all of this advice is pointless. If you liked learning to write software with this book, you should try to use it to improve your life any way you can. Go out and explore this weird wonderful new intellectual pursuit that barely anyone in the last 50 years has been able to explore. Might as well enjoy it while you can.

Finally, I will say that learning to create software changes you and makes you different. Not better or worse, just different. You may find that people treat you harshly because you can create software, maybe using words like "nerd". Maybe you will find that because you can dissect their logic that they hate arguing with you. You may even find that simply knowing how a computer works makes you annoying and weird to them.

To this I have one just piece of advice: they can go to hell. The world needs more weird people who know how things work and who love to figure it all out. When they treat you like this, just remember that this is your journey, not theirs. Being different is not a crime, and people who tell you it is are just jealous that you have picked up a skill they never in their wildest dreams could acquire.

You can code. They cannot. That is pretty damn cool.
===

***CLASS STYLE
* Your class should use “camel case” like SuperGoldFactory rather than super_gold_factory.
* Try not to do too much in your __init__ functions. It makes them harder to use.
* Your other functions should use “underscore format” so write my_awesome_hair and not myawesomehair or MyAwesomeHair.
* Be consistent in how you organize your function arguments. If your class has to deal with users, dogs, and cats, keep that order throughout unless it really doesn't make sense. If you have one function takes (dog, cat, user) and the other takes (user, cat, dog), it'll be hard to use.
* Try not to use variables that come from the module or globals. They should be fairly self-contained.
* A foolish consistency is the hobgoblin of little minds. Consistency is good, but foolishly following some idiotic mantra because everyone else does is bad style. Think for yourself.
* Always, always have class Name(object) format or else you will be in big trouble.

***CODE STYLE
* Give your code vertical space so people can read it. You will find some very bad programmers who are able to write reasonable code, but who do not add any spaces. This is bad style in any language because the human eye and brain use space and vertical alignment to scan and separate visual elements. Not having space is the same as giving your code an awesome camouflage paint job.
* If you can't read it out loud, it's probably hard to read. If you are having a problem making something easy to use, try reading it out loud. Not only does this force you to slow down and really read it, but it also helps you find difficult passages and things to change for readability.
* Try to do what other people are doing in Python until you find your own style.
* Once you find your own style, do not be a jerk about it. Working with other people's code is part of being a programmer, and other people have really bad taste. Trust me, you will probably have really bad taste too and not even realize it.
* If you find someone who writes code in a style you like, try writing something that mimics their style.

***GOOD COMMENTS
* There are programmers who will tell you that your code should be readable enough that you do not need comments. They'll then tell you in their most official sounding voice that, "Ergo you should never write comments." Those programmers are either consultants who get paid more if other people can't use their code, or incompetents who tend to never work with other people. Ignore them and write comments.
* When you write comments, describe why you are doing what you are doing. The code already says how, but why you did things the way you did is more important.
* When you write doc comments for your functions , make the comments documentation for someone who will have to use your code. You do not have to go crazy, but a nice little sentence about what someone does with that function helps a lot.
* Finally, while comments are good, too many are bad, and you have to maintain them. Keep your comments relatively short and to the point, and if you change a function, review the comment to make sure it's still correct.

some useful link for programming format

高质量C++/C编程指南

Google code: google style code (including C/C++, Javascript, and Python)

Microsoft: All-In-One Code Framework

some advices about python coding

from 《learn python the hard way》
======

Every if-statement must have an else. If this else should never be run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.

Never nest if-statements more than 2 deep and always try to do them 1 deep. This means if you put an if in an if then you should be looking to move that second if into another function.

Treat if-statements like paragraphs, where each if,elif,else grouping is like a set of sentences. Put blank lines before and after. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.

The best way to debug a program is to use print to print out the values of variables at points in the program to see where they go wrong.

Make sure parts of your programs work as you work on them. Do not write massive files of code before you try to run them. Code a little, run a little, fix a little.
======

Every if-statement must have an else. If this else should never be run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.

Never nest if-statements more than 2 deep and always try to do them 1 deep. This means if you put an if in an if then you should be looking to move that second if into another function.

Treat if-statements like paragraphs, where each if,elif,else grouping is like a set of sentences. Put blank lines before and after. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.

The best way to debug a program is to use print to print out the values of variables at points in the program to see where they go wrong.

Make sure parts of your programs work as you work on them. Do not write massive files of code before you try to run them. Code a little, run a little, fix a little.


When scrutinizing the code, pay attention on:

1. Functions and what they do.
2. Where each variable is first given a value.
3. Any variables with the same names in different parts of the program. These may be trouble later.
4. Any if-statements without else clauses. Are they right?
5. Any while-loops that might not end.
6. Finally, any parts of code that you can’t understand for whatever reason.

Top 20 Programming Lessons I've Learned in 20 Years

  1. Set a duration of how long you think it should take to solve a problem - C'mon, admit it! I'm just as guilty as the next programmer. I've seen programmers sit in front of a monitor for eight hours at a time trying to solve a particular problem. Set a time table for yourself of 1 hour, 30 minutes, or even 15 minutes. If you can't figure out a solution to your problem within your time frame, ask for help or research your problem on the Internet instead of trying to be super-coder.
  2. A language is a language is a language - Over time, once you understand how one language works, you'll notice similarities between other languages. The language you choose should provide you with a suitable "comfort" level, the ability to produce efficient (and clean) code, and, above all, allow the language to suit the project and vice-versa.
  3. Don't over-"design pattern" applications - Sometimes it's just easier to write a simple algorithm than it is to incorporate a singleton or facade pattern. For the most part, it even allows for cleaner, understandable code. :-)
  4. Always backup your code - I've experienced a complete hard drive failue and lost a lot of code when I was younger and felt horrible because of what had happened. The one time you don't back up your data may be the one time where you have a strict deadline with a client and they need it tomorrow. Source code/version control applies here as well.
  5. You are not the best at programming. Live with it. - I always thought that I knew so much about programming, but there is always someone out there better than you. Always. Learn from them.
  6. Learn to learn more - With number five explained, I've always had a magazine or book in my hand about computers or programming (ask my friends, they'll confirm). True, there is a lot of technology out there and keeping up with it is a fulltime job, but if you have a smart way of receiving your news, you'll learn about new technology every single day.
  7. Change is constant - Your knowledge of technology and/or programming should be similar to how you treat stocks: Diversify. Don't get too comfortable with a particular technology. If there's not enough support for that language or technology, you might as well start updating your resume now and start your training period. My general rule of thumb that has kept me going? Know at least two or three languages, so if one dies off, you have another one to fall back on while you train for a new technology.
  8. Support Junior - Assist and train the junior/entry-level developers on good programming guidelines and techniques. You never know...you may move up in rank and you'll feel more confident having personally trained and prepared them for their next position.
  9. Simplify the algorithm - Code like a fiend, but once you're done, go back through your code and optimize it. A little code improvement here and there will make support happier in the long run.
  10. Document your code - Whether its documenting a Web Service API or documenting a simple class, document as you go. I've been accused of over-commenting my code and that's something I'm proud of. It only takes a second to add an additional comment line for each 3 lines of code. If it's a harder technique to grasp, don't be afraid to over-comment. This is one problem most architects, backup coders, and support groups don't complain about if you've done your job right.
  11. Test, Test, Test - I'm a fan of Black Box Testing. When your routine is finished, your "stamp of approval" period starts. If you have a Quality Assurance department, you may be talking more to them than your project manager regarding errors in your code. If you don't test your code thoroughly, you may develop more than code. Possibly a bad reputation.
  12. Celebrate every success - I've met a lot of programmers who have conquered headache-style problems with a great programming technique and celebrated with a fellow programmer by doing the "shake", the high-five, or even a "happy dance." Everyone has enlightening periods in their life and even though that one happy coder asked you to come and see his extraordinary piece of code and you've seen that one piece of code over 100 times in your experiences, celebrate the success of a fellow developer for the 101-st time.
  13. Have Code Reviews Frequently - On projects and personally. In the company, you will always have code reviews of how well you coded something. Don't look at it as people crucifying your coding style. Think of it as constructive criticism. On the personal front, review your code and always ask, "How could I have done it better?" This will accelerate your learning and make you a better programmer.
  14. Reminisce about your code - There are two ways to looking at old code: "I can't believe I wrote this code" and "I can't believe I wrote this code." The first statement is often of disgust and wondering how you can improve it. You'd be surprised at how old code can be resurrected into a possible and better routine, or maybe even an entire product. The second statement is of amazement and achievement. Developers have their one or two project code achievements that they completed and had everyone standing up and taking notice. Again, based on your excellent coding ability, you could take those past routines or projects and update them into a better product or idea.
  15. Humor is necessary - In my 20 years of development, I have never met a programmer who hasn't had a decent sense of humor. Actually, in this industry, it's a requirement.
  16. Beware the know-it-all, possessive coder, and the inexperienced coder - Humble yourself when you meet these types of coders. The know-it-all tries to upstage you instead of working as a team player, the defensive coder created code that he doesn't want to share with anyone, and the inexperienced coder constantly asks for assistance every ten minutes where the finished code developed is yours, not theirs.
  17. No project is ever simple - I've been asked by friends, family, and associates to just "whip something up for me." To "whip" up a program or web site, it takes planning from both parties to complete something that both sides can appreciate. If someone needs a 3-page web site with Microsoft Access from the start, it winds up becoming a 15-page web site with SQL Server, a forum, and a custom CMS (Content Management System).
  18. Never take anything for granted - If you take on a simple project, you may think that a certain section will be easy to complete. Don't think that even for a moment. Unless you have a class, component, or piece of code already coded...and has been tested thoroughly...and is in production from an existing project, don't think it will be easy.
  19. Software is never finished - A fellow programmer once told me that software is never finished, it's "temporarily completed." Sound advice. If the client is still using a program you wrote and has stood the test of time, chances are, you are still updating it, which isn't a bad thing. It keeps you working. :-)
  20. Patience is definitely a virtue - When clients, friends, or family members use a PC, they get frustrated and proceed to hit a component of the PC or storm off. I keep telling everyone, "you are controlling the computer not the other way around." You need to have a certain level of patience for programming computers. As soon as programmers understand what they did wrong, they look at it from the computers point of view and say, "Oh, that's why it was doing that."

November 10, 2010

What make code "looks" more professional?

author: Micheal Lu

这么题目看起来就比较有争议:运行起来专业的代码才专业嘛。但是从另外一个角度来说"让代码看上去比较专业"是一个积极的做法,无论对谁都没有坏处,对工程师,管理者和用户都有益无弊。

 首先这个题目说的是"看上去",所以我不会说明如何使代码真正专业。世界上有很多的书籍和文章告诉软件工程师如何写出专业的代码。如果要说"什么样的代码看上去比较专业?"那就要定义什么是专业的代码。嗯,关于这点我不能下一个准确的定义。那么可以这样,大家可以参考一些大家共认的专业代码。对于Java JDK代码来说几乎没人会否认它是专业的代码。或者一些很有影响力的open source代码,像Spring 和Apache 的代码。当然很多商业软件的代码也是很专业,但是我们看不到,或者说这不是共认的专业代码。

   * 最显而易见的做法是充足的代码注释 和标准缩进 的格式。但是大家一致认为这是最明显的因素。

   * 然后是命名规范 。有人曾经在网上展示自己的一个framework的代码,framework自然是很牛的东西。但是接下来马上有人回帖"我一看到大写开头的方法名,我就没兴趣了"。这是个很典型的例子。

       命名规范里面用拼音 做包名,类名,方法和变量名字也会使代码看上去感觉比较差。我说的是代码,不是注释。

   * 还有就是要用最新的语言特性 。对于Java,譬如要用Annotaion, Generic。虽然这些特性已经出现很多年了。至少要用@Override 一下吧。我知道大家知道用Annotaion, Generic的真正的益处。

   * 尽量不要用Magic number 。如果一看到到处都是"id".equals(...); if(i==356). ..大家就会感觉不好。

   * 还有就是最好包含单元测试 的代码,JUnit 已经成为Java的公认单元测试工具。很多开发人员认为对于一个严肃的程序,单元测试是必需的。

   * 避免冗长的方法和类。我知道大家深受其害。

 其实我认为"看上去"专业能促进代码质量。充足的代码注释和标准缩进的格式能增强可读性,另外在撰写注释的时候也是在"拷问"自己的代码,如果你觉得某个方法的注释很难写,那就要问问自己的这个方法的代码逻辑写得不够清晰。有时候在注释方法的@throws XXXException 的时候,你才会仔细考虑哪些Exception会在什么情况下被抛出。@Override 能够避免低级打字错误。Generic容器比较安全等等。

 从代码演变的角度来说,有个明显的"破窗理论"在起作用。就是越是难看的代码,在它的演化过程中会越来越差。因为当你看到你要bugfix的代码很乱,那么在bugfix的时候一般也会草草了事。一个方法有400行,在修改这个方法的时候大家不会在意再加上几十行代码。因为它看起来很差,它就是很差,我没必要美化它。反过来说,如果待改的代码很整洁很规范,那么修改者也会比较小心。这不是绝对,只是一般情况。一定有很帅的工程师把很难看的代码改得很整洁,也一定有很无畏的工程师在很好的代码上面乱改,这就是生活:)

Susan Sontag: a letter to Borges

13 June 1996 New York
Dear Borges,

Since your literature was always placed under the sign of eternity, it doesn't seem too odd to be addressing a letter to you. (Borges, it's 10 years!) If ever a contemporary seemed destined for literary immortality, it was you. You were very much the product of your time, your culture, and yet you knew how to transcend your time, your culture, in ways that seem quite magical. This had something to do with the openness and generosity of your attention. You were the least egocentric, the most transparent of writers, as well as the most artful. It also had something to do with a natural purity of spirit. Though you lived among us for a rather long time, you perfected practices of fastidiousness and of detachment that made you an expert mental traveller to other eras as well. You had a sense of time that was different from other people's. The ordinary ideas of past, present and future seemed banal under your gaze. You liked to say that every moment of time contains the past and the future, quoting (as I  remember) the poet Browning, who wrote something like, "the present is the instant in which the future crumbles into the past.'' That, of course, was part of your modesty: your taste for finding your ideas in the ideas of other writers.

Your modesty was part of the sureness of your presence. You were a discoverer of new joys. A pessimism as profound, as serene, as yours did not need to be indignant. It had, rather, to be inventive – and you were, above all, inventive. The serenity and the transcendence of self that you found are to me exemplary. You showed that it is not necessary to be unhappy, even while one is clear-eyed and undeluded about how terrible everything is. Somewhere you said that a writer–delicately you added: all persons – must think that whatever happens to him or her is a resource. (You were speaking of your blindness.) You have been a great resource, for other writers. In 1982 – that is, four years before you died – I said in an interview, "There is no writer living today who matters more to other writers than Borges. Many people would say he is the greatest living writer... Very few writers of today have not learnt from him or imitated him.''

That is still true. We are still learning from you. We are still imitating you. You gave people new ways of imagining, while proclaiming over and over our indebtedness to the past, above all, to literature. You said that we owe literature almost everything we are and what we have been. If books disappear, history will disappear, and human beings will also disappear. I am sure you are right. Books are not only the arbitrary sum of our dreams, and our memory. They also give us the model of self-transcendence. Some people think of reading only as a kind of escape: an escape from the "real'' everyday world to an imaginary world, the world of books. Books are much more. They are a way of being fully human.

I'm sorry to have to tell you that books are now considered an endangered species. By books, I also mean the conditions of reading that make possible literature and its soul effects. Soon, we are told, we will call up on "bookscreens'' any "text'' on demand, and will be able to change its appearance, ask questions of it, "interact'' with it. When books become "texts'' that we "interact'' with according to criteria of utility, the written word will have become simply another aspect of our advertising-driven televisual reality. This is the glorious future being created, and promised to us, as something more "democratic''. Of course, it means nothing less then the death of inwardness – and of the book.

This time around, there will be no need for a great conflagration. The barbarians don't have to burn the books. The tiger is in the library. Dear Borges, please understand that it gives me no satisfaction to complain. But to whom could such complaints about the fate of books–of reading itself – be better addressed than to you? (Borges, it's 10 years!) All I mean to say is that we miss you. I miss you. You continue to make a difference. The era we are entering now, this 21st century, will test the soul in new ways. But, you can be sure, some of us are not going to abandon the Great Library. And you will continue to be our patron and our hero.

Extracted from 'Where the Stress Falls' by Susan Sontag (Jonathan Cape, £17.99).

November 1, 2010

(ZT) some important algorithms

下面是一些比较重要的算法,原文罗 列了32个,但我觉得有很多是数论里的,和计算机的不相干,所以没有选取。下面的这些,有的我们经常在用,有的基本不用。有的很常见,有的很偏。不过了解 一下也是好事。也欢迎你留下你觉得有意义的算法。(注:本篇文章并非翻译,其中的算法描述大部份摘自Wikipedia,因为维基百科描述的很专业了)

A*搜寻算法

俗称A星算法。这是一种在图形平面上,有多个节点的路径,求出最低通过成本的算法。常用于游戏中的NPC的移动计算,或线上游戏的BOT的移动计算上。该算法像Dijkstra算法一样,可以找到一条最短路径;也像BFS一样,进行启发式的搜索。

Beam Search

束 搜索(beam search)方法是解决优化问题的一种启发式方法,它是在分枝定界方法基础上发展起来的,它使用启发式方法估计k个最好的路径,仅从这k个路径出发向下 搜索,即每一层只有满意的结点会被保留,其它的结点则被永久抛弃,从而比分枝定界法能大大节省运行时间。束搜索于20 世纪70年代中期首先被应用于人工智能领域,1976 年Lowerre在其称为HARPY的语音识别系统中第一次使用了束搜索方法,他的目标是并行地搜索几个潜在的最优决策路径以减少回溯,并快速地获得一个 解。

二分取中查找算法一 种在有序数组中查找某一特定元素的搜索算法。搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束;如果某一特定元素大于或者 小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。这种搜索算法每一次比较都使搜索范围缩小一半。

Branch and bound

分支定界(branch and bound)算法是一种在问题的解空间树上搜索问题的解的方法。但与回溯算法不同,分支定界算法采用广度优先或最小耗费优先的方法搜索解空间树,并且,在分支定界算法中,每一个活结点只有一次机会成为扩展结点。

数据压缩

数据压缩是通过减少计算机中所存储数据或者通信传播中数据的冗余度,达到增大数据密度,最终使数据的存储空间减少的技术。数据压缩在文件存储和分布式系统领域有着十分广泛的应用。数据压缩也代表着尺寸媒介容量的增大和网络带宽的扩展。

Diffie�Hellman密钥协商Diffie�Hellman key exchange,简称"D�H",是一种安全协议。它可以让双方在完全没有对方任何预先信息的条件下通过不安全信道建立起一个密钥。这个密钥可以在后续的通讯中作为对称密钥来加密通讯内容。

Dijkstra's 算法迪 科斯彻算法(Dijkstra)是由荷兰计算机科学家艾兹格・迪科斯彻(Edsger Wybe Dijkstra)发明的。算法解决的是有向图中单个源点到其他顶点的最短路径问题。举例来说,如果图中的顶点表示城市,而边上的权重表示著城市间开车行 经的距离,迪科斯彻算法可以用来找到两个城市之间的最短路径。

动态规划

动 态规划是一种在数学和计算机科学中使用的,用于求解包含重叠子问题的最优化问题的方法。其基本思想是,将原问题分解为相似的子问题,在求解的过程中通过子 问题的解求出原问题的解。动态规划的思想是多种算法的基础,被广泛应用于计算机科学和工程领域。比较著名的应用实例有:求解最短路径问题,背包问题,项目 管理,网络流优化等。这里也有一篇文章说得比较详细。

欧几里得算法

在数学中,辗转相除法,又称欧几里得算法,是求最大公约数的算法。辗转相除法首次出现于欧几里得的《几何原本》(第VII卷,命题i和ii)中,而在中国则可以追溯至东汉出现的《九章算术》。

最大期望(EM)算法在 统计计算中,最大期望(EM)算法是在概率(probabilistic)模型中寻找参数最大似然估计的算法,其中概率模型依赖于无法观测的隐藏变量 (Latent Variable)。最大期望经常用在机器学习和计算机视觉的数据聚类(Data Clustering)领域。最大期望算法经过两个步骤交替进行计算,第一步是计算期望(E),利用对隐藏变量的现有估计值,计算其最大似然估计值;第二 步是最大化(M),最大化在 E 步上求得的最大似然值来计算参数的值。M 步上找到的参数估计值被用于下一个 E 步计算中,这个过程不断交替进行。

快速傅里叶变换(FFT)快 速傅里叶变换(Fast Fourier Transform,FFT),是离散傅里叶变换的快速算法,也可用于计算离散傅里叶变换的逆变换。快速傅里叶变换有广泛的应用,如数字信号处理、计算大 整数乘法、求解偏微分方程等等。本条目只描述各种快速算法,对于离散傅里叶变换的性质和应用,请参见离散傅里叶变换。

哈希函数

HashFunction 是一种从任何一种数据中创建小的数字"指纹"的方法。该函数将数据打乱混合,重新创建一个叫做散列值的指纹。散列值通常用来代表一个短的随机字母和数字组 成的字符串。好的散列函数在输入域中很少出现散列冲突。在散列表和数据处理中,不抑制冲突来区别数据,会使得数据库记录更难找到。

堆排序

Heapsort是指利用堆积树(堆)这种数据结构所设计的一种排序算法。堆积树是一个近似完全二叉树的结构,并同时满足堆积属性:即子结点的键值或索引总是小于(或者大于)它的父结点。

归并排序

Merge sort是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。

RANSAC 算法

RANSAC 是"RANdom SAmpleConsensus"的缩写。该算法是用于从一组观测数据中估计数学模型参数的迭代方法,由Fischler and Bolles在1981提出,它是一种非确定性算法,因为它只能以一定的概率得到合理的结果,随着迭代次数的增加,这种概率是增加的。该算法的基本假设是 观测数据集中存在"inliers"(那些对模型参数估计起到支持作用的点)和"outliers"(不符合模型的点),并且这组观测数据受到噪声影响。 RANSAC 假设给定一组"inliers"数据就能够得到最优的符合这组点的模型。

RSA加密演算法

这是一个公钥加密算法,也是世界上第一个适合用来做签名的算法。今天的RSA已经专利失效,其被广泛地用于电子商务加密,大家都相信,只要密钥足够长,这个算法就会是安全的

并查集Union-find

并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。常常在使用中以森林来表示。

Viterbi algorithm

寻找最可能的隐藏状态序列(Finding most probable sequence of hidden states)


BTY:
关于这个世界上的算法,你可以看看Wikipedia的这个网页:http://en.wikipedia.org/wiki/List_of_algorithms

关于排序算法,你可以看看本站的这几篇文章《一个显示排序过程的Python脚本》、《一个排序算法比较的网站》

October 29, 2010

matlab syms

>>syms x
>>syms y
>> y=diff(0.25*3^x*exp(-3.56*x*(1-x)))


y =
(3^x*exp((89*x*(x - 1))/25)*((178*x)/25 - 89/25))/4 + (3^x*exp((89*x*(x - 1))/25)*log(3))/4


>> solve('-(178*x)/25 + 89/25-log(3)=0','x')

ans = 1/2 - (25*log(3))/178


>> x=1/2 - (25*log(3))/178

x = 0.3457



***OR***

>> solve('y=0','y','x')

% if x has only one solution, the value can be seen from the "Workspace"
% However, if it has more than one solution, i still do not know how to look into % the construction of syms......

backup: interview summary

谷歌笔试:
1.
n支队伍比赛,分别编号为0,1,2。。。。n-1,已知它们之间的实力对比关系,存储在一个二维数组w[n][n] 中,w[i][j]
的值代表编号为i,j的队伍中更强的一支 所以w[i][j]=i 或者j,现在给出它们的出场顺序,并存储在数组order[n]中,
比如order[n] = {4,3,5,8,1......},那么第一轮比赛就是 4对3, 5对8。。。。。。
胜者晋级,败者淘汰,同一轮淘汰的所有队伍排名不再细分,即可以随便排,
下一轮由上一轮的胜者按照顺序,再依次两两比,比如可能是4对5,直至出现第一名
编程实现,给出二维数组w,一维数组order 和 用于输出比赛名次的数组result[n],求出result


2.题目说的比较花哨,根据我的理解,本质上就是有n个长为m+1的字符串,如果某个字符串的最后m个字符与某个字符串的前m个字符匹配,则两个字符串可以联接,问这n个字符串最多可以连成一个多长的字符串,如果出现循环,则返回错误

百度面试:

3.
用天平(只能比较,不能称重)从一堆小球中找出其中唯一一个较轻的,使用x次天平 最多可以从y个小球中找出较轻的那个,求y与x的关系式
4.有一个很大很大的输入流,大到没有存储器可以将其存储下来,而且只输入一次,如何从这个输入流中随机取得m个记录
5.大量的URL字符串,如何从中去除重复的,优化时间空间复杂度

网易有道笔试:
6. 求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义是
这两个节点间边的个数,比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2,优化时间空间复杂度
7.求一个有向连通图的割点,割点的定义是,如果除去此节点和与其相关的边,有向图不再连通,描述算法

discussion can be found @:
http://topic.csdn.net/u/20100930/13/9f10c56c-9545-488e-9b53-edffc9b6761d.html

==========

GOOGLE今天晚上的笔试题,刚参加回来.

第一题比较简单,检测同一个平面上的两个矩形是否重合

第二题是,给定一个随机函数,对一个数组进行随机排列,保证所有可能的排列出现的概率相等,也就是n!分之一


第三题就是约瑟夫问题的最优解法~Knuth具体数学上有,不过我忘记了,自己没推导出来,就写了个模拟

discussion can be found @:
http://topic.csdn.net/u/20101018/23/75b6dc53-610f-401e-b8ae-5aebee5cabe8.html

==========

雅虎:
1.对于一个整数矩阵,存在一种运算,对矩阵中任意元素加一时,需要其相邻(上下左右)某一个元素也加一,现给出一正数矩阵,判断其是否能够由一个全零矩阵经过上述运算得到。

2.一个整数数组,长度为n,将其分为m份,使各份的和相等,求m的最大值
比如{3,2,4,3,6} 可以分成{3,2,4,3,6} m=1;
{3,6}{2,4,3} m=2
{3,3}{2,4}{6} m=3 所以m的最大值为3

搜狐:

3.四对括号可以有多少种匹配排列方式?比如两对括号可以有两种:()()和(())

创新工场:

4.求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}

微软:
5.一个数组是由一个递减数列左移若干位形成的,比如{4,3,2,1,6,5}是由{6,5,4,3,2,1}左移两位形成的,在这种数组中查找某一个数。

discussion can be found @:
http://topic.csdn.net/u/20101021/14/7fdbcd52-3ee6-42ce-b48e-8fb56c4418da.html

==========

雅虎:
1.对于一个整数矩阵,存在一种运算,对矩阵中任意元素加一时,需要其相邻(上下左右)某一个元素也加一,现给出一正数矩阵,判断其是否能够由一个全零矩阵经过上述运算得到。

2.一个整数数组,长度为n,将其分为m份,使各份的和相等,求m的最大值
比如{3,2,4,3,6} 可以分成{3,2,4,3,6} m=1;
{3,6}{2,4,3} m=2
{3,3}{2,4}{6} m=3 所以m的最大值为3

搜狐:

3.四对括号可以有多少种匹配排列方式?比如两对括号可以有两种:()()和(())

创新工场:

4.求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}

微软:
5.一个数组是由一个递减数列左移若干位形成的,比如{4,3,2,1,6,5}是由{6,5,4,3,2,1}左移两位形成的,在这种数组中查找某一个数。

discussion can be found @:
http://topic.csdn.net/u/20101021/14/7fdbcd52-3ee6-42ce-b48e-8fb56c4418da.html

sth. about usrp in gnuradio

On Thu, Jul 21, 2005 at 05:48:33PM +0530, Arora_Amit wrote:
> Hi all,
>
> We are working on USRP. Please can any let us know what the
> factors or on what basis the audio_decimation, if_freq, usrp_decim.

These values are choosen so that the sample rates through the
processing path "make sense".  The USRP can sample and decimate at
particular rates.  The audio sink/source can sample at particular
rates.  We generally pick ratios such that they are related by simple
integer factors and that the signals of interest have appropriate
bandwidth at various points in the signal processing chain.

The API for using and controlling the usrp is documented in
usrp/host/lib/usrp_basic.h and usrp_standard.h

> It will be help if we can get what the following mention programs does:

> 1.    usrp_fft_simple.py

Does the same thing as usrp_fft only with less gui cruft.
(Plots Fast Fourier Transform of samples received from USRP.)

> 2.    benchmark_usb.py

An unreliable program to detemine maximum bandwidth of USB

>From the comment at the top of the file:

  Benchmark the USB/USRP throughput.  Finds the maximum full-duplex speed
  the USRP/USB combination can sustain without errors.

> 3.    usrp_oscope.py

Digital oscilloscope that uses a USRP as the source of samples.

> 4.    dbs_debug.py

Program to assist in debugging the DBS_RX daughterboard.

The DBS_RX daughterboard is a receive-only daughterboard that covers
800 MHz to 2400 MHz.

> 5.    nbfm_ptt_quick_and_dirty.py

Removed from CVS.  See nbfm_ptt.py  Narrow Band FM "Push to Talk" (wakie-talkie)

> 6.     usrp_rx_cfile.py

Read samples from the USRP and write to file formatted as binary
single-precision complex values.

> 7.    dbs_fft.py

Removed from CVS.

> 8.    nbfm_rcv.py

Narrow Band FM receiver.


If you haven't already, I suggest that you spend some time with:

  http://www.gnu.org/software/gnuradio/doc/exploring-gnuradio.html
  http://www.gnu.org/software/gnuradio/doc/howto-write-a-block.html


Also, there are online docs for the C++ guts:

  http://www.gnu.org/software/gnuradio/doc/index.html

matlab log

log: Natural logarithm
Syntax: Y = log(X)
Description:
The log function operates element-wise on arrays. Its domain includes
complex and negative numbers, which may lead to unexpected results if
used unintentionally.
Y = log(X) returns the natural logarithm of the elements of X. For
complex or negative , where , the complex logarithm is returned.
log(z) = log(abs(z)) + i*atan2(y,x)
Examples
The statement abs(log(-1)) is a clever way to generate .
ans =
3.1416

CS Conference Rankings: System Technology area

Rank 1:

SIGCOMM: ACM Conf on Comm Architectures, Protocols & Apps
INFOCOM: Annual Joint Conf IEEE Comp & Comm Soc
SPAA: Symp on Parallel Algms and Architecture
PODC: ACM Symp on Principles of Distributed Computing
PPoPP: Principles and Practice of Parallel Programming
RTSS: Real Time Systems Symp
SOSP: ACM SIGOPS Symp on OS Principles
SOSDI: Usenix Symp on OS Design and Implementation
CCS: ACM Conf on Comp and Communications Security
IEEE Symposium on Security and Privacy
MOBICOM: ACM Intl Conf on Mobile Computing and Networking
USENIX Conf on Internet Tech and Sys
ICNP: Intl Conf on Network Protocols
PACT: Intl Conf on Parallel Arch and Compil Tech
RTAS: IEEE Real-Time and Embedded Technology and Applications Symposium
ICDCS: IEEE Intl Conf on Distributed Comp Systems


Rank 2:

CC: Compiler Construction
IPDPS: Intl Parallel and Dist Processing Symp
IC3N: Intl Conf on Comp Comm and Networks
ICPP: Intl Conf on Parallel Processing
SRDS: Symp on Reliable Distributed Systems
MPPOI: Massively Par Proc Using Opt Interconns
ASAP: Intl Conf on Apps for Specific Array Processors
Euro-Par: European Conf. on Parallel Computing
Fast Software Encryption
Usenix Security Symposium
European Symposium on Research in Computer Security
WCW: Web Caching Workshop
LCN: IEEE Annual Conference on Local Computer Networks
IPCCC: IEEE Intl Phoenix Conf on Comp & Communications
CCC: Cluster Computing Conference
ICC: Intl Conf on Comm
WCNC: IEEE Wireless Communications and Networking Conference
CSFW: IEEE Computer Security Foundations Workshop


Rank 3:

MPCS: Intl. Conf. on Massively Parallel Computing Systems
GLOBECOM: Global Comm
ICCC: Intl Conf on Comp Communication
NOMS: IEEE Network Operations and Management Symp
CONPAR: Intl Conf on Vector and Parallel Processing
VAPP: Vector and Parallel Processing
ICPADS: Intl Conf. on Parallel and Distributed Systems
Public Key Cryptosystems
Annual Workshop on Selected Areas in Cryptography
Australasia Conference on Information Security and Privacy
Int. Conf on Inofrm and Comm. Security
Financial Cryptography
Workshop on Information Hiding
Smart Card Research and Advanced Application Conference
ICON: Intl Conf on Networks
NCC: Nat Conf Comm
IN: IEEE Intell Network Workshop
Softcomm: Conf on Software in Tcomms and Comp Networks
INET: Internet Society Conf
Workshop on Security and Privacy in E-commerce


Un-ranked:


PARCO: Parallel Computing
SE: Intl Conf on Systems Engineering (**)
PDSECA: workshop on Parallel and Distributed Scientific and
Engineering Computing with Applications
CACS: Computer Audit, Control and Security Conference
SREIS: Symposium on Requirements Engineering for Information Security
SAFECOMP: International Conference on Computer Safety, Reliability and Security
IREJVM: Workshop on Intermediate Representation Engineering for the
Java Virtual Machine
EC: ACM Conference on Electronic Commerce
EWSPT: European Workshop on Software Process Technology
HotOS: Workshop on Hot Topics in Operating Systems
HPTS: High Performance Transaction Systems
Hybrid Systems
ICEIS: International Conference on Enterprise Information Systems
IOPADS: I/O in Parallel and Distributed Systems
IRREGULAR: Workshop on Parallel Algorithms for Irregularly Structured Problems
KiVS: Kommunikation in Verteilten Systemen
LCR: Languages, Compilers, and Run-Time Systems for Scalable Computers
MCS: Multiple Classifier Systems
MSS: Symposium on Mass Storage Systems
NGITS: Next Generation Information Technologies and Systems
OOIS: Object Oriented Information Systems
SCM: System Configuration Management
Security Protocols Workshop
SIGOPS European Workshop
SPDP: Symposium on Parallel and Distributed Processing
TreDS: Trends in Distributed Systems
USENIX Technical Conference
VISUAL: Visual Information and Information Systems
FoDS: Foundations of Distributed Systems: Design and Verification of
Protocols conference
RV: Post-CAV Workshop on Runtime Verification
ICAIS: International ICSC-NAISO Congress on Autonomous Intelligent Systems
ITiCSE: Conference on Integrating Technology into Computer Science Education
CSCS: CyberSystems and Computer Science Conference
AUIC: Australasian User Interface Conference
ITI: Meeting of Researchers in Computer Science, Information Systems
Research & Statistics
European Conference on Parallel Processing
RODLICS: Wses International Conference on Robotics, Distance Learning
& Intelligent Communication Systems
International Conference On Multimedia, Internet & Video Technologies
PaCT: Parallel Computing Technologies workshop
PPAM: International Conference on Parallel Processing and Applied Mathematics
International Conference On Information Networks, Systems And Technologies
AmiRE: Conference on Autonomous Minirobots for Research and Edutainment
DSN: The International Conference on Dependable Systems and Networks
IHW: Information Hiding Workshop
GTVMT: International Workshop on Graph Transformation and Visual
Modeling Techniques

Days of our lives

Daisypath Anniversary tickers