Friday, 29 February 2008

IT guys recycle


USB Pottery Wheel - Click here for more home videos

Earthquake of England

I experienced......
clipped from news.bbc.co.uk

Earthquake felt across much of UK
The biggest earthquake in the UK for nearly 25 years has shaken homes across large parts of the country.
Kleber Afonso surveys the damage to his home in South Yorkshire
People in Newcastle, Yorkshire, London, Cumbria, the Midlands, Norfolk and also parts of Wales, felt the tremor just before 0100 GMT.
A man suffered a broken pelvis when a chimney collapsed in South Yorkshire.
The British Geological Survey (BGS) said the epicentre of the 5.2 magnitude quake was near Market Rasen in Lincolnshire.
Davie Galloway, seismologist for the BGS, said people had reported feeling the tremor from as far as Bangor in Northern Ireland to the west, Haarlem in Holland to the east, Plymouth to the south and Edinburgh to the north.
Student David Bates, 19, suffered a broken pelvis when he was pinned under masonry in his attic bedroom in Barnsley Road, Wombwell, South Yorks.
His father Paul Bates said: "There was a rumble and then we heard a bang and my son screaming 'Dad'."
His son was taken to hospital and was due to undergo surgery later.

make your website rss activated

To use such a tag in your html:

<LINK REL="alternate" TITLE="Shared RSS" href="http://www.....rss" TYPE="application/rss+xml">

HTML <link> tag


Definition and Usage

This element defines the relationship between two linked documents.

Details are on: http://www.w3schools.com/tags/tag_link.asp


java download file program

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class downloadit {

/**
* @param args
*/
public static void main(String[] args) {
// // TODO Auto-generated method stub
// URL url = new URL("http://pagead2.googlesyndication.com/pagead/show_ads.js");
// BufferedReader br = new BufferedReader(new InputStream(url));
//// new BufferReader (new InputStremReader());

OutputStream out;
URLConnection conn;
InputStream in;
try {
String address = "http://pagead2.googlesyndication.com/pagead/show_ads.js";
String localFileName = "downloaed";
URL url = new URL(address);
out = new BufferedOutputStream(
new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
}
System.out.println(localFileName + "\t" + numWritten);
} catch (Exception exception) {
exception.printStackTrace();
}

}

}

Rss server generate whole rss feed from separate rss files

import javax.xml.parsers.*;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

import java.io.File;

/*
* This is a java program to accumulate all
* xml files in some specific directory into
* one xml file, in this case it's much easier
* to maintain the xml server file system and
* provide costumers the xml file they need.
*
* Author: Cross
*/

public class domjaxp {

public static void main(String[] args) {

try {
// Jaxp: create a parser/builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();

// Create the new xml file to accumulate all separate xml file into this one.
Document newdoc = parser.newDocument();

// As rss, Create the root tag, which is <rss>......</rss>
Element newrss = newdoc.createElement("rss");
newrss.setAttribute("version", "2.0");
newdoc.appendChild(newrss);

// As rss, under the root (rss), you must have a channel as a news provider
Element newchannel = newdoc.createElement("channel");
newrss.appendChild(newchannel);

// Basic information of the channel.
Element newtitle = newdoc.createElement("title");
newtitle.setTextContent("ANP unit");
Element newlink = newdoc.createElement("link");
newlink.setTextContent("http://blackboard.lsbu.ac.uk/webapps/portal/frameset.jsp?tab=courses&url=/bin/common/course.pl?course_id=_52692_1");
Element newdescription = newdoc.createElement("description");
newdescription.setTextContent("A rss feed example for ANP unit");

newchannel.appendChild(newtitle);
newchannel.appendChild(newlink);
newchannel.appendChild(newdescription);

// Goto the folder to retrive all the separate rss/xml files.
String path = "src"; // change to your path, here src is used in Eclipse.
File dir = new File(path);
String[] mylist=dir.list(); // Scan the path find the files in it.

// Start to parse each rss/xml file.
for (int i=0;i<mylist.length;i++)
{
String filename = "src\\"+mylist[i];
if (filename.endsWith(".rss")){
System.out.println(filename);

try {
// parse the rss file.
Document d = parser.parse(new File(filename));

// Because we have known the tag name we need, so go for it directly.
NodeList itemlevellist = d.getElementsByTagName("item");

// Get the element of item, which is the story in the rss.
Element itemelement = (Element) itemlevellist.item(0);

// Attach this item into the new xml Document. P.s.: you must import the node.
Node importednode = newdoc.importNode(itemelement, true);
newchannel.appendChild(importednode);

} catch (Exception e) {
e.printStackTrace();
}

} // end if
} // end for

// output the xml document to a new xml file.
try {
File file = new File("newxml.rss");

// DOM dcoument can not be outpur directly, you should make it as a kind of source.
Source source = new DOMSource(newdoc);

// Create file, you must have a kind of stream.
Result result = new StreamResult(file);

// Transformer can make the DOM document source to a file.
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);

} catch (Exception e) {
e.printStackTrace();
}
} // end try
catch (Exception e) {
e.printStackTrace();
}
} // end main
}

Thursday, 28 February 2008

Javascript fundemental

JavaScript就这么回事1:基础知识

1 创建脚本块

1: <script language=”JavaScript”>
2: JavaScript code goes here
3: </script>



2 隐藏脚本代码

1: <script language=”JavaScript”>
2: <!--
3: document.write(“Hello”);
4: // -->
5: </script>


在不支持JavaScript的浏览器中将不执行相关代码

3 浏览器不支持的时候显示

1: <noscript>
2: Hello to the non-JavaScript browser.
3: </noscript>



4 链接外部脚本文件

1: <script language=”JavaScript” src="/”filename.js"”></script>


5 注释脚本

1: // This is a comment
2: document.write(“Hello”); // This is a comment
3: /*
4: All of this
5: is a comment
6: */



6 输出到浏览器

1: document.write(“<strong>Hello</strong>”);



7 定义变量

1: var myVariable = “some value”;



8 字符串相加

1: var myString = “String1” + “String2”;



9 字符串搜索

1: <script language=”JavaScript”>
2: <!--
3: var myVariable = “Hello there”;
4: var therePlace = myVariable.search(“there”);
5: document.write(therePlace);
6: // -->
7: </script>



10 字符串替换

1: thisVar.replace(“Monday”,”Friday”);


11 格式化字串

1: <script language=”JavaScript”>
2: <!--
3: var myVariable = “Hello there”;
4: document.write(myVariable.big() + “<br>”);
5: document.write(myVariable.blink() + “<br>”);
6: document.write(myVariable.bold() + “<br>”);
7: document.write(myVariable.fixed() + “<br>”);
8: document.write(myVariable.fontcolor(“red”) + “<br>”);
9: document.write(myVariable.fontsize(“18pt”) + “<br>”);
10: document.write(myVariable.italics() + “<br>”);
11: document.write(myVariable.small() + “<br>”);
12: document.write(myVariable.strike() + “<br>”);
13: document.write(myVariable.sub() + “<br>”);
14: document.write(myVariable.sup() + “<br>”);
15: document.write(myVariable.toLowerCase() + “<br>”);
16: document.write(myVariable.toUpperCase() + “<br>”);
17:
18: var firstString = “My String”;
19: var finalString = firstString.bold().toLowerCase().fontcolor(“red”);
20: // -->
21: </script>



12 创建数组

1: <script language=”JavaScript”>
2: <!--
3: var myArray = new Array(5);
4: myArray[0] = “First Entry”;
5: myArray[1] = “Second Entry”;
6: myArray[2] = “Third Entry”;
7: myArray[3] = “Fourth Entry”;
8: myArray[4] = “Fifth Entry”;
9: var anotherArray = new Array(“First Entry”,”Second Entry”,”Third Entry”,”Fourth Entry”,”Fifth Entry”);
10: // -->
11: </script>



13 数组排序

1: <script language=”JavaScript”>
2: <!--
3: var myArray = new Array(5);
4: myArray[0] = “z”;
5: myArray[1] = “c”;
6: myArray[2] = “d”;
7: myArray[3] = “a”;
8: myArray[4] = “q”;
9: document.write(myArray.sort());
10: // -->
11: </script>



14 分割字符串

1: <script language=”JavaScript”>
2: <!--
3: var myVariable = “a,b,c,d”;
4: var stringArray = myVariable.split(“,”);
5: document.write(stringArray[0]);
6: document.write(stringArray[1]);
7: document.write(stringArray[2]);
8: document.write(stringArray[3]);
9: // -->
10: </script>



15 弹出警告信息

1: <script language=”JavaScript”>
2: <!--
3: window.alert(“Hello”);
4: // -->
5: </script>



16 弹出确认框

1: <script language=”JavaScript”>
2: <!--
3: var result = window.confirm(“Click OK to continue”);
4: // -->
5: </script>



17 定义函数

1: <script language=”JavaScript”>
2: <!--
3: function multiple(number1,number2) {
4: var result = number1 * number2;
5: return result;
6: }
7: // -->
8: </script>



18 调用JS函数

1: <a href=”#” onClick=”functionName()”>Link text</a>
2: <a href="/”javascript:functionName"()”>Link text</a>



19 在页面加载完成后执行函数

1: <body onLoad=”functionName();”>
2: Body of the page
3: </body>


20 条件判断

1: <script>
2: <!--
3: var userChoice = window.confirm(“Choose OK or Cancel”);
4: var result = (userChoice == true) ? “OK” : “Cancel”;
5: document.write(result);
6: // -->
7: </script>



21 指定次数循环

1: <script>
2: <!--
3: var myArray = new Array(3);
4: myArray[0] = “Item 0”;
5: myArray[1] = “Item 1”;
6: myArray[2] = “Item 2”;
7: for (i = 0; i < myArray.length; i++) {
8: document.write(myArray[i] + “<br>”);
9: }
10: // -->
11: </script>



22 设定将来执行

1: <script>
2: <!--
3: function hello() {
4: window.alert(“Hello”);
5: }
6: window.setTimeout(“hello()”,5000);
7: // -->
8: </script>



23 定时执行函数

1: <script>
2: <!--
3: function hello() {
4: window.alert(“Hello”);
5: window.setTimeout(“hello()”,5000);
6: }
7: window.setTimeout(“hello()”,5000);
8: // -->
9: </script>



24 取消定时执行

1: <script>
2: <!--
3: function hello() {
4: window.alert(“Hello”);
5: }
6: var myTimeout = window.setTimeout(“hello()”,5000);
7: window.clearTimeout(myTimeout);
8: // -->
9: </script>



25 在页面卸载时候执行函数

1: <body onUnload=”functionName();”>
2: Body of the page
3: </body>

JavaScript就这么回事2:浏览器输出


26 访问document对象

1: <script language=”JavaScript”>
2: var myURL = document.URL;
3: window.alert(myURL);
4: </script>



27 动态输出HTML

1: <script language=”JavaScript”>
2: document.write(“<p>Here’s some information about this document:</p>”);
3: document.write(“<ul>”);
4: document.write(“<li>Referring Document: “ + document.referrer + “</li>”);
5: document.write(“<li>Domain: “ + document.domain + “</li>”);
6: document.write(“<li>URL: “ + document.URL + “</li>”);
7: document.write(“</ul>”);
8: </script>


28 输出换行

1: document.writeln(“<strong>a</strong>”);
2: document.writeln(“b”);



29 输出日期

1: <script language=”JavaScript”>
2: var thisDate = new Date();
3: document.write(thisDate.toString());
4: </script>



30 指定日期的时区

1: <script language=”JavaScript”>
2: var myOffset = -2;
3: var currentDate = new Date();
4: var userOffset = currentDate.getTimezoneOffset()/60;
5: var timeZoneDifference = userOffset - myOffset;
6: currentDate.setHours(currentDate.getHours() + timeZoneDifference);
7: document.write(“The time and date in Central Europe is: “ + currentDate.toLocaleString());
8: </script>


31 设置日期输出格式

1: <script language=”JavaScript”>
2: var thisDate = new Date();
3: var thisTimeString = thisDate.getHours() + “:” + thisDate.getMinutes();
4: var thisDateString = thisDate.getFullYear() + “/” + thisDate.getMonth() + “/” + thisDate.getDate();
5: document.write(thisTimeString + “ on “ + thisDateString);
6: </script>


32 读取URL参数

1: <script language=”JavaScript”>
2: var urlParts = document.URL.split(“?”);
3: var parameterParts = urlParts[1].split(“&”);
4: for (i = 0; i < parameterParts.length; i++) {
5: var pairParts = parameterParts[i].split(“=”);
6: var pairName = pairParts[0];
7: var pairValue = pairParts[1];
8: document.write(pairName + “ :“ +pairValue );
9: }
10: </script>

你还以为HTML是无状态的么?

33 打开一个新的document对象

1: <script language=”JavaScript”>
2: function newDocument() {
3: document.open();
4: document.write(“<p>This is a New Document.</p>”);
5: document.close();
6: }
7: </script>



34 页面跳转

1: <script language=”JavaScript”>
2: window.location = “http://www.liu21st.com/”;
3: </script>



35 添加网页加载进度窗口

1: <html>
2: <head>
3: <script language='javaScript'>
4: var placeHolder = window.open('holder.html','placeholder','width=200,height=200');
5: </script>
6: <title>The Main Page</title>
7: </head>
8: <body onLoad='placeHolder.close()'>
9: <p>This is the main page</p>
10: </body>
11: </html>



JavaScript就这么回事3:图像



36 读取图像属性

1: <img src="/”image1.jpg"” name=”myImage”>
2: <a href=”# ” onClick=”window.alert(document.myImage.width)”>Width</a>
3:


37 动态加载图像

1: <script language=”JavaScript”>
2: myImage = new Image;
3: myImage.src = “Tellers1.jpg”;
4: </script>


38 简单的图像替换

1: <script language=”JavaScript”>
2: rollImage = new Image;
3: rollImage.src = “rollImage1.jpg”;
4: defaultImage = new Image;
5: defaultImage.src = “image1.jpg”;
6: </script>
7: <a href="/”myUrl"” onMouseOver=”document.myImage.src = rollImage.src;”
8: onMouseOut=”document.myImage.src = defaultImage.src;”>
9: <img src="/”image1.jpg"” name=”myImage” width=100 height=100 border=0>


39 随机显示图像

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = “image1.jpg”;
4: imageList[1] = “image2.jpg”;
5: imageList[2] = “image3.jpg”;
6: imageList[3] = “image4.jpg”;
7: var imageChoice = Math.floor(Math.random() * imageList.length);
8: document.write(‘<img src=”’ + imageList[imageChoice] + ‘“>’);
9: </script>


40 函数实现的图像替换

1: <script language=”JavaScript”>
2: var source = 0;
3: var replacement = 1;
4: function createRollOver(originalImage,replacementImage) {
5: var imageArray = new Array;
6: imageArray[source] = new Image;
7: imageArray[source].src = originalImage;
8: imageArray[replacement] = new Image;
9: imageArray[replacement].src = replacementImage;
10: return imageArray;
11: }
12: var rollImage1 = createRollOver(“image1.jpg”,”rollImage1.jpg”);
13: </script>
14: <a href=”#” onMouseOver=”document.myImage1.src = rollImage1[replacement].src;”
15: onMouseOut=”document.myImage1.src = rollImage1[source].src;”>
16: <img src="/”image1.jpg"” width=100 name=”myImage1” border=0>
17: </a>


41 创建幻灯片

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = new Image;
4: imageList[0].src = “image1.jpg”;
5: imageList[1] = new Image;
6: imageList[1].src = “image2.jpg”;
7: imageList[2] = new Image;
8: imageList[2].src = “image3.jpg”;
9: imageList[3] = new Image;
10: imageList[3].src = “image4.jpg”;
11: function slideShow(imageNumber) {
12: document.slideShow.src = imageList[imageNumber].src;
13: imageNumber += 1;
14: if (imageNumber < imageList.length) {
15: window.setTimeout(“slideShow(“ + imageNumber + “)”,3000);
16: }
17: }
18: </script>
19: </head>
20: <body onLoad=”slideShow(0)”>
21: <img src="/”image1.jpg"” width=100 name=”slideShow”>


42 随机广告图片

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = “image1.jpg”;
4: imageList[1] = “image2.jpg”;
5: imageList[2] = “image3.jpg”;
6: imageList[3] = “image4.jpg”;
7: var urlList = new Array;
8: urlList[0] = “http://some.host/”;
9: urlList[1] = “http://another.host/”;
10: urlList[2] = “http://somewhere.else/”;
11: urlList[3] = “http://right.here/”;
12: var imageChoice = Math.floor(Math.random() * imageList.length);
13: document.write(‘<a href=”’ + urlList[imageChoice] + ‘“><img src=”’ + imageList[imageChoice] + ‘“></a>’);
14: </script>

JavaScript就这么回事4:表单


还是先继续写完JS就这么回事系列吧~
43 表单构成

1: <form method=”post” action=”target.html” name=”thisForm”>
2: <input type=”text” name=”myText”>
3: <select name=”mySelect”>
4: <option value=”1”>First Choice</option>
5: <option value=”2”>Second Choice</option>
6: </select>
7: <br>
8: <input type=”submit” value=”Submit Me”>
9: </form>


44 访问表单中的文本框内容

1: <form name=”myForm”>
2: <input type=”text” name=”myText”>
3: </form>
4: <a href='#' onClick='window.alert(document.myForm.myText.value);'>Check Text Field</a>


45 动态复制文本框内容

1: <form name=”myForm”>
2: Enter some Text: <input type=”text” name=”myText”><br>
3: Copy Text: <input type=”text” name=”copyText”>
4: </form>
5: <a href=”#” onClick=”document.myForm.copyText.value =
6: document.myForm.myText.value;”>Copy Text Field</a>


46 侦测文本框的变化

1: <form name=”myForm”>
2: Enter some Text: <input type=”text” name=”myText” onChange=”alert(this.value);”>
3: </form>


47 访问选中的Select

1: <form name=”myForm”>
2: <select name=”mySelect”>
3: <option value=”First Choice”>1</option>
4: <option value=”Second Choice”>2</option>
5: <option value=”Third Choice”>3</option>
6: </select>
7: </form>
8: <a href='#' onClick='alert(document.myForm.mySelect.value);'>Check Selection List</a>


48 动态增加Select项

1: <form name=”myForm”>
2: <select name=”mySelect”>
3: <option value=”First Choice”>1</option>
4: <option value=”Second Choice”>2</option>
5: </select>
6: </form>
7: <script language=”JavaScript”>
8: document.myForm.mySelect.length++;
9: document.myForm.mySelect.options[document.myForm.mySelect.length - 1].text = “3”;
10: document.myForm.mySelect.options[document.myForm.mySelect.length - 1].value = “Third Choice”;
11: </script>


49 验证表单字段

1: <script language=”JavaScript”>
2: function checkField(field) {
3: if (field.value == “”) {
4: window.alert(“You must enter a value in the field”);
5: field.focus();
6: }
7: }
8: </script>
9: <form name=”myForm” action=”target.html”>
10: Text Field: <input type=”text” name=”myField”onBlur=”checkField(this)”>
11: <br><input type=”submit”>
12: </form>


50 验证Select项

1: function checkList(selection) {
2: if (selection.length == 0) {
3: window.alert(“You must make a selection from the list.”);
4: return false;
5: }
6: return true;
7: }


51 动态改变表单的action

1: <form name=”myForm” action=”login.html”>
2: Username: <input type=”text” name=”username”><br>
3: Password: <input type=”password” name=”password”><br>
4: <input type=”button” value=”Login” onClick=”this.form.submit();”>
5: <input type=”button” value=”Register” onClick=”this.form.action = ‘register.html’; this.form.submit();”>
6: <input type=”button” value=”Retrieve Password” onClick=”this.form.action = ‘password.html’; this.form.submit();”>
7: </form>


52 使用图像按钮

1: <form name=”myForm” action=”login.html”>
2: Username: <input type=”text” name=”username”><br>
3: Password: <input type=”password”name=”password”><br>
4: <input type=”image” src="/”login.gif"” value=”Login”>
5: </form>
6:


53 表单数据的加密

1: <SCRIPT LANGUAGE='JavaScript'>
2: <!--
3: function encrypt(item) {
4: var newItem = '';
5: for (i=0; i < item.length; i++) {
6: newItem += item.charCodeAt(i) + '.';
7: }
8: return newItem;
9: }
10: function encryptForm(myForm) {
11: for (i=0; i < myForm.elements.length; i++) {
12: myForm.elements[i].value = encrypt(myForm.elements[i].value);
13: }
14: }
15:
16: //-->
17: </SCRIPT>
18: <form name='myForm' onSubmit='encryptForm(this); window.alert(this.myField.value);'>
19: Enter Some Text: <input type=text name=myField><input type=submit>
20: </form>




JavaScript就这么回事5:窗口和框架


54 改变浏览器状态栏文字提示

1: <script language=”JavaScript”>
2: window.status = “A new status message”;
3: </script>


55 弹出确认提示框

1: <script language=”JavaScript”>
2: var userChoice = window.confirm(“Click OK or Cancel”);
3: if (userChoice) {
4: document.write(“You chose OK”);
5: } else {
6: document.write(“You chose Cancel”);
7: }
8: </script>


56 提示输入

1: <script language=”JavaScript”>
2: var userName = window.prompt(“Please Enter Your Name”,”Enter Your Name Here”);
3: document.write(“Your Name is “ + userName);
4: </script>


57 打开一个新窗口

1: //打开一个名称为myNewWindow的浏览器新窗口
2: <script language=”JavaScript”>
3: window.open(“http://www.liu21st.com/”,”myNewWindow”);
4: </script>


58 设置新窗口的大小

1: <script language=”JavaScript”>
2: window.open(“http://www.liu21st.com/”,”myNewWindow”,'height=300,width=300');
3: </script>


59 设置新窗口的位置

1: <script language=”JavaScript”>
2: window.open(“http://www.liu21st.com/”,”myNewWindow”,'height=300,width=300,left=200,screenX=200,top=100,screenY=100');
3: </script>


60 是否显示工具栏和滚动栏

1: <script language=”JavaScript”>
2: window.open(“http:


61 是否可以缩放新窗口的大小

1: <script language=”JavaScript”>
2: window.open('http://www.liu21st.com/' , 'myNewWindow', 'resizable=yes' );</script>


62 加载一个新的文档到当前窗口

1: <a href='#' onClick='document.location = '125a.html';' >Open New Document</a>


63 设置页面的滚动位置

1: <script language=”JavaScript”>
2: if (document.all) { //如果是IE浏览器则使用scrollTop属性
3: document.body.scrollTop = 200;
4: } else { //如果是NetScape浏览器则使用pageYOffset属性
5: window.pageYOffset = 200;
6: }</script>


64 在IE中打开全屏窗口

1: <a href='#' onClick=”window.open('http://www.juxta.com/','newWindow','fullScreen=yes');”>Open a full-screen window</a>


65 新窗口和父窗口的操作

1: <script language=”JavaScript”>
2: //定义新窗口
3: var newWindow = window.open(“128a.html”,”newWindow”);
4: newWindow.close(); //在父窗口中关闭打开的新窗口
5: </script>
6: 在新窗口中关闭父窗口
7: window.opener.close()


66 往新窗口中写内容

1: <script language=”JavaScript”>
2: var newWindow = window.open(“”,”newWindow”);
3: newWindow.document.open();
4: newWindow.document.write(“This is a new window”);
5: newWIndow.document.close();
6: </script>


67 加载页面到框架页面

1: <frameset cols=”50%,*”>
2: <frame name=”frame1” src="/”135a.html"”>
3: <frame name=”frame2” src="/”about:blank"”>
4: </frameset>
5: 在frame1中加载frame2中的页面
6: parent.frame2.document.location = “135b.html”;


68 在框架页面之间共享脚本
如果在frame1中html文件中有个脚本

1: function doAlert() {
2: window.alert(“Frame 1 is loaded”);
3: }

那么在frame2中可以如此调用该方法

1: <body onLoad=”parent.frame1.doAlert();”>
2: This is frame 2.
3: </body>


69 数据公用
可以在框架页面定义数据项,使得该数据可以被多个框架中的页面公用

1: <script language=”JavaScript”>
2: var persistentVariable = “This is a persistent value”;
3: </script>
4: <frameset cols=”50%,*”>
5: <frame name=”frame1” src="/”138a.html"”>
6: <frame name=”frame2” src="/”138b.html"”>
7: </frameset>


这样在frame1和frame2中都可以使用变量persistentVariable
70 框架代码库
根据以上的一些思路,我们可以使用一个隐藏的框架页面来作为整个框架集的代码库

1: <frameset cols=”0,50%,*”>
2: <frame name=”codeFrame” src="/”140code.html"”>
3: <frame name=”frame1” src="/”140a.html"”>
4: <frame name=”frame2” src="/”140b.html"”>
5: </frameset>

java文件操作

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class FileOperate {
private String message;
public FileOperate() {
}

/**
* 读取文本文件内容
* @param filePathAndName 带有完整绝对路径的文件名
* @param encoding 文本文件打开的编码方式
* @return 返回文本文件的内容
*/

public String readTxt(String filePathAndName,String encoding) throws IOException{
encoding = encoding.trim();
StringBuffer str = new StringBuffer("");
String st = "";
try{
FileInputStream fs = new FileInputStream(filePathAndName);
InputStreamReader isr;
if(encoding.equals("")){
isr = new InputStreamReader(fs);
}else{
isr = new InputStreamReader(fs,encoding);
}
BufferedReader br = new BufferedReader(isr);
try{
String data = "";
while((data = br.readLine())!=null){
str.append(data+" ");
}
}catch(Exception e){
str.append(e.toString());
}
st = str.toString();
}catch(IOException es){
st = "";
}
return st;
}

/**
* 新建目录
* @param folderPath 目录
* @return 返回目录创建后的路径
*/

public String createFolder(String folderPath) {
String txt = folderPath;
try {
java.io.File myFilePath = new java.io.File(txt);
txt = folderPath;
if (!myFilePath.exists()) {
myFilePath.mkdir();
}
}
catch (Exception e) {
message = "创建目录操作出错";
}
return txt;
}

/**
* 多级目录创建
* @param folderPath 准备要在本级目录下创建新目录的目录路径 例如 c:myf
* @param paths 无限级目录参数,各级目录以单数线区分 例如 a|b|c
* @return 返回创建文件后的路径 例如 c:myfac
*/

public String createFolders(String folderPath, String paths){
String txts = folderPath;
try{
String txt;
txts = folderPath;
StringTokenizer st = new StringTokenizer(paths,"|");
for(int i=0; st.hasMoreTokens(); i++){
txt = st.nextToken().trim();
if(txts.lastIndexOf("/")!=-1){
txts = createFolder(txts+txt);
}else{
txts = createFolder(txts+txt+"/");
}
}
}catch(Exception e){
message = "创建目录操作出错!";
}
return txts;
}


/**
* 新建文件
* @param filePathAndName 文本文件完整绝对路径及文件名
* @param fileContent 文本文件内容
* @return
*/

public void createFile(String filePathAndName, String fileContent) {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
resultFile.close();
}
catch (Exception e) {
message = "创建文件操作出错";
}
}


/**
* 有编码方式的文件创建
* @param filePathAndName 文本文件完整绝对路径及文件名
* @param fileContent 文本文件内容
* @param encoding 编码方式 例如 GBK 或者 UTF-8
* @return
*/

public void createFile(String filePathAndName, String fileContent, String encoding) {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
PrintWriter myFile = new PrintWriter(myFilePath,encoding);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
}
catch (Exception e) {
message = "创建文件操作出错";
}
}


/**
* 删除文件
* @param filePathAndName 文本文件完整绝对路径及文件名
* @return Boolean 成功删除返回true遭遇异常返回false
*/

public boolean delFile(String filePathAndName) {
boolean bea = false;
try {
String filePath = filePathAndName;
File myDelFile = new File(filePath);
if(myDelFile.exists()){
myDelFile.delete();
bea = true;
}else{
bea = false;
message = (filePathAndName+"
删除文件操作出错");
}
}
catch (Exception e) {
message = e.toString();
}
return bea;
}


/**
* 删除文件夹
* @param folderPath 文件夹完整绝对路径
* @return
*/

public void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹
}
catch (Exception e) {
message = ("删除文件夹操作出错");
}
}


/**
* 删除指定文件夹下所有文件
* @param path 文件夹完整绝对路径
* @return
* @return
*/

public boolean delAllFile(String path) {
boolean bea = false;
File file = new File(path);
if (!file.exists()) {
return bea;
}
if (!file.isDirectory()) {
return bea;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
}else{
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
delFolder(path+"/"+ tempList[i]);//再删除空文件夹
bea = true;
}
}
return bea;
}


/**
* 复制单个文件
* @param oldPathFile 准备复制的文件源
* @param newPathFile 拷贝到新绝对路径带文件名
* @return
*/

public void copyFile(String oldPathFile, String newPathFile) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPathFile);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPathFile); //读入原文件
FileOutputStream fs = new FileOutputStream(newPathFile);
byte[] buffer = new byte[1444];
while((byteread = inStream.read(buffer)) != -1){
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}catch (Exception e) {
message = ("复制单个文件操作出错");
}
}

/**
* 复制整个文件夹的内容
* @param oldPath 准备拷贝的目录
* @param newPath 指定绝对路径的新目录
* @return
*/

public void copyFolder(String oldPath, String newPath) {
try {
new File(newPath).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}else{
temp=new File(oldPath+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}catch (Exception e) {
message = "复制整个文件夹内容操作出错";
}
}


/**
* 移动文件
* @param oldPath
* @param newPath
* @return
*/

public void moveFile(String oldPath, String newPath) {
copyFile(oldPath, newPath);
delFile(oldPath);
}

/**
* 移动目录
* @param oldPath
* @param newPath
* @return
*/

public void moveFolder(String oldPath, String newPath) {
copyFolder(oldPath, newPath);
delFolder(oldPath);
}
public String getMessage(){
return this.message;
}
}

simple DTD file

Following codes are a kind of INTERNAL SUBSET DTD style <


< !DOCTYPE people_list[
< !ELEMENT people_list (person*)>
< !ELEMENT person (name, birthdate?, gender?, socialsecuritynumber?)>
< !ELEMENT name (#PCDATA)>
< !ELEMENT birthdate (#PCDATA)>
< !ELEMENT gender (#PCDATA)>
< !ELEMENT socialsecuritynumber (#PCDATA)>]>



Fred Bloggs
27/11/2008
Male


#############################################


Following codes are a kind of EXTERNAL SUBSET DTD style,which includes 2 separate files.<

1. xml file:


< !DOCTYPE people_list SYSTEM "example.dtd">


Fred Bloggs
27/11/2008
Male




2. dtd file:

< !ELEMENT people_list (person*)>
< !ELEMENT person (name, birthdate?, gender?, socialsecuritynumber?)>
< !ELEMENT name (#PCDATA)>
< !ELEMENT birthdate (#PCDATA)>
< !ELEMENT gender (#PCDATA)>
< !ELEMENT socialsecuritynumber (#PCDATA)>

Tuesday, 26 February 2008

about mount

The programs mount and umount maintain a list of currently mounted file systems in the file /etc/mtab. If no arguments are given tomount, this list is printed.


mount options:
user
Allow an ordinary user to mount the file system. The name of the mounting user is written to mtab so that he can unmount the file system again. This option implies the options noexec, nosuid, and nodev (unless overridden by subsequent options, as in the option line user,exec,dev,suid).



/etc/fstab
file system table
/etc/mtab
table of mounted file systems
/etc/mtab~
lock file
/etc/mtab.tmp
temporary file
/etc/filesystems
a list of filesystem types
========================
Some time, the mounted device or img can not pass fsck, which is determined by the sixth of /etc/fstab option. / as root should be 1-the first device to mount and check, other device should be 2, while partition or img from other device can be 1 too as start parallelism. If error occurs, the boot will be suspended.

To avoid this, you can mark the sixth option as 0. BUT SOME TIME, for example, if you mount it to /home, while some scripts from /home has been running, the mount will not be done.

1. So keep pass option (sixth option in /etc/fstab) 0, and add it manually to /etc/mtab, for example, "/dev/cobd2 /home ext3 sw 0 0". In this case, no suspend when mounting in the boot process.
2. Alternatively, mount command can be put in /etc/rc.local, same effect with above one.



Linux boot sequence

Boot Sequence
1. bootloader
2. linux kernel
3. inittab
4. rc script (differs depending on which linux distribution )
==================
1) /etc/passwd
2) /etc/shadow
3) /etc/group

4) /etc/profile
5) /etc/profile.d/*.sh

6) ~/.bash_profile
7) ~/.bashrc
8) /etc/bashrc

===================
Graphical Environment:
/etc/X11/xinit/xinitrc.d/

AddSwapPartition in colinux

  • First, we need a file of predetermined size which will be used as our swap partition.

The size of this file will determine the size of the swap partition. You can create the file manually, or you can download and unzip one of the premade swap files of various sizes provided by &lt;Gniarf&gt; (the filename indicates the size of the unzipped swap file in megabytes).


  • You must declare the file as a virtual partition in your coLinux configuration file (see, for example, the file example.conf included with coLinux).

For example:


cobd1=c:\coLinux\swap-file

(If you are using a version of coLinux older than 0.7.1, then the configuration file is called default.colinux.xml and the format is completely different;
see ConfigurationXMLFormat for details.
The example above, for a coLinux older than 0.7.1, becomes &lt;block_device index="1" path="\DosDevices\c:\coLinux\swap-file" enabled="true" /&gt;.)


  • Boot up coLinux, or reboot if it is already running.

Among the messages the kernel produces, there should be some mention of cobd1,
giving the size of your new (virtual) partition in megabytes.


  • Run ls /dev/cobd1 /dev/cobd/1 to determine which device name your system uses to refer to the swap file.

We will assume in the coming steps that your swap device is /dev/cobd1.


  • You must add an entry to the file /etc/fstab

in your Linux (guest) distribution to declare the swap partition and mount it at each bootup:


/dev/cobd1    swap    swap    defaults    0    0

(Change the name of the device as necessary.)

(Note: Using the Gentoo image, you can install vim
in your running system using the command emerge vim.
But you might want to wait until you have added swap space first;
if so, you can just use the pre-installed editor nano instead.)


  • Initialize the swap partition by running mkswap /dev/cobd1.

(If your swap partition was one of those prepared by &lt;Gniarf&gt;,
this step is probably unnecessary.)


  • Finally, to make use of your swap partition immediately without

rebooting, run swapon -a. You should see a message about
the swap space being added.

Monday, 25 February 2008

java dialog: simplest prompt

String temp = javax.swing.JOptionPane.showInputDialog("Please enter your name: ");

System.out.println(temp);

linux command: dd

虚拟机技术 - 把Linux安装在一个文件中(用dd生成虚拟块设备文件)


第一个问题是:什么是虚拟块设备文件?虚拟块设备文件是本人杜撰的一个名称,该类文件在主机操作系统上是普通文件,在虚拟机中作为一个虚拟块设备,也就是虚拟机中的硬盘。在虚拟机中对虚拟块设备的读写,实际都是对主机上该文件的操作。


虚拟块设备文件更通用的名称是硬盘镜像文件(Hard Disk Image),但不是所有的硬盘镜像文件都是虚拟块设备文件,例如,目前Ghost的GHO格式的镜像文件就不能成为虚拟机中的硬盘。


LInux的dd命令,可以用于生成虚拟块设备文件。既可以用于创建空镜像文件,也可以用于创建物理硬盘的镜像。先看一个实际例子:



# dd if=/dev/hda of=/mnt/nebula/hda_dd.image4757130+0 records in4757130+0 records out



面这个命令将IDE设备/dev/hda的内容复制到/mnt/nebula/hda_dd.image文件。参数if告诉dd从哪个文件读取数据,参数
of告诉dd读出的数据写入哪个文件中。注意,对于dd来说,输入和输出都是文件,dd做的只是文件拷贝工作,这得益于Unix/Linux下面将设备也
抽象为特殊的文件。


一般来说设备文件有两种,一种是块设备,一种是字符设备。块设备的特点是可以随机读写(Random Access),比如内存、硬盘等。字符设备的特点是顺序读写(Sequential Access),比如鼠标,键盘,麦克风等。


前面说了如何生成物理硬盘的镜像,如果想生成空镜像文件(本文的主要目的),还需要一个特殊的设备。/dev/zero是Linux提供的一个特殊的字符设备,它的特点是可以永远读该文件,每次读取的结果都是二进制0。下面的命令可以生成一个100M的空镜像文件:



dd if=/dev/zero of=100M.img bs=1M count=100

100+0 records in

100+0 records out

104857600 bytes (105 MB) copied, 0.18719 seconds, 560 MB/s




了前面已经解释的of和if参数,这次又出现了bs和count参数。bs=1M表示每一次读写1M数据,count=100表示读写100次,
这样就指定了生成文件的大小为100M。bs参数还可以进一步细分为ibs和obs两种,为读操作与写操作分别指定不同的Buffer大小。


这样就生成100M的空镜像文件,问题是,如果要生成1G的虚拟块设备文件,就得占用1G的硬盘空间,而这个镜像文件完全是空的,是不是有一点浪费?好在Linux支持Sparse(稀疏)文件。请看下面的例子




# dd if=/dev/zero of=1G.img bs=1M seek=1000 count=0

0+0 records in

0+0 records out

0 bytes (0 B) copied, 3.3e-05 seconds, 0.0 kB/s


# ls -l 1G.img

-rw-r–r– 1 root root 1048576000 Mar 25 15:32 1G.img


# du -m 1G.img

1 1G.img


这里用了一个新的命令seek,表示略过1000个Block不写(这里Block按照bs的定义是1M),count=0表示写入0个Block。用ls命令看新生成的文件,大小可以看出是1000M。但是再用du一看,实际占用硬盘大小只有1M。

现在为止已经讲解了如何生成空镜像文件,以及如何利用稀疏文件有效减少镜像文件对磁盘空间的占用。



现在让我们在上面建立文件系统,操作很简单:



mkfs.ext2 1G.img



在这儿我选择了ext2磁盘格式,你也可以根据自己的喜好来做

接下来会提示:is not a block special device

按y继续,之后就成功在这个文件中建立了文件系统



之后就是挂载文件系统了,

mount 1G.img /mnt/ -o loop

这样就可以在/mnt/目录下享受你的块文件了,除了能够像普通磁盘一样操作之外,还限定了它的大小只有1G,连磁盘配额都省了!









虚拟机技术的一大特点是封装性(Encapsulation),说的是将整个操作系统装进在文件系统的一个普通文件中。可以在虚拟机中运行该文件中的操作系统。虚拟机能够提供的诸多好处不是本文的重点,就不多说。


很多人可能熟悉用Ghost生成的系统镜像文件,这和虚拟机使用的操作系统镜像文件类似,只不过前者用于恢复真实机器上的操作系统,或用于快速安装多台真实机器,虽然比重装系统方便,却仍然没有后者可利用虚拟机直接运行来的方便快捷。


总的来说,把Linux安装到一个文件中需要5个步骤



我在下面将分别用5篇文章来解释这5个步骤。

Sunday, 24 February 2008

xming address setup

Xming



Reportedly easier to install than Cygwin-Xserver, although with Cygwin you get so many other useful *nix tools.

dieselnutjob: Xming only works with XP, server 2003 or Vista, Windows 2000 isn't supported.

Note that you can still get an old version of Xming that works with Windows 2000 (6.9.0.18). See the Trouble page.

Xming will work with CoLinux with all of the Xming settings set
to default, except that in the Xming installation folder there is a
file called X0.hosts; the IP address of the CoLinux machine must be
added to this file.

Run the XLaunch windows application (comes with Xming) and follow all defaults options.

Now in CoLinux type for example


 export DISPLAY=192.168.0.1:0.0
xterm &

where 192.168.0.1 is the IP address of Windows and provided that you
have xterm installed. You can view the log of Xming to see the IP
address it is currently using.

You should now see an xterm window appear in Windows.

Adding the line


 export DISPLAY=192.168.0.1:0.0

to /etc/profile makes the setting permanent, at least in Debian.

Thursday, 21 February 2008

two ways to synchronized in Java

The following two examples are the classic consumer/producer example of multithread programming. Here I used two ways of invoking synchronized to do such a job.

  1. synchronized method:

    import java.util.*;

    public class Que {

    /**
    * @param args
    */
    public static void main(String[] args) {

    mapQ q = new mapQ();

    new genQ(q);
    new conQ(q);
    }
    }

    ////////////////// the commodity Queue /////////////////
    class mapQ {

    String s;
    LinkedList que = new LinkedList();

    synchronized void put(String s) {

    if (que.size()>10)
    try {
    wait();
    }
    catch(InterruptedException e) {
    System.out.println("InterruptedException caught");
    }
    que.addLast(s);
    System.out.println("Put: " + s);
    notify();
    }

    synchronized String get() {

    if (que.isEmpty())
    try {
    wait();
    }
    catch (InterruptedException e) {
    System.out.println("InterruptedException caught");
    }
    String temps = (String) que.removeFirst();
    // System.out.println(que);
    System.out.println("Got: " + temps);
    notify();

    return temps;
    }
    }

    //////////////// producer /////////////////////
    class genQ implements Runnable {
    mapQ q;

    genQ(mapQ q) {
    this.q=q;
    new Thread(this, "Producer").start();
    }
    public void run() {
    int i=0;

    while(true) {
    int tempi = i++;
    q.put(Integer.toString(tempi));
    }
    }
    }

    /////////////// consumer ///////////////////////
    class conQ implements Runnable {
    mapQ q;

    conQ(mapQ q) {
    this.q=q;
    new Thread(this, "Consumer").start();
    }

    public void run() {
    while(true) {
    q.get();
    }
    }
    }





  2. synchronized block:

    import java.util.*;

    public class Que {

    /**
    * @param args
    */
    public static void main(String[] args) {

    mapQ q = new mapQ();

    new genQ(q);
    new conQ(q);
    }
    }

    ////////////////// the commodity Queue /////////////////
    class mapQ {

    String s;
    LinkedList que = new LinkedList();

    void put(String s) {
    synchronized(que){
    if (que.size()>10)
    try {
    que.wait();
    }
    catch(InterruptedException e) {
    System.out.println("InterruptedException caught");
    }
    System.out.println(que);
    que.addLast(s);
    // System.out.println("Put: " + s);
    que.notify();
    }
    }

    String get() {
    synchronized(que){
    if (que.isEmpty())
    try {
    que.wait();
    }
    catch (InterruptedException e) {
    System.out.println("InterruptedException caught");
    }
    String temps = (String) que.removeFirst();
    // System.out.println("Got: " + temps);
    que.notify();

    return temps;
    }
    }
    }

    //////////////// producer /////////////////////
    class genQ implements Runnable {
    mapQ q;

    genQ(mapQ q) {
    this.q=q;
    new Thread(this, "Producer").start();
    }
    public void run() {
    int i=0;

    while(true) {
    int tempi = i++;
    q.put(Integer.toString(tempi));
    }
    }
    }

    /////////////// consumer ///////////////////////
    class conQ implements Runnable {
    mapQ q;

    conQ(mapQ q) {
    this.q=q;
    new Thread(this, "Consumer").start();
    }

    public void run() {
    while(true) {
    q.get();
    }
    }
    }

###########################################################

P.S.:
The second choice is much clearer and flexible, but you should be careful how to call the wait() and notify(), which should be called by the synchronized object.

java synchronized example

具体到应用比较复杂,举两个例子:
1:

public class Test1 implements Runnable {

public void run() {
synchronized(this) {
try {
System.out.println(System.currentTimeMillis());
Thread.sleep(2000);
System.out.println(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
Test1 test=new Test1();
for(int i=0;i<10;i++) {
new Thread(test).start();
}
}
}


2:
public class Test1 implements Runnable {

public void run() {
synchronized(this) {
try {
System.out.println(System.currentTimeMillis());
Thread.sleep(2000);
System.out.println(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
for(int i=0;i<10;i++) {
new Thread(new Test1()).start();
}
}
}

两个例子中,都有一段synchronized的代码。
在1中,main方法中创建的10个线程 不能同时进入到那段代码执行,因为这10个线程需要让
同一个object授权

在2中,main方法中创建的10个线程 可以同时进入到那段代码执行,因为10个线程是让不同
的object授权的,均授权成功,同时进入到那段代码执行.

java中synchronized用法

synchronized的一个简单例子


public class TextThread

{


/**

* @param args

*/

public static void main(String[] args)

{

// TODO 自动生成方法存根

TxtThread tt = new TxtThread();

new Thread(tt).start();

new Thread(tt).start();

new Thread(tt).start();

new Thread(tt).start();

}


}

class TxtThread implements Runnable

{

int num = 100;

String str = new String();

public void run()

{

while (true)

{

synchronized(str)

{

if (num&gt;0)

{

try

{

Thread.sleep(10);

}

catch(Exception e)

{

e.getMessage();

}

System.out.println(Thread.currentThread().getName()+ "this is "+ num--);

}

}

}

}

}


上面的例子中为了制造一个时间差,也就是出错的机会,使用了Thread.sleep(10)


Java对多线程的支持与同步机制深受大家的喜爱,似乎看起来使用了synchronized关键字就可以轻松地解决多线程共享数据同步问题。到底如何?――还得对synchronized关键字的作用进行深入了解才可定论。


总的说来,synchronized关键字可以作为函数的修饰符,也可作为函数内的语句,也就是平时说的同步方法和同步语句块。如果再细的分类,
synchronized可作用于instance变量、object reference(对象引用)、static函数和class
literals(类名称字面常量)身上。


在进一步阐述之前,我们需要明确几点:


A.无论synchronized关键字加在方法上还是对象上,它取得的锁都是对象,而不是把一段代码或函数当作锁――而且同步方法很可能还会被其他线程的对象访问。


B.每个对象只有一个锁(lock)与之相关联。


C.实现同步是要很大的系统开销作为代价的,甚至可能造成死锁,所以尽量避免无谓的同步控制。


接着来讨论synchronized用到不同地方对代码产生的影响:


假设P1、P2是同一个类的不同对象,这个类中定义了以下几种情况的同步块或同步方法,P1、P2就都可以调用它们。


1. 把synchronized当作函数修饰符时,示例代码如下:


Public synchronized void methodAAA()


{


//….


}


这也就是同步方法,那这时synchronized锁定的是哪个对象呢?它锁定的是调用这个同步方法对象。也就是说,当一个对象P1在不同的线程
中执行这个同步方法时,它们之间会形成互斥,达到同步的效果。但是这个对象所属的Class所产生的另一对象P2却可以任意调用这个被加了
synchronized关键字的方法。


上边的示例代码等同于如下代码:


public void methodAAA()


{


synchronized (this) // (1)


{


//…..


}


}


(1)处的this指的是什么呢?它指的就是调用这个方法的对象,如P1。可见同步方法实质是将synchronized作用于object
reference。――那个拿到了P1对象锁的线程,才可以调用P1的同步方法,而对P2而言,P1这个锁与它毫不相干,程序也可能在这种情形下摆脱同
步机制的控制,造成数据混乱:(


2.同步块,示例代码如下:


public void method3(SomeObject so)


{


synchronized(so)


{


//…..


}


}


这时,锁就是so这个对象,谁拿到这个锁谁就可以运行它所控制的那段代码。当有一个明确的对象作为锁时,就可以这样写程序,但当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的instance变量(它得是一个对象)来充当锁:


class Foo implements Runnable


{


private byte[] lock = new byte[0]; // 特殊的instance变量


Public void methodA()


{


synchronized(lock) { //… }


}


// …..


}


注:零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操作码,而Object lock = new Object()则需要7行操作码。


3.将synchronized作用于static 函数,示例代码如下:


Class Foo


{


public synchronized static void methodAAA() // 同步的static 函数


{


//….


}


public void methodBBB()


{


synchronized(Foo.class) // class literal(类名称字面常量)


}


}


代码中的methodBBB()方法是把class literal作为锁的情况,它和同步的static函数产生的效果是一样的,取得的锁很特别,是当前调用这个方法的对象所属的类(Class,而不再是由这个Class产生的某个具体对象了)。


记得在《Effective Java》一书中看到过将 Foo.class和 P1.getClass()用于作同步锁还不一样,不能用P1.getClass()来达到锁这个Class的目的。P1指的是由Foo类产生的对象。


可以推断:如果一个类中定义了一个synchronized的static函数A,也定义了一个synchronized
的instance函数B,那么这个类的同一对象Obj在多线程中分别访问A和B两个方法时,不会构成同步,因为它们的锁都不一样。A方法的锁是Obj这
个对象,而B的锁是Obj所属的那个Class。


小结如下:


搞清楚synchronized锁定的是哪个对象,就能帮助我们设计更安全的多线程程序。


还有一些技巧可以让我们对共享资源的同步访问更加安全:


1. 定义private 的instance变量+它的
get方法,而不要定义public/protected的instance变量。如果将变量定义为public,对象在外界可以绕过同步方法的控制而直
接取得它,并改动它。这也是JavaBean的标准实现方式之一。


2.
如果instance变量是一个对象,如数组或ArrayList什么的,那上述方法仍然不安全,因为当外界对象通过get方法拿到这个instance
对象的引用后,又将其指向另一个对象,那么这个private变量也就变了,岂不是很危险。
这个时候就需要将get方法也加上synchronized同步,并且,只返回这个private对象的clone()――这样,调用端得到的就是对象副
本的引用了。

Tuesday, 19 February 2008

turn off Vista index search

Windows Vista has greatly enhanced its search algorithm where the search process is now not only faster, but users can also easily search for almost all kind of files, documents, pictures, videos, emails and contacts in Outlook 2007, and even commands or application programs’ executables. To achieve the fast searching speed, indexing service plays a pivotal role. Windows Vista starts to crawl and index files on hard disks right after installed with a low priority background process. If you notice that your hard drive activity LED light is constantly flashing even if computer is idle, this is probably due to indexer at work.

This is supposedly the case - indexing at system idle period in order to minimize the performance penalty affected on normal usage. However, this may not be the case in Vista, as the search indexing related processes such as SearchProtocolHost, SearchFilterHost and SearchIndexer actively running even though computer is processing other more critical tasks or running important applications, effectively slow down overall computer performance by sucking up important CPU, memory and other system resources.

So to speed up Vista, users may want to turn off and disable the search indexer and indexing service. You can and should also disable the indexing of files if you’re using other desktop search utility such as Google Desktop Search and etc. If you don’t mind the slower searching speed when performing searches, the indexing has no meaningful use to you too. There are several ways to do this, as listed at the guide below.

  • Disable Windows Search Service

This method effectively stop and disable all search indexing processes, and is the recommended way.

Windows Search Properties

1. Click on Start button, then select Control Panel -&gt; System and Maintenance -&gt; Administrative Tools, and double click on Services applet. Alternatively, simply type “Services” (without quotes) in Start Search box.
2. If User Account Control asks for permission, click Continue.
3. Locate an service named Windows Search. Right click on WindowsSearch, and then select Properties on contextual menu.
4. Click on Stop button to stop the indexing service immediately.
5. On the Startup Type dropdown box, select Disabled.
6. Click on OK button.

To re-enable the Windows Seearch, simply change back the Startup Type.
  • Disable Indexing on Drives
This method allows users to selectively disable indexing on certain drives which rarely used or searched. However, it may take a long time to apply new attributes to all files, folders and sub-folders to exclude them from indexing.

1. Open Windows Explorer from Accessories.
2. Right click on the drive (or drive letter) that you want to turn off the indexing.
3. Select Properties on the contextual menu.
4. Unselect (untick) the Index this drive for faster searching option.

Stop Indexing on Drives
5. Click Apply or OK button.

To re-include the drive, simply select the option again.

Indexing Options Remove or Exclude Indexed Locations in Control Panel

This method does not turn off indexing service. Instead, it just excludes deselected folders from search index, or deselect folders from included list. The indexer processes may still run after you remove or exclude everything.

1. Click on Start button.
2. Click on Control Panel.
3. Click on System and Maintenance.
4. Click on Indexing Options.
5. To remove an Included Location, simply click on Modify button, and then untick the checkbox for respective folders under the “Change selected locations” box. To remove indexing on Start Menu and/or Users folder, click on “Advanced” button at Indexing Options dialog or “Show all locations” in Indexed Locations dialog. UAC access request continue required. Click on Start Menu and Users once at “Summary of selected locations” box if you do not see the checkbox for them.

  • Indexed Locations

To re-enable, simply tick back the folders.

Monday, 18 February 2008

keybinding = shortcut in Ubuntu

For more configurability look at this method I used for getting Amarok to start on Ctrl+Alt+a.

Firstly call up a terminal and enter:

gconf-editor

This will bring the central config tool for GNOME; here you can access all of your settings.
We are interested in the following entries.

/-&gt;apps-&gt;metacity-&gt;global_keybindings

/-&gt;apps-&gt;metacity-&gt;keybinding_commands

When you click on global_keybindings you should see entries along the line of

run_command_x disabled

Where x is a number between 1 and 12 (it can go upto 32 according the the manual but defaults to 12).

In keybinding_commands you should see entries like

command_x

Where x is the same number as for run_command.

In order to set a keybinding you simply enter the key
combination in place of disabled in run_command-x, then enter the
command to launch in the blank field for the respective command_x
entry.



run_command_x

For this all meta keys are enclosed in &lt;&gt; as follows.

&lt;Control&gt; &lt;Alt&gt; &lt;Shift&gt;

Letters are simply lowercased entries. Direction arrows start with a capital letter such as

Up Down


We are interested in setting Ctrl+Alt+a for Amarok's
shortcut keyc so we need to enter this after run_command_1 (or
whichever one is free)

&lt;Control&gt;&lt;Alt&gt;a


Ensure the value is entered by clicking a different entry
(if you don't, the command may disappear as you change to
keybinding_commands)



command_x

Here I had some problems. For whatever reason entering the same
command as Amarok uses from a launcher (amarok %U) doesn't work
properly. The program starts but doesn't load the last playlist opened
like it normally does. No matter - we will force it to open it by
saving the playlist, then directly calling the list in the command.
This still doesn't call the last used list but it's better than having
to mess around in a GUI every time you want to run your player. For the
moment assume I saved the playlist as playlist.m3u and your user name
is foo.

The command we enter into the blank field is

amarok /home/foo/.kde/share/apps/amarok/playlists/playlist.m3u



This will make the program run correctly.

I'm not sure if this problem is unique to Amarok or is a general
GNOME problem. Anyway if you do have a problem with another program you
can now try something along this line.



The Moment of Truth

Having done that, close the configuration editor (it will save
all the altered values automatically). Then press your designated key
combination (Ctrl+Alt+a in the example). If all is set up properly you
should see Amarok (or whatever app you tried) starting. If not check
again in gconf-editor to see if you have used the same value for x in
both entries; also check that you haven't made any errors in either the
key combination or the command itself.

Friday, 15 February 2008

Get Ip address in Java

getInetAddress

public InetAddress getInetAddress()

Returns the address to which the socket is connected.

Returns:
the remote IP address to which this socket is connected, or null if the socket is not connected.



getLocalAddress

public InetAddress getLocalAddress()

Gets the local address to which the socket is bound.

Returns:
the local address to which the socket is bound or InetAddress.anyLocalAddress() if the socket is not bound yet.
Since:
JDK1.1


Thursday, 14 February 2008

Java Ubuntu alternative option

7 Multiple JRE/JDK installed

From: http://wiki.serios.net/wiki/Ubuntu_Java_JRE/JDK_installation_with_java-package


If you have multiple JRE or JDK installed (e.g. 1.5.0 and 1.4.2) and want/need to switch between them, you can use update-alternatives to do so.

Example: Choosing which java executable to use:


update-alternatives --config java


Example: Choosing which javac executable to use:


update-alternatives --config javac


And so on in that fashion for the remaining executables related to Java. You can look in /etc/alternatives to see what one can configure with update-alternatives.

If you wish to remove some of the JRE/JDKs you have installed, execute (example: for Sun JRE 1.4.2):


apt-get remove sun-j2re1.4



Powered by ScribeFire.

Wednesday, 13 February 2008

java variable to be initialized to null

This topic concerns variable scope.

Local variable: It's called in the local method, has no default value.
instance variable: It's from other class which is called by local class ('s method).

Here is an example:

Local Object
References


Objects references, too, behave differently when declared
within a method rather than as instance variables. With instance variable object
references, you can get away with leaving an object reference uninitialized, as
long as the code checks to make sure the reference isn't null before using
it. Remember, to the compiler, null is a value.
You can't use the dot operator on a null reference,
because there is no object at the other end of it, but a
null reference is not the same as an uninitialized reference. Locally declared references can't
get away with checking for null before use,
unless you explicitly initialize the local variable to null. The compiler
will complain about the following code:


import java.util.Date;
public class TimeTravel {
public static void main(String [] args) {
Date date;
if (date == null)
System.out.println("date is null");
}
}

Compiling the code results in an error similar to the
following:


%javac TimeTravel.java
TimeTravel.java:5: Variable date may not have been initialized.
if (date == null)
1 error

Instance variable references are always given a default value of
null, until
explicitly initialized to something else. But local references are not given a
default value; in other words, they aren't null. If you don't
initialize a local reference variable, then by default, its value iswell that's the whole point—it doesn't have any value at
all! So we'll make this simple: Just set the darn thing to null explicitly, until you're ready to initialize it
to something else. The following local variable will compile properly:


Date date = null; // Explicitly set the local reference
// variable to null



Powered by ScribeFire.

Tuesday, 12 February 2008

ubuntu add printer

Now if you want to add a printer, you must come here.
http://localhost:631
Because, the GUI for printer installation in Ubuntu using current user while not root, so no way to pass the authorization check. The web UI can put in root user and password, so it's better.

Another issue is that the default setting of Ubuntu have no root password, so
sudo passwd
to create a password for the Unix system. Then when you add printer from the web UI, it will work.

python run system command: os.exec.....

Python can call other program easily. Here are some ways:

import os

os.chdir('the path your program is in')
os.execv('WinProgram.exe',['argv[0]','other parameter']) # here the first one will not passed to the program!!!! And execv requires the arguments are in one list or turtle.
##os.execl('WinProgram.exe','argv[0]','other parameter')
##os.system('WinProgram.exe'+' '+'other parameter')

Here os.system just run the command, while execl and execv will stop current process and turn to another one, the rest codes will not run.

Saturday, 9 February 2008

python change working directory

Sometimes this concept of working directory is essential, especially when calling another system or executable programs.

import os

os.chdir('c:\\thepath\\')
os.system('the command') # otherwise, if the command need to read some file within same folder, the command can not find it, because the needed file is not in the current working directory.


Powered by ScribeFire.

Bash Programming Cheat Sheet


A quick cheat sheet for programmers who want to do shell
scripting. This is not intended to teach programming, etc. but
it is intended for a someone who knows one programming language
to begin learning about bash scripting.



Basics



All bash scripts must tell the o/s what to use as the
interpreter. The first line of any script should be:



#!/bin/bash



You must make bash scripts executable.



chmod +x filename




Variables



Create a variable - just assign value. Variables are
non-datatyped (a variable can hold strings, numbers, etc. with
out being defined as such).



varname=value



Access a variable by putting $ on the front of the name



echo $varname



Values passed in from the command line as arguments are
accessed as $# where #= the index of the variable in the array
of values being passed in. This array is base 1 not base 0.

command var1 var2 var3 .... varX

$1 contains whatever var1 was, $2 contains whatever var2 was,
etc.



Built in variables:

































$1-$N Stores the arguments (variables) that were passed to
the shell program from the command line.
$? Stores the exit value of the last command that was
executed.
$0 Stores the first word of the entered command (the
name of the shell program).
$* Stores all the arguments that were entered on the
command line ($1 $2 ...).
"$@" Stores all the arguments that were entered on the
command line, individually quoted ("$1" "$2" ...).





Quote Marks



Regular double quotes ("like these") make the shell ignore
whitespace and count it all as one argument being passed or
string to use. Special characters inside are still
noticed/obeyed.



Single quotes 'like this' make the interpreting shell ignore
all special characters in whatever string is being passed.



The back single quote marks (`command`) perform a different
function. They are used when you want to use the results of a
command in another command. For example, if you wanted to set
the value of the variable contents equal to the list of files
in the current directory, you would type the following command:
contents=`ls`, the results of the ls program are put in the
variable contents.



Logic and comparisons



A command called test is used to evaluate conditional
expressions, such as a if-then statement that checks the
entrance/exit criteria for a loop.



test expression

Or

[ expression ]



Numeric Comparisons













































int1 -eq int2 Returns True if int1 is equal to int2.
int1 -ge int2 Returns True if int1 is greater than or equal to
int2.
int1 -gt int2 Returns True if int1 is greater than int2.
int1 -le int2 Returns True if int1 is less than or equal to
int2
int1 -lt int2 Returns True if int1 is less than int2
int1 -ne int2 Returns True if int1 is not equal to int2




String Comparisons



































str1 = str2 Returns True if str1 is identical to str2.
str1 != str2 Returns True if str1 is not identical to str2.
str Returns True if str is not null.
-n str Returns True if the length of str is greater than
zero.
-z str Returns True if the length of str is equal to zero.
(zero is different than null)


File Comparisons























































-d filename Returns True if file, filename is a directory.
-f filename Returns True if file, filename is an ordinary
file.
-r filename Returns True if file, filename can be read by the
process.
-s filename Returns True if file, filename has a nonzero
length.
-w filename Returns True if file, filename can be written by the
process.
-x filename Returns True if file, filename is executable.














Expression Comparisons



!expression



Returns true if expression is not true

expr1 -a expr2



Returns True if expr1 and expr2 are true. ( && , and
)

expr1 -o expr2



Returns True if expr1 or expr2 is true. ( ||, or )







Logic Con't.



If...then



if [ expression ]

then

commands

fi





If..then...else



if [ expression ]

then

commands

else

commands

fi





If..then...else If...else



if [ expression ]

then

commands

elif [ expression2 ]

then

commands

else

commands

fi



Case select



case string1 in

str1)

commands;;

str2)

commands;;

*)

commands;;

esac



string1 is compared to str1 and str2. If one of these strings
matches string1, the commands up until the double semicolon (;
;) are executed. If neither str1 nor str2 matches string1, the
commands associated with the asterisk are executed. This is the
default case condition because the asterisk matches all
strings.



Iteration (Loops)



for var1 in list

do

commands

done



This executes once for each item in the list. This list can be
a variable that contains several words separated by spaces
(such as output from ls or cat), or it can be a list of values
that is typed directly into the statement. Each time through
the loop, the variable var1 is assigned the current item in the
list, until the last one is reached.



while [ expression ]

do

commands

done



until [ expression ]

do

commands

done



Functions



Create a function:



fname(){

commands

}





Call it by using the following syntax: fname



Or, create a function that accepts arguments:



fname2 (arg1,arg2...argN){

commands

}



And call it with: fname2 arg1 arg2 ... argN

Powered by ScribeFire.

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter