sudo apt-get install squid接着对/etc/squid/squid.conf作如下修改
http_port 8888 #设定proxy的端口为8888 acl homenet src 98.219.0.0/16 #把访问proxy的机器的网段设为homenet http_access allow homenet #所有从homenet定义的网段的访问许可设为允许
sudo apt-get install squid接着对/etc/squid/squid.conf作如下修改
http_port 8888 #设定proxy的端口为8888 acl homenet src 98.219.0.0/16 #把访问proxy的机器的网段设为homenet http_access allow homenet #所有从homenet定义的网段的访问许可设为允许
f(x) = 1+\frac{\int_0^{x-1}[f(t)+f(x-1-t)]dt}{x-1} = 1 + \frac{2}{x-1}\int_0^{x-1}f(t)dt
不难得知f(t)=1+2\frac{\int_0^{t-1}f(u)du}{(t-1)} = 1+\frac{2(t-2}{t-1}
f(4)=1+\frac{2}{3}[\int_0^{1}f(t)dt + \int_1^{2}f(t)dt + \int_2^{3}f(t)dt] = \frac{11}{3} - \frac{4}{3}ln 2
#!/usr/bin/python from urlparse import urlparse, urljoin import urllib, sgmllib from HTMLParser import HTMLParser import re, sys class MyParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.num = 0 self.albums = {} def parse(self, url): req = urllib.urlopen(url) self.state = 0 self.raw_text = req.read() self.feed(self.raw_text) def handle_starttag(self, tag, attrs): #print "Encountered the beginning of a %s tag" % tag try: if self.state == 0: if tag == "table" and dict(attrs)["class"] =="olts": self.state = 1 self.row = 0 elif self.state == 1: if tag == "tr": self.row += 1 self.state = 2 elif self.state == 2: if tag == "td": self.state = 3 elif self.state == 3: if tag == "a": self.state = 4 else: self.state = 1 elif self.state == 4: self.state = 1 except KeyError: pass def handle_endtag(self, tag): #print "Encountered the end of a %s tag" % tag if self.state >= 1 and tag == "table": self.state = 0 def handle_data(self, data): if self.state == 3: if self.row > 1: print "%d title"%(self.num), data[:-2], self.num += 1 self.title = data[:-2] elif self.state == 4: if data.strip(): print "album", data try: self.albums[data].append(self.title) except KeyError: self.albums[data] = [self.title] numsongs = int(raw_input("How many songs do you have?")) myparser = MyParser() base = 0 while base < numsongs: current_url = "http://www.douban.com/people/apc/songs?start=%d"%(base) print current_url myparser.parse(current_url) base += 20 print "done, all together %d songs"%(myparser.num) al = myparser.albums.keys()[:] al.sort(cmp= lambda x,y: len(myparser.albums[x]) - len(myparser.albums[y])) for a in al: print a, "%d songs"%(len(myparser.albums[a]))我输出的结果是这两张专辑我标记的最多:
$asy inputfilenameinputfilename是你的asy输入源文件名称.如果它是helloworld.asy,那么asy就把这个源文件编译,输出为helloworld.eps.可以用-o选项指定输出文件名.
dot((0,0));
dot((0,0), blue);
draw((0,0)--(2,1));
draw((0,0)--(50,0),BeginArrow); draw((0,-10)--(50,-10),MidArrow); draw((0,-20)--(50,-20),EndArrow); draw((0,-30)--(50,-30),Arrows);这里设置arrow的参数可以为None(没有箭头,默认), Blank (不但不画箭头,线都不画), BeginArrow(箭头在起始端), MidArrow(箭头在正中间), EndArrow(箭头在末端,也简写成Arrow), 以及Arrows(两端都有)
draw((0,0)--(2,1),Bar);这里的参数还可以是None, BeginBar, EndBar (或者等价的简写为Bar), Bars(两端都是Bar)
unitsize(1cm); draw(unitsquare); label("$P_{0,0}$", (0,0), SW); label("$P_{1,1}$", (1,1), NE);
unitsize(1cm);这样(0,0)到(0,72)的距离就是72 inch而不是1 inch
size(100,200);这样所画的图会被自动scale到100*200这样的大小. 如果使用
size(0,200);x轴方向上不scale而在y方向上scale到200个pt
write(a)输出a的值,
size(400,200); import flowchart; block state0 = circle(" $0$ ", (0,0)); block state1 = circle(" $1$ ", (10,0)); block state2 = circle(" $2$ ", (20,0)); block state3 = circle(" $3$ ", (30,0)); block state4 = circle(" ... ", (40,0), fillpen=invisible, drawpen = invisible); draw(state0); draw(state1); draw(state2); draw(state3); draw(state4); add(new void(picture pic, transform t) { real r = 0.4; //state0 draw(pic,"$\lambda$", state0.position(2-r, t){NE}..{SE}state1.position(r,t),0.5*N, Arrow); //state1 draw(pic,"$\lambda$", state1.position(2-r, t){NE}..{SE}state2.position(r,t),0.5*N, Arrow); draw(pic,"$\mu$",state1.position(-r, t){SW}..{NW}state0.position(2+r,t),0.5*N, Arrow); //state2 draw(pic,"$\lambda$", state2.position(2-r, t){NE}..{SE}state3.position(r,t),0.5*N, Arrow); draw(pic,"$\mu$",state2.position(-r, t){SW}..{NW}state1.position(2+r,t),0.5*N, Arrow); //state3 draw(pic,"$\lambda$", state3.position(2-r, t){NE}..{SE}state4.position(r,t),0.5*N, Arrow); draw(pic,"$\mu$",state3.position(-r, t){SW}..{NW}state2.position(2+r,t),0.5*N, Arrow); //state4 draw(pic,"$\mu$",state4.position(-r, t){SW}..{NW}state3.position(2+r,t),0.5*N, Arrow); });
Pr(s) = \sum_{j=s}^n \frac{1}{n}\frac{s-1}{j-1}=\frac{s-1}{n}\sum_{j=s}^n \frac{1}{j-1}
这里1/n 是最大西瓜在第j个房间的概率,(s-1)/(j-1)是之前j-1个房间中最大的西瓜在房间1到房间s-1的概率. 可以证明s取n/e的时候这个概率取最大值."webkit": {
"webprefs": {
"default_fixed_font_size": 16,
"default_font_size": 16,
"fixed_font_family": "Microsoft YaHei",
"minimum_font_size": 16,
"minimum_logical_font_siz": 16,
"sansserif_font_family": "Microsoft YaHei",
"serif_font_family": "Microsoft YaHei"
}
}
svnadmin create /home/svn/myproject1在/home/svn目录底下, 你可以看见每个工程都对应一个目录. 目录里存放的是改工程的相关数据库.每个工程有不同的设置,也有自己独立的commit number.
$ svn import -m "New import" /path/to/mydir1 file:///home/svn/myproject1/mydir1 Adding mydir1/file1 Adding mydir1/file2 … Transmitting file data ......... Committed revision 1.
svn co file:///home/svn/myproject1或者
svn co svn+ssh://hostname/home/svn/myproject1
svn add newfile如果要添加文件夹newdir,但是不包括newdir底下的已有文件(默认是递归添加的)
svn add --depth empty newdir
svn commit -m "add newfile"
svn list http://192.168.61.79/repos/server svn list -v http://192.168.61.79/repos/server
svn cat foo.c > foo.c.tmp查看foo.c在111版本时的内容
svn cat foo.c -r 111
svn co http://192.168.61.79/repos/server -r 4
svn update -r 4
svn delete foo.c
svn -v status
svn log svn log http://192.168.61.79/repos/server
svn update foo.c
svn revert foo.c
svn revert foo.c
svn: Commit failed (details follow): svn: File or directory 'foo.c' is out of date; try updating svn: resource out of date; try updatinguser2这个时候运行
svn up Conflict discovered in 'foo.c'. Select: (p) postpone, (df) diff-full, (e) edit, (mc) mine-conflict, (tc) theirs-conflict, (s) show all options:这是因为svn发现了conflict, 需要user2采取措施解决. user2可以采取的动作总共包括
(e) edit - change merged file in an editor (df) diff-full - show all changes made to merged file (r) resolved - accept merged version of file (dc) display-conflict - show all conflicts (ignoring merged version) (mc) mine-conflict - accept my version for all conflicts (same) (tc) theirs-conflict - accept their version for all conflicts (same) (mf) mine-full - accept my version of entire file (even non-conflicts) (tf) theirs-full - accept their version of entire file (same) (p) postpone - mark the conflict to be resolved later (l) launch - launch external tool to resolve conflict (s) show all - show this list这里我们的选择包括
\int_{x=0}^{1}x^2+(1-x)^2 d x = \frac{2}{3}
.sty, .cls or .fd: $TEXMF/tex/<format>/<package>/ .mf: $TEXMF/fonts/source/<supplier>/<font>/ .tfm: $TEXMF/fonts/tfm/<supplier>/<font>/ .vf: $TEXMF/fonts/vf/<supplier>/<font>/ .afm: $TEXMF/fonts/afm/<supplier>/<font>/ .pfb: $TEXMF/fonts/type1/<supplier>/<font>/ .ttf: $TEXMF/fonts/truetype/<supplier>/<font>/ .otf: $TEXMF/fonts/opentype/<supplier>/<font>/ .pool, .fmt, .base or .mem: $TEXMF/web2c
kpsewhich -expand-var='$TEXMFMAIN'在我的MacTex(基于TeX Live)上结果为/usr/local/texlive/2010/texmf
kpsewhich texmf.cnf
\frac{A-B+1}{A+1}{A+B \choose A}
The Ballot ProblemIn[1]:= f[x_]:=x^2+1
In[1]:= Solve[x^2+2x-a == b, x]
In[1]:= Limit[Sin[x]/x, x->0] In[2]:= Limit[1/x, x->Infinity]
In[1]:= D[Exp[x],x]二阶导数
In[2]:= D[Exp[x],{x,2}]
In[1]:= Sum[a^i/i, {i,1,M}]
In[1]:= Plot[Sin[x],{x,0, Pi}] In[1]:= Plot[{Sin[x], Cos[x]},{x,0, Pi}]
In[1]:= M=.
In[1]:= Remove[M]
In[1]:= Import["foo.dat","Table"]
In[1]:= Fit[{{1,10},{2,25},{3,31},{4,40}}, {1,x}, x] In[1]:= Fit[Import["foo.dat","Table"], {1,x}, x]
In[1]:= Expand[(1 + x + x^2) (1 + x)] Out[1]:= 1 + 2 x + 2 x^2 + x^3
In[1]:= Factor[1 + x^3] Out[1]:= (1 + x) (1 - x + x^2)
In[1]:= Simplify[(1 + x)^2 - (1 - x)^2] Out[1]:= 4x
plot sin(x)+exp(x)除了sin(x)外, 还支持的其他函数包括: abs(x),acos(x),asin(x),atan(x),cos(x),cosh(x),erf(x),exp(x),inverf(x),invnorm(x),log(x),log10(x),norm(x),rand(x),sgn(x),sin(x),sinh(x),sqrt(x),tan(x),tanh(x).
y(x)=x**2+log(x) z(x)=x**3-xgnuplot还支持?:这种C风格的函数.比如
f(x) = x < 1 ? 1 : x < 2 ? 3 : 5就是f(x) =1 if x<1, =3 if 1<=x<2 =5 otherwise
plot y(x), z(x)还可以直接这样作:
plot y(x) = x**2+log(x), y(x), z(x)=x**3-x, z(x)
plot "foo.dat" using 1:2使用foo.dat第1列和第2列作为数据,但每2行skip掉一行
plot "foo.dat" using 1:2 every 2使用foo.dat第1列(作为x)和第2列(作为y)做第一条曲线,使用foo.dat第1列(作为x)和第3列(作为y)做第二条曲线
plot "foo.dat" using 1:2, "foo.dat" using 1:3foo.dat第3列作为errobar:
plot "foo.dat" using 1:2:3 with yerrorbarsfoo.dat的第二列除以第一列作为y值
plot "foo.dat" using 1:($2/$1)foo.dat分为若干个block(block之间用两行回车隔开), 使用第2个block绘图
plot "foo.dat" index 1 using 1:2
replot
plot "foo.dat" using 1:2 title "sample curve"
plot "foo.dat" using 1:2 with lines # 用线条画图 plot "foo.dat" using 1:2 with points # 用点画图 plot "foo.dat" using 1:2 with linespoints # 用点线结合的方式画图 plot "foo.dat" using 1:2 with boxes # bar-chart plot "foo.dat" using 1:2:(sprintf("%.2f", $2)) with labels # 在图上标注数字更多的曲线样式比如financebars等 参见Plot Style , errorbars
plot "foo.dat" using 1:2:3:4:(width)\ with boxerror fs pattern 1 #x:mean:min:max:box_width
plot "foo.dat" using 1:2 with lines linetype 1lt(linetype)指定点或者线的颜色-1=black 1=red 2=grn 3=blue 4=purple 5=aqua 6=brn 7=orange 8=light-brn
plot "foo.dat" using 1:2 with lines linecolor rgb "red" plot "foo.dat" using 1:2 with lines linecolor rgb "#ff0000"
plot "foo.dat" using 1:2 with lines linewidth 6
plot "foo.dat" using 1:2 with points pointsize 2也可以对所有曲线指定(默认大小为1)
set pointsize 2如果使用points 或者linepoints画曲线的话,这里的piont相当于marker.可以用 pointtype和pointsize指定marker的样式和大小。
set style line 1 lt 1 lw 1 lc rgb "red" set style line 6 lt 2 lw 3 lc rgb "blue" plot sin(x) w l linestyle 1, cos(c) w lp linestyle 2
set xlabel "time(t)" set ylabel "A"使用LaTeX数学符号:
set ylabel "{/Symbol f_i}"
set logscale x取消logscale的x轴
unset logscale x
set format x "%g%%"以指数形式表现, 比如10^1, 10^2,10^3而不是10, 100, 1000
set format x "10^{%L}"
set xrange [-3:65] set yrange [ 4:14]也可以在绘制的时候指定:
plot [-3:65] sin(x)
set xtics ("x=1" 1, "x=10" 10, "x=100" 100)
set xtics 100
set xtics 0, 100 #坐标轴小于0的部分就没有刻度了
set ytics nomirror #y坐标轴的tics在y2上没有mirror
set xdata time set timefmt "%s" #输入时间数据形式为time()函数返回值 set format x "%b/%y" #输出时间数据形式为month/year
set key left bottom set key outside也可以用坐标指定(这里的坐标是指图例中第一行文字和符号之间的中点坐标)
set key 100,40
set key at 100,40
unset key
set term x11
set term postscript eps enhanced
set term png
set output "foo.eps"如果另存为png文件
set output "foo.png"
set size ratio 3
set size 2,1
set grid set grid y unset grid
unset border # 没有边框 set border 3 #只留下左边和下边的边框
$eps2eps input.eps output.eps
set label center at 11.5,1.5 "My-Fav-Label!" font ",6"
load "your-gnuplot-file"
$ gdb foogdb会在你出现段错误的地方停下来,你会看到是哪个程序哪行语句出了问题.
$ ulimit -c unlimited然后运行你的代码,比如叫foo, 等到segment fault发生并异常退出以后, 你会发现在foo的同一个文件夹下多了一个名字类似core.1234这样的文件。这时候运行如下命令就可以重现案发现场了
$ gdb foo core.1234
(gdb) bt #0 0x000000010005ea07 in init (ctx=0x100622070, opts=@0x10060d078) at Utils.cpp:1678 #1 0x00000001000149ad in main (argc=3, argv=0x7fff5fbffb30) at main.cpp:591frame: 改变frame,比如
(gdb) frame 1 #2 0x8048414 in main (argc=1, argv=0xbffffaf4) at test.c:19 19 x = func1(x);info frame: 查看当前frame的信息
(gdb) info frame Stack level 2, frame at 0xbffffa8c: eip = 0x8048414 in main (test.c:19); saved eip 0x40037f5c called by frame at 0xbffffac8, caller of frame at 0xbffffa5c source language c. Arglist at 0xbffffa8c, args: argc=1, argv=0xbffffaf4 Locals at 0xbffffa8c, Previous frame's sp is 0x0 Saved registers: ebp at 0xbffffa8c, eip at 0xbffffa90info locals: 查看当前frame里的局部变量
(gdb) info locals x = 30 s = 0x8048484 "Hello World!\n"info args: 查看当前frame的调用参数
(gdb) info args argc = 1 argv = (char **) 0xbffffaf4
(gdb) p it $1 = (item *) 0x100700060查看这个struct的内容
(gdb) p *it $2 = { next = 0x100700000, prev = 0x0 }如果你有如下数组
int *array = (int *) malloc (len * sizeof (int));你可以这样来查看你的数组
p *array@len有时候你知道一段二进制代码所属的函数和偏移, 查这段对应的源代码:
list *myfunc+0x16
set variable a=10
(gdb) info source Current source file is shared_ptr.hpp Compilation directory is /usr/local/include/boost/smart_ptr Located in /usr/local/include/boost/smart_ptr/shared_ptr.hpp Contains 712 lines. Source language is c++. Compiled with unknown debugging format. Does not include preprocessor macro info.info threads: 查看当前线程数目以及状态
(gdb) info threads Id Target Id Frame 3 process 35 thread 27 0x34e5 in sigpause () 2 process 35 thread 23 0x34e5 in sigpause () * 1 process 35 thread 13 main (argc=1, argv=0x7ffffff8) at threadtest.c:68
国王的决定 | 版本1国王告诉A | 版本1可以排除掉 | 版本2可以排除掉 |
放A 杀B 杀C | B |   |   |
放A 杀B 杀C | C | x |   |
杀A 放B 杀C | C | x | x |
杀A 放B 杀C | C | x | x |
杀A 杀B 放C | B |   |   |
杀A 杀B 放C | B |   |   |
Hello, World
\bye
\starttext你可以在http://live.contextgarden.net/尝试在线编译ConTeX文件
Hello, World
\stoptext
\documentclass{article}
\begin{document}
Hello, World
\end{document}
\documentclass[10pt,a4paper]{article} \usepackage{graphicx} \title{Empty Article} \author{apc999} \date{\today} \begin{document} \maketitle Put your text here \end{document}
\usepackage[top=1.0cm,right=0.5cm,bottom=1.0cm,left=0.5cm]{geometry}
\begin{eqnarray} E=MC^2 \label{eq:relativity} \end{eqnarray}
\usepackage{graphicx}在需要插入图片的地方:
\begin{figure}[h] \centering \includegraphics[width=0.8\textwidth]{foo.eps} \caption{caption of figure foo} \label{fig:foo} \end{figure}
\usepackage{subfigure}然后在你需要插入图片的地方:
\begin{figure} \centering \subfigure[caption of foo]{ \label{fig:subfigure:foo} \includegraphics[width=0.48\textwidth]{foo.eps}}\hfill \subfigure[caption of bar]{ \label{fig:subfigure:bar} \includegraphics[width=0.48\textwidth]{bar.eps}} \caption{caption of subfigures foo and bar} \label{fig:subfigure} \end{figure}** subfig包用法与subfigure基本一样,就是把\subfigure换成\subfloat
\centering \begin{table}[h] \begin{tabular}{ll} x & x \\ x & x \end{tabular} \caption{caption of table foo} \label{tab:foo} \end{table}更多table的用法
\begin{eqnarray*} y = \left\{ \begin{array}{ll} a & \textrm{if $d>c$}\\ b+x & \textrm{in the morning}\\ l & \textrm{all day long} \end{array} \right. \end{eqnarray*}实际上还有一个更简单的做法--用cases环境. 不过需要amsmath这个package
\usepackage{amsmath} \begin{eqnarray*} y = \begin{cases} a & \textrm{if $d>c$}\\ b+x & \textrm{in the morning}\\ l & \textrm{all day long} \end{cases} \end{eqnarray*}
\usepackage[]{listings} \lstset{language=Python,tabsize=4} \begin{lstlisting} import sys sys.stdout.write("Hello World") \end{lstlisting}
\begin{quote} the quoted text \end{quote}
\bibliographystyle{xxx} % 使用style文件xxx.bst \bibliography{yyy} %使用reference 数据库文件yyy.bib"xxx可以为 IEEE, acm, plain, abbrv等等
/etc/fonts/fonts.conf
以及用户自定义配置~/.fonts.conf
./usr/local/share/fonts/
.网上教程之类的通常是这样做.不过你也可以直接添加到~/fonts/
这个路径下,该路径被/etc/fonts/fonts.conf
默认的访问.所以你只需要把新添加的字体拷到~/.fonts
就好了.比如我就把windows下的C:\WINDOWS\Fonts
的simsun.ttc
以及simshei.ttf
文件考到了上述目录下.这样我就可以在linux中使用windows下的宋体,新宋和黑体. <family>-<size>:<name>=<value>...比如
times-12:bold:slant=italic,oblique
fc-list :lang=zh来查看你当前系统中的中文字体.相比之下,texlive中自带的CJK只能支持区区几种.
\documentclass{article} %需要fontspec这个宏包设置字体 \usepackage{fontspec} %指定文档的字体, 上面fc-list命令列出的中文字体都可以用在底下 \setmainfont[BoldFont=WenQuanYi Zen Hei]{SimSun} %默认字体为SimSun,默认的bold(比如用在section title之类的地方)为文泉译增黑. %还可以用\setsansfont, \setmonofont来设置文档的sans 和mono字体. %针对中文设置下换行 \XeTeXlinebreaklocale "zh" %使用中文换行 \XeTeXlinebreakskip = 0pt plus 1pt % % OK了,后面就和latex没有两样了 \title{Notes} \author{apc999} \date{\today} \begin{document} \maketitle \section{中文} 你好,世界 \section{数学} $$\sum_i x_i$$ \end{document}
xelatex helloworld.tex
import pylab params = {'backend': 'ps', 'axes.labelsize': 14, 'text.fontsize': 10, 'lines.linewidth':2, 'legend.fontsize': 16, 'xtick.labelsize': 14, 'ytick.labelsize': 14} pylab.rcParams.update(params)
set terminal postscript eps enhanced color linewidth 2 font "Helvetica, 20" set terminal x11 enhanced font "Helvetica, 15"对于输出为eps的文件,我希望它字体大一些,线宽粗一些.通常paper里需要这样设定才能看得清楚.
plot sin(x)这里x取值范围默认是[-10,10],如果要改变x取值范围
set xrange [1:10]如果要从文件里读入数据,比如用'data.txt'文件中第1列作x第3列作y作图,线段类型为"lines",这个curve取名为data1
plot 'data.txt' using 1:3 with lines title 'data1', 'data.txt' using 1:3 with lines title 'data2'设置xlabel 以及字体(可选)
set xlabel "time t" font "Arial, 15"设置输出文件名, 默认是STDOUT
set output "data.eps"更新/重画
replot
\usepackage{graphicx}
\begin{figure}[t] \begin{center} \showthe\columnwidth % Use this to determine the width of the figure. \includegraphics[width=\columnwidth]{fig1.eps} \caption{\label{fig:sin_cos} Plot of the sine and cosine functions.} \end{center} \end{figure}如果是pdflatex, 可以支持png等非矢量格式图片
\begin{figure}[t] \begin{center} \psfrag{sin(x)}{$\sin(x)$} \psfrag{cos(x)}{$\cos(x)$} \psfrag{x (radians)}{$x$ (radians)} \psfrag{y}{$y$} {\footnotesize % Replace tick-lables with smaller font. \psfrag{1.0}{1.0} \psfrag{0.5}{0.5} \psfrag{0.0}{0.0} \psfrag{-0.5}{-0.5} \psfrag{-1.0}{-1.0} \psfrag{-8}{-8} \psfrag{-6}{-6} \psfrag{-4}{-4} \psfrag{-2}{-2} \psfrag{0}{0} \psfrag{2}{2} \psfrag{4}{4} \psfrag{6}{6} \psfrag{8}{8} \showthe\columnwidth % Use this to determine the width of the figure. \includegraphics[width=\columnwidth]{fig2.eps} } % Note that the psfrag commands only work in the top-most environment. \caption{\label{fig:sin_cos} Plot of the sine and cosine functions.} \end{center} \end{figure}
P\{head\} = \int_{p=0}^1P{head|p}\mathrm{d}p = \int_{p=0}^1p\mathrm{d}p=\frac{1}{2}
f(p|head) =\frac{P\{head|p\}f(p)}{P\{head\}}=2p
\hat{p} = \int_{p=0}^1 2p p\mathrm{d}p = 2/3
\begin{CJK}{编码种类}{字体种类} \end{CJK}把用到中文的地方包围起来就可以了。这里CJK环境可以换成CJK*环境,区别是CJK环境里中英文间会有空格而CJK*没有。编码种类可以是GB,Big5 也可以是UTF8,取决于你自己的locale设定。我是用的纯英文环境,所以都上的是UTF8。默认情况下字体种类选择不多,可以是gbsn(gb宋体),gkai(gb楷体),bsmi(big5宋体),bkai(big5楷体)
\documentclass{article} \usepackage{CJK} \begin{document} \begin{CJK*}{UTF8}{gbsn} 您好! \end{CJK*} \end{document}
\sum_{i\neq j} x_ix_j
。所以本题就是给定N,看是否能找到一个组人数划分使得上式等于K。K=\sum_{i\neq j} x_ix_j = \frac{(x_1+\ldots+x_m)^2-\sum_ix_i^2}{2}=\frac{N^2-\sum_ix_i^2}{2}
T(s)=\{x_1+\dots+x_m|\forall \sum_ix^2_i=s\}
T(s)=\left\{\begin{array}{ll}
(\bigcup_{i=1}^{s/2} (\{t\} \cup T(i))\odot T(s-i)) & i=t^2\\
\bigcup_{i=1}^{s/2} T(i)\odot T(s-i) & \textrm{otherwise}
\end{array}
\right.
A\odot B = \{ a+b | \forall a\in A, b\in B\}
XLFD: -*-Courier New-normal-r-*-*-13-*-*-*-c-*-iso8859-1
Fontconfig: Courier New-13
(add-to-list 'default-frame-alist '(font . "DejaVu Sans Mono-14"))这样普通和daemon模式就都可以正确设置字体了.
$xlsfonts得到像如下格式的输出
-adobe-courier-medium-r-normal--17-120-100-100-m-100-iso8859-1每一行都是一种系统支持的字体。每一行的格式参见 Font specification , 简单说来遵循“-maker-family-weight-slant-widthtype-style-pixels-height-horiz-vert-spacing-width-registry-encoding"这样的格式。需要特别指出的是pixels代表的是字体的高度(单位是像素),height代表的是字体在屏幕上的高度*10(单位是磅), pixels和height两个当中通常只指定一个值,另一个用*代替。另外我们注意到列出来的字体当中有些字段为0,这说明这些字体是矢量字体。对于这些字段我们使用的时候需要用数字或者*来替换。
-dejavu-dejavu sans mono-medium-r-normal--0-0-0-0-c-0-iso8859-1
$xfd -fn "-dejavu-dejavu sans mono-medium-r-normal--16-*-*-*-c-*-iso8859-1"
(set-default-font "-dejavu-dejavu sans mono-medium-r-normal--16-*-*-*-m-*-iso8859-1")
(setq-default line-spacing 0)另外我这里的emacs有一点小bug所以set-default-font以后会有好几秒钟的延迟,需要在~/.emacs开头加入
(modify-frame-parameters nil '((wait-for-wm . nil)))
~/.cshrc
(tcsh)或者~/.bashrc
(bash)里设置环境变量,对于terminal中的程序完全没有问题。但是对于基于Carbon或者Cocoa的Native Mac程序(比如Carbon Emacs)来说是没有用的。它们不会从shell中继承环境变量。一个方法是把$PATH, $PYTHONPATH等环境变量设置在~/.MacOSX/environment.plist
这里。可以用(a) "/Developer/Applications/Utilities/Property List Editor.app
"这个工具修改. 也可以(b) 用defaults 命令:defaults write ${HOME}/.MacOSX/environment PATH "${HOME}/bin:/usr/bin:/bin:/usr/local/bin"
setenv PATH `defaults read ~/.MacOSX/environment PATH`
~/.MacOSX/environment.plist
已经deprecated了.
新的方法是修改/etc/launchd.conf
使得所有Unix 环境变量在GUI中可见
参考Accessing the Unix environment from emacs and Cocoa apps in OS X Mountain Lion$ system_profiler查看CPU信息
$ sysctl -a machdep.cpu或者
$ sysctl -n machdep.cpu.brand_string Intel(R) Core(TM) i5-2435M CPU @ 2.40GHz
sudo rm -rf /private/var/log/asl/*.asl
$ lpstat -a GHC6107_BW accepting requests since Sun Oct 28 15:30:42 2012 GHC9206_BW accepting requests since Mon Oct 29 12:48:11 2012 GHC9206_COLOR accepting requests since Mon Nov 28 13:00:02 2011 $ lp -d "GHC9206_BW" -o sides=two-sided-long-edge *.pdf request id is GHC9206_BW-82 (6 file(s))
$ networksetup -setv6off ethernet $ networksetup -setv6off wi-fi
apt-get install wine
def test(func, *args, **kargs): if not callable(func): raise RuntimeError, str(func) + ' not a callable object' else: func(*args, **kargs)
import os
import time
from threading import Thread
class Job(Thread):
def __init__(self, cmd):
Thread.__init__(self)
self.cmd = cmd
self.starttime = time.time()
def run(self):
os.popen(self.cmd)
print "time %.2fs, job %s is done"%(time.time()-self.starttime,self.cmd)
jobs = []
for i in range(1, 5):
j = Job("sleep %d"%i)
jobs.append(j)
j.start()
for j in jobs:
j.join()
print "time %.2fs, job %s returned"%(time.time() - j.starttime, j.cmd)
time 1.00s, job sleep 1 is done
time 1.00s, job sleep 1 returned
time 2.00s, job sleep 2 is done
time 2.00s, job sleep 2 returned
time 3.00s, job sleep 3 is done
time 3.00s, job sleep 3 returned
time 4.00s, job sleep 4 is done
time 4.00s, job sleep 4 returned
for j in reversed(jobs):得到结果:
j.join()
print "time %.2fs, job %s returned"%(time.time() - j.starttime, j.cmd)
time 1.00s, job sleep 1 is done所以当你调用join时,仅仅是检查该线程是否以及结束。如果结束则返回;否则阻塞直至结束。
time 2.00s, job sleep 2 is done
time 3.00s, job sleep 3 is done
time 4.00s, job sleep 4 is done
time 4.00s, job sleep 4 returned
time 4.01s, job sleep 3 returned
time 4.01s, job sleep 2 returned
time 4.01s, job sleep 1 returned
for j in reversed(jobs):
j.join(0.5)
print "time %.2fs, job %s returned"%(time.time() - j.starttime, j.cmd)
time 0.52s, job sleep 1 returned
time 1.00s, job sleep 1 is done
time 1.02s, job sleep 2 returned
time 1.52s, job sleep 3 returned
time 2.00s, job sleep 2 is done
time 2.02s, job sleep 4 returned
time 3.00s, job sleep 3 is done
time 4.00s, job sleep 4 is done
class Jobs(Queue.Queue):
def __init__(self):
Queue.Queue.__init__(self)
def newjob(self, name, func, *args, **kargs):
if not callable(func):
raise RuntimeError, str(func) + ' not a callable object'
self.put((name, func, args, kargs))
def do(self, numthreads = 1, debug = True):
threads = []
for i in range(numthreads):
t = Worker("thread%d"%i, self, debug)
threads.append(t)
t.start()
for t in threads:
t.join()
class Worker(threading.Thread):
def __init__(self, name, jobs, debug = False):
threading.Thread.__init__(self)
self.name = name
self.jobs = jobs
self.debug = debug
def run(self):
while not self.jobs.empty():
try:
job = self.jobs.get(True, 1)
(name, func, args, kargs) = job
except:
break
stime = time()
func(*args, **kargs)
if self.debug:
print "%s is done by %s, fin in %.2f s"%(name, self.name, time()-stime
>>>mylist = [1,2,3] >>>type(mylist) <type 'list'>所以这里我们新建了一个list的实例叫mylist。通过内建的type()函数我们可以查看这个实例的类型,返回的结果告诉我们它的类型是list这种内建的类型。
>>>type(list) <type 'type'> >>>list.__bases__ (<type 'object'>,)这里我们先查看了list的类型。我们得知list的类型是type,换言之list是type的一个实例。紧接着我们用__bases__属性查看它的父类,得知list其实继承了内建的object。再来
>>>type(type) <type 'type'> >>>type.__bases__ (<type 'object'>,)好,现在我们知道type的类型还是type自己,它是自己的一个实例,同时它继承了object。最后:
>>>type(object) <type 'type'> >>>type.__bases__ ()从而我们得知,object也是type的一个实例,同时它没有父类。
>>>class oldclass: ... def __init__(self): ... pass >>>class newclass(object): ... def __init__(self): ... pass
>>>oldobj = oldclass() >>>newobj = newclass() >>>print type(oldobj), oldobj.__class__ <type 'instance'> <class __main__.oldclass at 0x7f700714da10> >>>print type(newobj), newobj.__class__ <class '__main__.newclass'> <class '__main__.newclass'>
>>>print type(dict), dict.__class__ <type 'type'> <type 'type'>我们看到同样的结论。
Include/ | C源代码的头文件(.h) |
Lib/ | 用Python自己写的Python库文件(.py) |
Python/ | 这里是"编译器"和解释器的源码,Python的核心所在 |
Grammar/ | 包括一个Grammar文件,用BNF描述Python语言语法 |
Parser/ | 生成pgen这个工具使用Grammar文件 |
stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef它表示每个stmt可以是一个simple_stmt也可以是一个compound_stmt。simple_stmt可以是几个small_stmt的同行并列用";"隔开。 small_stmt可以是expr_stmt, print_stmt, del_stmt等简单语句。而compound_stmt则包括if_stmt, while_stmt等需要跨越多行的复合语句。就这样Python用BNF范式定义了最基本的语法。 现在我们有了这个通俗易懂的Grammar文件以后,pgen负责把这个Grammar转换成NFA,然后再转换为相应的DFA,接着再化简这个DFA,最后保存在gramint.c 和gramint.h这两个文件中。如果你觉得很复杂,你只需要记住我们根据Grammar这个文件得到了一个语法规则就可以了。我们现在来看一下一个py交互模式的运作流程以便于理解:
run_tty_loop(fp,filename){ for (;;) { run_tty_1(fp,filename); //不断执行一个“单行”语句 } }
run_tty_1(fp, filename) { //gram <- graminit将已生成的Python语法规则放进gram, //其实不在这个函数里完成,为了理解的方便我就这样写在这里。 //根据语法gram以及输入文件fp生成语法树存放在n中 node* n = parsefile(fp, filename, &gram, single_input, ...) // 执行以n为根节点的语法树 v = run_node(n, filename, ...) }
parsefile(fp,filename, g, ...) { //初始化err_ret //初始化一个tokenizer(词法分析器)tok tok = tok_setupf(fp, ...); return parsetok(tok, g, ...); }所以这个函数也相当简单,初始化一个词法分析器然后调用parsetok开始做词法分析。再来看parsetok:
parsetok(tok, g, ...) { ps = newparser(g, start) for (;;) { type = tok_get(tok, &a, &b); addtoken(ps, type, ...); } delparser(ps); }所以这里就是用一个for循环不停的调用tok_get抓取下一个token供语法分析使用。语法分析里的状态转移以及移进归约在addtoken中实现。
#!/usr/bin/python import sys import os import getopt import pexpect import re try: from ansi_color import * except ImportError: def color_str(s, *args): return s fg_green = None fg_red = None fg_blue = None prompt = "^.*\(.*\):|\[.*@.*\]|\$" nl = open("/dev/null", "w") def _print(s): if not single_mode: print s def do(cmds, hostname, username): global verbose, quiet, good_hosts #print "executing \"%s\""%(repr(cmds)) ret = 0 try: sshcmd = 'ssh %s'%(hostname) if username != None: sshcmd = sshcmd + " -l %s"%username s = pexpect.spawn(command=sshcmd, timeout=20) if verbose: s.logfile_read = sys.stdout s.setecho(False) else: s.logfile_read = s.logfile_send = nl s.setecho(False) t = 0 while t < 3: i = s.expect([prompt, pexpect.EOF, pexpect.TIMEOUT,\ "Are you sure you want to continue connecting (yes/no)?",\ "(P|p)assword:"]) t += 1 if i == 0: break elif i == 1: _print("End Of File") return 1 elif i == 2: _print("time out") return 1 elif i == 3: s.sendline("yes") elif i == 4: s.sendline(password) if t >= 3: return 1 if cmds: for cmd in cmds: s.sendline(cmd) s.expect(prompt) else: _print("\nEntering interactive mode, please ^] to escape") s.interact() s.sendline("exit") s.close() return 0 except pexpect.ExceptionPexpect: return 1 def print_usage(): print "Usage:\t ./multissh.py -f cmdfile -l username -c cmd -n nodesfile -v -r" print "execut cmd on remote hosts (all hosts in ./hosts.txt by default)" print "\t-v verbose" print "\t-r recording hosts on which mission succeeded and failed" print "\t-l username" print "\t-c cmd to be executed remotely" print "\t-n file containing the nodes" print "\t-f file conaining the cmd" print "\t-h show the usage" print "\t-p password" sys.exit(0) if __name__ == "__main__": try: opts, args=getopt.getopt(sys.argv[1:], \ "l:f:n:c:p:vhrq",["login_name", "cmdfile","nodesfile","command","password","verbose","help","recording","quiet"]) except getopt.GetoptError, err: print str(err) print_usage() if opts == [] and args == []: print_usage() if args: hosts = [args[0]] else: hosts = [] cmds = [] verbose = False quiet = False username = None recording = False password = "" single_mode = True for o, ra in opts: a = ra.strip("\n") if o in ("-h", "--help"): print_usage() elif o in ("-n", "--nodesfile"): hosts = [l.strip(" \t\n") for l in open(a, 'r')] single_mode = False elif o in ("-c", "--command"): cmds = [a] elif o in ("-f", "--cmdfile"): cmds = [cmd.strip(' \n') for cmd in open(a, 'r')] elif o in ("-v", "--verbose"): verbose = True elif o in ("-q", "--quiet"): quiet = True elif o in ("-r", "--recording"): recording = True elif o in ("-l", "--login_name"): username = a elif o in ("-p", "--password"): password = a if not hosts: _print("using default ./hosts.txt") h = open(os.path.join(os.path.expanduser("."), "hosts.txt"),'r') hosts = [dst.strip(' \n') for dst in h] if recording: f_good = open("good_hosts.txt","w") f_bad = open("bad_hosts.txt","w") good_hosts =[] bad_hosts =[] for (i, hostname) in enumerate(hosts): _print ("%d/%d: ["%(i+1, len(hosts))+ color_str(hostname, fg_blue)+"]") ret = do(cmds, hostname, username) if verbose: print if ret == 1: bad_hosts.append(hostname) _print("["+color_str("Fail!", fg_red)+"]") if recording: print>>f_bad, hostname f_bad.flush() else: good_hosts.append(hostname) _print ("["+color_str("OK!", fg_green)+"]") if recording: print>>f_good, hostname f_good.flush() _print ("%d hosts suceed!"%len(good_hosts)) sys.exit(ret)
import popen2 def _popen(cmd, timeout = 10, num_retry = 3, logfile = sys.stdout): i = 0 is_timeout = False while i <= num_retry: print "%dth try"%i, cmd sys.stdout.flush() i += 1 t0 = time() P = popen2.Popen3(cmd, True) prompt = False while time() < t0 + timeout and P.poll() == -1: sleep(0.1) sts = P.poll() if sts == -1: logfile.write(color_str("command [%s] timeout\n"%(cmd), fg_red)) if i < num_retry: logfile.write(color_str("terminate and try again\n", fg_red)) logfile.flush() is_timeout = True os.kill(P.pid, signal.SIGTERM) elif sts != 0: for l in P.childerr.readlines(): logfile.write(l) if i < num_retry: logfile.write(color_str("try again\n", fg_red)) logfile.flush() is_timeout = False else: is_timeout = False break logfile.write(color_str("return "+str(sts)+"\n", fg_red)) sys.stdout.flush() if is_timeout: return (sts, open("/dev/null", "r")) else: return (sts, P.fromchild)