Sunday, October 24, 2010

Scripting java using rhino and javascript

通过Rhino可以使javascript调用java的标准类库,这使得javascript的编程能力得以强化,在服务器端已经有javascript的MVC框架,一般也是基于Rhino的.
首先在ubuntu上可以通过命令安装rhino:
$> sudo apt-get install rhino

安装完成后,在命令行中输入js或者rhino:

$> js
$> rhino
Rhino 1.7 release 2 2010 09 15
js> new Date()
Sun Oct 24 2010 17:24:27 GMT+0800 (CST)
js> /^\d+$/.test("369");
true

就可以进入javascript的控制台.

另外一种方式就是从网上下载rhino 1.5R4.1版本,在命令行中用java运行,下面的代码在命令行的rhino1.7版本中不能运行,因为无法导入java.awt.*的包:
$> java -jar rhino-1.5R4.1.jar
Rhino 1.5 release 4.1 2003 04 21
js> importPackage(java.awt);
js> frame = new Frame("JavaScript")
js> frame.show()
js> button = new Button("OK")
js> frame.add(button)
js> frame.show()
js> function printDate() { print(new Date()) }
js> o = { actionPerformed: printDate }
js> buttonListener = java.awt.event.ActionListener(o)
js> button.addActionListener(buttonListener)

javascript访问java的包和class

java中所有的代码都是class包装了的,而class又是在package下的,rhino为此封装了一个全局对象Packages,通过Packages可以引入所有的java类,如Package.java.lang, Packages.java.io等:

js> Packages.java.io.File
[JavaClass java.io.File]
js> importPackage(java.io)
js> File
[JavaClass java.io.File]

importPackage(java.io)的效果类似java代码中的import java.io.*;
java中的第三方类库也可以通过importClass和importPackage引入,如:
js> importPackage(Packages.org.mozilla.javascript);
js> Context.currentContext
org.mozilla.javascript.Context@1bc887b
js> importClass(java.awt.List)
js> List
[JavaClass java.awt.List]

在引入了java的类库之后,就可以在javascript中使用这些类库了,如:

js> new java.util.Date()
Sun Oct 24 17:46:50 CST 2010
js> new Date()
Sun Oct 24 2010 17:46:54 GMT+0800 (CST)
js> var f = new java.io.File("/etc/hosts");
js> f.exists();
true
js> f.getName();
hosts
js> java.lang.Math.PI
3.141592653589793
js> java.lang.Math.cos(0)
1
js> for (i in f) { print(i) }
getAbsoluteFile
setReadOnly
listFiles
setReadable
writable
hashCode
wait
setExecutable
usableSpace
file
canonicalPath
getUsableSpace
notifyAll
equals
getParent
mkdirs
parent
class
compareTo
freeSpace
getTotalSpace
createNewFile
toString
toURI
toURL
getCanonicalPath
getCanonicalFile
canonicalFile
renameTo
getParentFile
executable
getFreeSpace
absolute
deleteOnExit
canWrite
name
notify
path
canRead
getPath
delete
length
getClass
readable
totalSpace
absoluteFile
lastModified
absolutePath
isAbsolute
list
mkdir
setWritable
isHidden
readOnly
canExecute
isDirectory
hidden
directory
isFile
getName
getAbsolutePath
exists
parentFile
setLastModified
在上面列出的File的方法中,还包括了其从java.lang.Object中继承的所有方法.对于java的重载方法,javascript调用需要用特别的方式.

用javascript实现java的接口

如要实现Runnable接口,按以下方式操作:
js> var obj = { run: function () { print("\nrunning"); } }
js> obj.run()

running
js> var r = new java.lang.Runnable(obj);
js> r.getClass()
class adapter1
js> var t = new java.lang.Thread(r)
Thread[Thread-1,5,main]
js> t.start();
js>
running

用javascript创建java的数组对象

一般直接用javascript创建数组就可以,转为java对象时,rhino会处理类型转换,也可以用以下方法直接创建java数组:
js> var arr = java.lang.reflect.Array.newInstance(java.lang.String, 5); arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = 'create java array using javascript.'
create java array using javascript.
js> arr
[Ljava.lang.String;@1e97f9f
js> arr[1]
create java array using javascript.
js>

Reference: http://www.mozilla.org/rhino/scriptjava.html

Saturday, October 23, 2010

在VIM中如何使用Tidy为HTML验证并格式化内容

在ubuntu中安装tidy只要输入命令:
$> sudo apt-get install tidy

$> man tidy

查看手册,可以看到比较有用的参数设置,一般我的文件都是utf8编码的,所以tidy命令会跟上"-utf8",并且一般情况就是将tidy输出的文件直接替换掉原来的文件,所以"-m"选项也很有用,输出的HTML也希望是格式化,有缩进的代码,这时就要加上"-i"参数,这样在命令行上我的tidy命令会如下所示:

$> tidy -m -i -utf8 target-files1 target-files2

可以将常用的参数设置写在一个配置文件中,在调用tidy命令时指定"-config config-file-name",下面这份配置就是官网上的一个配置例子,稍做了点调整:

// sample config file for HTML tidy
indent: auto
indent-spaces: 4
wrap: 120
markup: yes
output-xml: no
input-xml: no
show-warnings: yes
numeric-entities: yes
quote-marks: yes
quote-nbsp: yes
quote-ampersand: no
break-before-br: no
uppercase-tags: no
uppercase-attributes: no
char-encoding: utf8
new-inline-tags: cfif, cfelse, math, mroot,
mrow, mi, mn, mo, msqrt, mfrac, msubsup, munderover,
munder, mover, mmultiscripts, msup, msub, mtext,
mprescripts, mtable, mtr, mtd, mth
new-blocklevel-tags: cfoutput, cfquery
new-empty-tags: cfelse
在VIM中,如果需要对当前文件进行HTML格式化操作,那么可以在VIM命令模式下输入以下指令:

:!tidy -m -i -utf8 %

References: Clean up your Web pages with HTML TIDY

Tuesday, October 19, 2010

VIM正则表达式说明

Vim 中查找替换使用的正则表达式与一般的编程语言如javascript/ruby/perl不一样,尤其是在进行非贪婪匹配时,下面主要是分析在VIM中怎么进行非贪婪匹配的.

在VIM手册中有这样的说明: If a character is taken literally or not depends on the 'magic' option and the items mentioned next.
It is recommended to always keep the 'magic' option at the default setting, which is 'magic'. This avoids portability problems.

就是说默认的搜索替换是按magic模式进行查找的,如果有字符用反斜杠"\"转义的话,是会在magic模式中检查其对应转义后含意.并且在VIM配置文件中尽量保持使用magic模式.

VIM中有4种正则匹配模式,可以用":h /magic"查看帮助文档的说明,简单说就是有"\m", "\M", "\v", "\V"这四种,最常用的是默认的"\m",其次"\v"在进行分组捕获时也非常有用,因为不需要像在"\m"模式下那样对小括号进行转义,写起来比较麻烦,另二个模式用得较少些.

在帮助手册中对"\v"的说明如下:
Use of "\v" means that in the pattern after it all ASCII characters except '0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning. "very magic"

也就是除了0-9, a-z, A-Z和下划线"_"之外的其他ASCII字符都有特殊含义,如(, ), |, $, ^, [, ], {, }, :, !, ., *, ?, +, <, >等,这与其他的如javascript的正则更接近一些,在这些字符用得比较多的时候,就考虑用"\v"模式,可以少打好多反斜杠,更像其他语言中的正则表达式,更容易看得明白,所以"\v"模式很好用.

关于"\m", "\v"二种模式的比较说明,摘自帮助手册,移除了"\M", "\V"部分,只要掌握好前面的二种模式就已经够用.


\v \m matches
$ $ matches end-of-line
. . matches any character
* * any number of the previous atom
() \(\) grouping into an atom
| \| separating alternatives
\a \a alphabetic character
\\ \\ literal backslash
\. \. literal dot
\{ { literal '{'
a a literal 'a'

对于这二种模式而言,"\a"都是代表字母,其中需要注意的是"\m"中的"|"(或分隔符)需要转义,这个与linux中的grep命令一样,另外其 "(", ")", "{" 这三个字符也需要转义,但是对于"\m"模式, "}"却可以无需转义(The } may optionally be preceded with a backslash: \{n,m\}),所以在"\m"模式中写出来的没有"\v"中的正则表达式更加整齐好明白,下面提到的非贪婪匹配正是与 "{", "}"这对花括号有关.

非贪婪匹配写法


VIM中的匹配1个或者更多相同字符的"+",在magic模式下需要转义,即用"\+"表示.如"\w\+"匹配一个或者一个以上的字母数字或者下划线."\+"和"*"一样是贪婪匹配的.

可以通过":h non-greedy"查看非贪婪匹配的写法.只能在"\m"模式下进行非贪婪匹配,使用".\{-}"进行最小匹配,如果写整齐点也可以用".\{-\}"来表示,如"pa.\{-\}n"可以匹配到"pattern"或者是"pan".摘录帮助手册中关于贪婪/非贪婪匹配说明如下(magic模式):

\{n,m} Matches n to m of the preceding atom, as many as possible
\{n} Matches n of the preceding atom
\{n,} Matches at least n of the preceding atom, as many as possible
\{,m} Matches 0 to m of the preceding atom, as many as possible
\{} Matches 0 or more of the preceding atom, as many as possible (like *)
\{-n,m} Matches n to m of the preceding atom, as few as possible
\{-n} Matches n of the preceding atom
\{-n,} Matches at least n of the preceding atom, as few as possible
\{-,m} Matches 0 to m of the preceding atom, as few as possible
\{-} Matches 0 or more of the preceding atom, as few as possible

匹配包括换号符在内的任意字符


如果匹配内容有换行符,用通配符"."不能匹配换行符,在其他语言如perl/php/javascript是用"/m"修饰符让"."可以匹配字符串内的换行符,VIM中是用一个转义的下划线"\_"加上"."组成的"\_."来表示包括换行符在内的任意字符,与此效果相似的还有"\_^", "\_$", "\_s".关于VIM和perl的正则表达式区别可以通过":h perl-patterns"查看更详细的说明.

字符类(Character classes)


摘录部分常用的字符类如下,这部分多数与其他语言相似,其他很多字符类与别的语言中的字符类完全不一样,并且大小写的字符集不是取反的字符集,如"\i",就不作记录说明.另外如果需要忽略大小写,可查看":h /ignorecase", 在任何位置加入"\c"标记开始忽略字母的大小写.

\s whitespace character: <Space> and <Tab>
\S non-whitespace character; opposite of \s
\d digit: [0-9]
\D non-digit: [^0-9]
\w word character: [0-9A-Za-z_]
\W non-word character: [^0-9A-Za-z_]
\a alphabetic character: [A-Za-z]
\A non-alphabetic character: [^A-Za-z]
\l lowercase character: [a-z]
\u uppercase character: [A-Z]
\t matches <Tab>
\r matches <CR>
\n matches an end-of-line
\1 Matches the same string that was matched by the first sub-expression in \( and \). Example: "\([a-z]\).\1" matches "ata", "ehe", "tot", etc.

关于VIM中的[](:h /collection)


在其他语言中perl/javascript/ruby中,方括号可以使用转义字符代替的字符集,如"\s", "\w"等,在VIM中只能在方括号中使用字符序列,也可以像其他编程语言一样放入"a-z", "0-9"等,但不能用转义字符,这点在使用时比较不顺手.

以上是个人认为比较常用并且较为简单的部分内容,更多神奇的VIM正则查找,以及结合一些VIM内置方法进行正则替换,则需要仔细阅读帮助手册说明.要熟练掌握VIM,就需要多查手册,多实践.

Friday, October 08, 2010

个人一直使用的一套ubuntu主题

http://www.bisigi-project.org/?page_id=8&lang=en上下载安装,在ubuntu上用apt-get安装很简单:

$>
sudo add-apt-repository ppa:bisigi/ppa && sudo apt-get update
$> sudo aptitude install showtime-theme

其他更多主题可以选择,都很不错.

ubuntu 10.10 自带的Ambiance配合mac4Lin的emerald主题也很酷.

Friday, October 01, 2010

vim中匹配换行符的正则表达式

\s* 匹配0或多个空白(比如空格,Tab等,不匹配换行)
VIM里面,如果要连换行一起匹配,则加个下划线,比如\_s匹配包括换行在内的空白,而\_.匹配包括换行在内的任意字符 (注意,后面有个小数点)

References:
VIM正则表达式查找替换

Ubuntu下Nvidia显卡不定时闪屏的解决

解决方法:

在配置文件中添加一行:
$> sudo vi /etc/modprobe.d/nvidia-kernel-nkc
options nvidia NVreg_Mobile=1 NVreg_RegistryDwords="PerfLevelSrc=0x2222"

更多信息可查看ubuntu的bug list:Occasional screen-wide "blink" when using opengl apps (compiz also) and Nvidia cards

References:
[分享]解决Nvidia显卡不定时闪屏问题