Thursday, January 31, 2008

Mysql master and slaver server日志文件清理方法

一、要在MASTER要清理日志,需按照以下步骤:
1. 在每个从属服务器上,使用SHOW SLAVE STATUS来检查它正在读取哪个日志。
2. 使用SHOW MASTER LOGS获得主服务器上的一系列日志。
3. 在所有的从属服务器中判定最早的日志。这个是目标日志。如果所有的从属服务器是更新的,这是清单上的最后一个日志。
4. 制作您将要删除的所有日志的备份。(这个步骤是自选的,但是建议采用。)
5. 清理所有的日志,但是不包括目标日志。
二、要在SLAVER上清理日志,需要按以下步骤:
1. 在本机上使用SHOW SLAVE STATUS来检查它正在使用哪个Relay_Log_File日志。
2. 保留此目标日志,可以删除之前的中继日志文件。
(中继日志也可以将本机MYSQL SERVER SHUTDOWN后,将hostname-relay-bin.index, hostname-relay-bin.*, relay-log.info删除之后重启MYSQL SERVER,其中master.info文件不能删除)
3. 使用SHOW MASTER LOGS获得本机上的一系列日志。
4. 保留最新一个,可以删除之前的bin-log文件。
5. 建议删除之前都先备份,删除后重启SERVER看是否正常同步数据,把当前正式使用的中继日志和bin-log日志删除可能会导致同步不可用。
三、如果主机更新了replication slave user的密码,在SLAVE上执行:
mysql> STOP SLAVE; -- if replication was running
mysql> CHANGE MASTER TO MASTER_PASSWORD='new3cret';
mysql> START SLAVE; -- if you want to restart replication
四、CHANGE MASTER 使用注意
CHANGE MASTER会删除所有的中继日志文件并启动一个新的日志,除非指定了RELAY_LOG_FILE或RELAY_LOG_POS,在此情况下,中继日志被保持;relay_log_purge全局变量被静默地设置为0。
CHANGE MASTER TO可以更新master.info和relay-log.info文件的内容。

CSS content generator and :before usage


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<title>css trick</title>
<style type="text/css">
a[href^="mailto:"]:hover:after { content: " > " attr(title) }
a:focus { font-size: 14pt; text-decoration: underline; color: purple; }
</style>
</head>
<body>
<h2>Thomas Jefferson</h2>
<p><a href="mailto:thomasjefferson@whitehouse.gov" title="thomasjefferson@whitehouse.gov">Send Email</a> :focus(伪对象),设置对象在成为输入焦点(该对象的 onfocus 事件发生)时的样式. :after和:focus伪对象IE不支持,本段程序在IE里无效. content属性一般是结合:after和:before使用,在文档流某个节点后面或者前面加入新的内容,其中有个attr()方法可以读取此节点的属性值.</p>
</body>
</html>

HTTP status list

200 : request completed (OK)
201 : object created, reason = new URI
202 : async completion (TBS)
203 : partial completion
204 : no info to return
205 : request completed, but clear form
206 : partial GET furfilled
300 : server couldn't decide what to return
301 : object permanently moved
302 : object temporarily moved
303 : redirection w/ new access method
304 : if-modified-since was not modified
305 : redirection to proxy, location header specifies proxy to use
307 : HTTP/1.1: keep same verb
400 : invalid syntax
401 : access denied
402 : payment required
403 : request forbidden
404 : object not found
405 : method is not allowed
406 : no response acceptable to client found
407 : proxy authentication required
408 : server timed out waiting for request
409 : user should resubmit with more info
410 : the resource is no longer available
411 : the server refused to accept request w/o a length
412 : precondition given in request failed
413 : request entity was too large
414 : request URI too long
415 : unsupported media type
500 : internal server error
501 : required not supported
502 : error response received from gateway
503 : temporarily overloaded
504 : timed out waiting for gateway
505 : HTTP version not supported

Wednesday, January 30, 2008

window frames property test

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
<HTML>
<HEAD>
<TITLE>A frameset document</TITLE>
</HEAD>
<FRAMESET cols="40%, 60%" name="fs" id="frs">
<FRAME src="fm1.html" frameborder="0" name="fmn1" id="fmi1"/>
<FRAME src="fm2.html" frameborder="0" name="fmn2" id="fmi2"/>
</FRAMESET>
</HTML>
debug under firebug console:
>>> window
Window frames.html
>>> window.frames
Window frames.html
>>> window.frames[0]
Window fm1.html
>>> window.frames[1]
Window fm2.html
>>> window.frames[1].id
# => undefined
>>> window.frames[1].src
# => undefined
>>> window.frames[1].name
"fmn2"
>>> document.getElementById('fmi1')
<frame id="fmi1" name="fmn1" frameborder="0" src="fm1.html">
>>> document.getElementById('fmi1').id
"fmi1"

Object window has name propery, but has no id and src properties, so window.frames[1].src is undefined, we can get src value throught top window's element object, such as cument.getElementById('fmi1').id

ActiveRecord callbacks execute sequence

before_validation
before_validation_on_create
after_validation
after_validation_on_create
before_save
before_create
insert operation
after_create
after_save

ActiveRecord callback instance methods execute ways on create will revok before_validation_on_create callback before ActiveRecord validation methods, and before_create callback will revoke after ActiveRecord validation methods and helpers, like validates_associated, validates_each.
If a new record has some error, and will not be validated by ActiveRecord validation methods and helpers, then after_validation and before_create callback will not be revoked.

Why can't I use SSL with name-based/non-IP-based virtual hosts?


参考apache的文档


Why can't I use SSL with name-based/non-IP-based virtual hosts?

The reason is very technical, and a somewhat "chicken and egg" problem. The SSL protocol layer stays below the HTTP protocol layer and encapsulates HTTP. When an SSL connection (HTTPS) is established Apache/mod_ssl has to negotiate the SSL protocol parameters with the client. For this, mod_ssl has to consult the configuration of the virtual server (for instance it has to look for the cipher suite, the server certificate, etc.). But in order to go to the correct virtual server Apache has to know the Host HTTP header field. To do this, the HTTP request header has to be read. This cannot be done before the SSL handshake is finished, but the information is needed in order to complete the SSL handshake phase. Bingo!
Why is it not possible to use Name-Based Virtual Hosting to identify different SSL virtual hosts?

Name-Based Virtual Hosting is a very popular method of identifying different virtual hosts. It allows you to use the same IP address and the same port number for many different sites. When people move on to SSL, it seems natural to assume that the same method can be used to have lots of different SSL virtual hosts on the same server.

It comes as rather a shock to learn that it is impossible.

The reason is that the SSL protocol is a separate layer which encapsulates the HTTP protocol. So the SSL session is a separate transaction, that takes place before the HTTP session has begun. The server receives an SSL request on IP address X and port Y (usually 443). Since the SSL request does not contain any Host: field, the server has no way to decide which SSL virtual host to use. Usually, it will just use the first one it finds, which matches the port and IP address specified.

You can, of course, use Name-Based Virtual Hosting to identify many non-SSL virtual hosts (all on port 80, for example) and then have a single SSL virtual host (on port 443). But if you do this, you must make sure to put the non-SSL port number on the NameVirtualHost directive, e.g.

NameVirtualHost 192.168.1.1:80

Other workaround solutions include:

Using separate IP addresses for different SSL hosts. Using different port numbers for different SSL hosts.

相关的中文说明

为什么我不能在相同IP地址下多个域名的虚拟主机上使用SSL?

这个问题十分专业,有些像“先有鸡还是先有蛋”的问题。SSL协议层是在HTTP协议层的前面,当SSL连接建立时,SSL模块在Web模块之前和浏览器进行通讯并交换证书、建立加密隧道。众所周知,Web服务器是通过 HTTP数据包中的”Host”字段来区分虚拟主机的。而SSL模块在把服务器证书发送到浏览器时,还没有收到任何关于HTTP的数据包,更不知道虚拟主机的域名,因此SSL模块只能固定的将一张SSL证书发送到浏览器,而不能根据域名有选择性的发送证书。因此,您无法在一个IP地址的默认SSL 443端口下为多个虚拟主机配置多张证书。

由于一个IP与一个端口号只能对应一张证书,因此可以采用以下方式解决:

(1) 为需要SSL加密的虚拟主机配置不同的IP地址,端口号都使用443。例如: www.domain1.com 的SSL使用 202.96.101.1:443 www.domain2.com的SSL使用 202.96.101.2:443,通过 https://www.domain1.com 和 https://www.domain2.com 访问这2个SSL网站了

(2) 如果只有一个IP地址,可以为多个网站配置不同的SSL端口。例如: www.domain1.com 的SSL使用 202.96.101.1:443 www.domain2.com的SSL使用 202.96.101.1:1000,通过 https://www.domain1.com 和 https://www.domain2.com:1000 访问这2个SSL网站了

如果多个虚拟主机是1个主域名下的多个子域名,情况发生了转变,因为你可以申请通配符SSL证书。

例如: 有2个虚拟主机 abc.domain.com、xyz.domain.com,你申请一张 *.domain.com的证书,按照前面所说的原理,2个虚拟主机都使用同一个IP和默认的443端口,当浏览器访问IP:443端口时,SSL模块把通配符SSL证书传送给浏览器,建立合法的SSL隧道,然后WEB模块接收到HTTP数据包时判断域名选择虚拟主机。

原理是OK的,不幸的是你无法按照这个原理对IIS进行配置,早期的IIS不支持SSL端口配置域名。只有您使用Windows 2003,安装了Service Pack1后,才可以通过命令行为SSL端口配置域名,Apache是可以为SSL端口配置域名。您需要为所有的虚拟主机配置相同的通配符证书。就是说,我可以建立一个*.domain的域名证书,给所有的子域名来使用。

原文链接:http://wlx.westgis.ac.cn/421/

Sunday, January 27, 2008

open Safari debug menu

open Terminal Application, and input:
$> defaults write com.apple.Safari IncludeDebugMenu 1
then reopen safari, debug menu will display at the end of menu bar.

方法名做为另外一个函数的参数-闭包用法一

<html>
<head><title> test cloures </title></head>
<body>
<script type="text/javascript" charset="utf-8">
var a = b = 1; // var a = (b = 1), variable b is no declared(like var b, the scope of b is global.)
function test() {
alert("a=" + a); // 1
alert("b=" + b); // 10
return a + b;
}

function testClosures(funcName) {
var a = b = 10; // var a = (b = 10); b is a global variable.
return funcName();
}
alert(testClosures(test));
</script>
</body>
</html>

javascript中相同命名空间下函数名和变量名冲突


<script type="text/javascript" charset="utf-8">
function test() {
alert(arguments.callee);
}
var test = 'xyz';
alert(test); // 'xyz'
test(); //test is not a function [Break on this error] test();
</script>

函数名其实也是一个变量名,所以是会发生冲突的。

Saturday, January 26, 2008

addEventListener's phase and sequence


<html>
<head><title> addEventListener Capturing_phase and Bubbling_phase and At_target </title></head>
<body>
<div id="a1">
<div id="a2"> <input type="button" name="input1" id="i1" value="click here"> </div>
</div>
<script type="text/javascript" charset="utf-8">
function doc(event) {
alert("currentTarget=" + event.currentTarget.id + "; target=" + event.target + "; eventPhase=" + event.eventPhase);
}
var a1 = document.getElementById("a1");
var a2 = document.getElementById("a2");
var i1 = document.getElementById("i1");
a1.addEventListener('click', doc, true);
a2.addEventListener('click', doc, false);
i1.addEventListener('click', doc, false);
</script>
</body>
</html>

addEventListener的第3个参数是指在capturing_phase是否捕获此动作,因此上面会按"a1->i1->a2"的顺序弹出提示,这个顺序与dom文档节点顺序和addEventListener第3个参数有关,与javascript代码中的addEventListener的顺序无关。
要在事件流的所有阶段侦听某一事件,您必须调用 addEventListener() 两次,第一次调用时将 useCapture 设置为 true,第二次调用时将 useCapture 设置为 false。如:
a1.addEventListener('click', doc, false);
此时在capturing phase和bubbling phase都会有a1的事件提示。

Friday, January 25, 2008

HTML5 Shiv

source article link: http://ejohn.org/blog/html5-shiv/


<html>
<head>
<style>blah { color: red; }</style>
<script type="text/javascript">document.createElement("blah")</script>
</head>
<body>
<blah>Hello!</blah>
</body>
</html>

防止浏览网页中毒

将三个不安全的组件进行卸载(原文http://bbs.17173.com/topics/936/200711/30/11734,1.html)
regsvr32 /u /s %SystemRoot%\system32\SHELL32.dll
  regsvr32 /u /s %SystemRoot%\system32\wshom.ocx
  regsvr32 /u /s %SystemRoot%\system32\scrrun.dll
******************************************************************
** Scripting.FileSystemObject 是由系统目录中的scrrun.dll实现 **
** WScript.Shell 是由系统目录中的wshom.ocx实现 **
** Shell.Application 是由系统目录中的SHELL32.dll实现 **
******************************************************************

Wednesday, January 23, 2008

value of element.style must be string in Javascript


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>img</title>
</head>
<body>
<div id="img" style="position: absolute;">
<img border="0" alt="img" src="logo.gif"/>
</div>
<script type="text/javascript">
var img = document.getElementById('img');
img.style.left = 200;
img.style.top = 200 + "px";
</script>
</body>
</html>

当文档声明DOCTYPE没有的话,JS会正常的起效果,如果加上第一行的文档声明,则JS中的left就不会生效.
参考JavaScript Pocket Reference, 2nd Edition中第3章Style:
Synopsis
element.style
Properties
The Style object defines a large number of properties: one property for each CSS attribute defined by the CSS2 specification. The property names correspond closely to the CSS attribute names, with minor changes required to avoid syntax errors in JavaScript. Multiword attributes that contain hyphens, such as font-family are written without hyphens in JavaScript, and each word after the first is capitalized: fontFamily. Also, the float attribute conflicts with the reserved word float, so it translates to the property cssFloat.

The visual CSS properties are listed in the following table. Since the properties correspond directly to CSS attributes, no individual documentation is given for each property. See a CSS reference (such as Cascading Style Sheets: The Definitive Guide (O'Reilly), by Eric A. Meyer) for the meaning and legal values of each. Note that current browsers do not implement all of these properties.

All of the properties are strings, and care is required when working with properties that have numeric values. When querying such a property, you must use parseFloat( ) to convert the string to a number. When setting such a property you must convert your number to a string, which you can usually do by adding the required units specification, such as "px".

Tuesday, January 22, 2008

Rails URI error[resolved]

当RAILS收到的请求URL里带有一些特殊字符时,RAILS直接会抛出一个URI异常,并且RAILS的LOG里也不会有此请求的记录生成,错误类似于:
irb(main):015:0> require 'uri'
irb(main):016:0> URI.parse('http://www.test.com/main/show?user=M603&db=test&border=1local=y|e|s')
URI::InvalidURIError: bad URI(is not URI?): http://www.test.com/main/show?user=M603&db=test&border=1local=y|e|s
from C:/ruby/lib/ruby/1.8/uri/common.rb:432:in `split'
from C:/ruby/lib/ruby/1.8/uri/common.rb:481:in `parse'
from (irb):16
from :0


在RAILS项目的config/environment.rb最后面加上以下代码:
module URI
class << self
alias _parse parse
def parse(uri)
uri = escape(uri) if uri.match(/[#{Regexp::quote('{}|\^[]`')}]/)
_parse(uri)
end
end
end


参考http://www.ietf.org/rfc/rfc2396.txt

Monday, January 21, 2008

keywords of this in javascript methods

<html>
<head>
<title> cloures </title>
<script src="/lib/prototype/prototype.js" type="text/javascript"></script>

<script type="text/javascript">
var o = {};
var obj = {
name: 'A nice demo in obj',
fx: function() {
return this.name + " " + $A(arguments).join(', ');
},
rf: function() {
return function() { return this.name + " " + $A(arguments).join(', '); }
}
};
alert(obj.fx);
window.name = 'I am such a beautiful window!';
function runFx(f) {
return f();
}
var fx2 = obj.fx.bind(obj, 'otherArg1', 'otherArg2');
var rf2 = obj.rf.bind(obj, 'otherArg1', 'otherArg2');
alert(fx2);
document.write(runFx(obj.fx));
document.write("<br />");
document.write(runFx(fx2));
document.write("<br />");
document.write(obj.rf()());
document.write("<br />");
document.write(rf2()());
document.write("<br />");
</script>
</head>
<body>
Javascript的闭包函数(如将函数做为另一个函数/方法的参数或者是返回结果为函数)中的this会因为闭包函数使用环境不同而变化。
<br />
prototype.js里加了一个bind方法可以把this重新绑回到原对象上(如fx方法所示),但如果返回的是闭包函数,则其中的this会指向新的object(如rf2方法所示指向了window)
</body>
</html>

利用arguments.callee写递归匿名函数


<html>
<head>
<title>arguments callee test</title>
</head>
<body>
<script type="text/javascript" charset="utf-8">
var factorial = function(x) {
if (x == 1) {
return 1;
} else {
return x * arguments.callee(x - 1);
}
};

document.write(factorial(5));
</script>
</body>
</html>

Javascript function and anonymous function differrence 1

Javascript函数存在于定义它们的整个作用域(包括出现在该函数语句前面的语句)内。与之相反, Javascript匿名函数只是为后续的语句定义的。如下example:


<html>
<head>
<title> test stateFunction and expressionFunction difference</title>
</head>
<body>
<div id="d1">d1</div>
<div id="d2">d2</div>
doc_write is not a function<br />
[Break on this error] doc_write(document.getElementById('d1').innerHTML);
<script type="text/javascript" charset="utf-8">
doc(document.getElementById('d1').innerHTML);
doc_write(document.getElementById('d1').innerHTML);

function doc(argument) {
document.write("<p>\n");
document.write(argument);
document.write("</p>\n");
}

var doc_write = function(args) {
document.write("<p>\n");
document.write(args);
document.write("</p>\n");
};
</script>
</body>
</html>

Sunday, January 20, 2008

usage of cut [awk] and xargs of linux commands

alias dierails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -KILL $1'
alias resetrails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -HUP $1'

在dzone.com上看到这个命令alias用以杀掉ruby rails server进程,其中的cut结合xargs或者是awk结合xargs使用相当便捷。

Friday, January 18, 2008

getURL and ExternalInterface.call of flash invoke javascript function

在Flash中,通过getURL("javascript:urchinTracker(pageUrl2);")方法调用GA的JS,从而跟踪FLASH的内部一些帧,当在flash相同的一帧里,此getURL()方法前还有一个getURL("javascript:urchinTracker(pageUrl1);")方法时,此时后面那个pageURL2是不会被访问的,也就是后面的JS不会被执行,可以将2个JS并到一个getURL()方法里去执行,另外用flash中的ExternalInterface.call()方法可以直接调用外部JS从避过此问题.

Rails multi-database connections resolutions

当Rails项目中数据处理量比较大时就需要将数据库的读写操作分在不同的database server上,在网上GOOGLE了一下,主要通过Dr.Nic的magic_multi_connections来处理,需要安装这个GEM包,然后修改config/database.yml,config/environment.rb文件,具体可参考Dr.Nic的说明,还是比较方便的.
还有个是叫active_delegate的Rails plugin,使用比上面的gem更方便,但是实际使用后发现没有Dr.Nic的方法好用.

Update: Nic的方法使用起来修改配置的地方还是比较多,实际使用过程中发现还是有点问题的.建议还是按rails本身提供的一个多数据库连接机制:
Connection to multiple databases in different models
Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. For example, if Course is a ActiveRecord::Base, but resides in a different database you can just say Course.establish_connection and Course *and all its subclasses* will use this connection instead.

This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.

基于prototype javascript library的几个常用扩展

个人用到比较多并觉得效果不错的几个基于prototype library的扩展(插件):
1.prototype.windows
2.prototype.tooltip
3.prototype.jester
4.prototype.tablekit
5.prototype.lightbox2
6.prototype.datepicker[这个跟http://www.dynarch.com/projects/calendar上的这个日期插件还是有差距,不过那个calendar文件有点大]

Thursday, January 10, 2008

ActionScript3 类型检查

类型检查可以在编译时或运行时执行。静态类型语言(如 C++ 和 Java)在编译时执行类型检查。动态类型语言(如 Smalltalk 和 Python)在运行时执行类型检查。ActionScript 3.0 是动态类型的语言,它在运行时执行类型检查,同时也支持在名为“严格模式”的特殊编译器模式下在编译时执行类型检查。在严格模式下,类型检查既发生在编译时也发生在运行时,但是在标准模式下,类型检查仅发生在运行时。
在构造代码时,动态类型的语言带来了极大的灵活性,但代价是在运行时可能出现类型错误。静态类型的语言在编译时报告类型错误,但代价是要求类型信息在编译时是已知的。

ActionScript 变量作用域说明

与 C++ 和 Java 中的变量不同的是,ActionScript 变量没有块级作用域。代码块是指左大括号 ({) 与右大括号 (}) 之间的任意一组语句。在某些编程语言(如 C++ 和 Java)中,在代码块内部声明的变量在代码块外部不可用。对于作用域的这一限制称为块级作用域,ActionScript 中不存在这样的限制,如果您在某个代码块中声明一个变量,那么,该变量不仅在该代码块中可用,而且还在该代码块所属函数的其它任何部分都可用。例如,下面的函数包含在不同的块作用域中定义的变量。所有的变量均在整个函数中可用。
有趣的是,如果缺乏块级作用域,那么,只要在函数结束之前对变量进行声明,就可以在声
明变量之前读写它。这是由于存在一种名为“提升”的方法,该方法表示编译器会将所有的
变量声明移到函数的顶部。例如,下面的代码会进行编译,即使 num 变量的初始 trace() 函
数发生在声明 num 变量之前也是如此。
trace(num); // NaN
var num:Number = 10;
trace(num); // 10
但是,编译器将不会提升任何赋值语句。这就说明了为什么 num 的初始 trace() 会生成 NaN(而非某个数字), NaN 是 Number 数据类型变量的默认值。这意味着您甚至可以在声明变量之前为变量赋值,如下面的示例所示:
num = 5;
trace(num); // 5
var num:Number = 10;
trace(num); // 10


function blockTest(testArray:Array) {
var numElements:int=testArray.length;
if (numElements > 0) {
var elemStr:String="Element #";
for (var i:int=0; i < numElements; i++) {
var valueStr:String=i + ": " + testArray[i];
trace(elemStr + valueStr);
}
trace(elemStr,valueStr,i);// 仍定义了所有变量
}
trace(elemStr,valueStr,i);// 如果 numElements > 0,则会定义所有变量
}
blockTest(["Earth","Moon","Sun"]);

Wednesday, January 09, 2008

Offscreen Images and Caching[22.1.3 JavaScript: The Definitive Guide, 5th Edition]


22.1.2. Traditional Image Rollovers
The main feature of the Image object is that its src property is read/write. You can read this property to obtain the URL from which an image was loaded, and, more importantly, you can set the src property to make the browser load and display a new image in the same space.
The ability to dynamically replace one image with another in an HTML document opens the door to any number of special effects, from animation to digital clocks that update themselves in real time. In practice, the most common use for image replacement is to implement image rollovers, in which an image changes when the mouse pointer moves over it. (To prevent jarring visual effects, the new image should be the same size as the original.) When you make images clickable by placing them inside your hyperlinks, rollover effects are a powerful way to invite the user to click on the image.[*] This simple HTML fragment displays an image within an <a> tag and uses JavaScript code in the onmouseover and onmouseout event handlers to create a rollover effect:
[*] No discussion of image rollovers is complete without pointing out that they can also be implemented using the CSS :hover pseudoclass to apply different CSS background images to elements when the mouse "hovers" over them. Unfortunately, making CSS image rollovers work portably is difficult. In practice, :hover is more useful when applied to hyperlinks containing text, rather than images.
<a href="help.html"
onmouseover="document.helpimage.src='images/help_rollover.gif';"
onmouseout="document.helpimage.src='images/help.gif';">
<img name="helpimage" src="images/help.gif" border="0">
</a>
Note that in this code fragment, the <img> tag has a name attribute that makes it easy to refer to the corresponding Image object in the event handlers of the <a> tag. The border attribute prevents the browser from displaying a blue hyperlink border around the image. The event handlers of the <a> tag do all the work: they change the image that is displayed simply by setting the src property of the image to the URLs of the desired images. These event handers are placed on the <a> tag for the benefit of very old browsers that support those handlers only on specific tags, such as <a>. In virtually every browser deployed today, you can also put the event handlers on the <img> tag itself, which simplifies the image lookup. The event-handler code can then refer to the Image object with the this keyword:
<img src="images/help.gif"
onmouseover="this.src='images/help_rollover.gif'"
onmouseout="this.src='images/help.gif'">
Image rollovers are strongly associated with clickability, so this <img> tag should still be enclosed in an <a> tag or given an onclick event handler.

22.1.3. Offscreen Images and Caching
In order to be viable, image rollovers and related effects need to be responsive. This means that you need some way to ensure that the necessary images are "prefetched" into the browser's cache. To force an image to be cached, you first create an Image object using the Image( ) constructor. Next, load an image into it by setting the src property of this object to the desired URL. This image is not added to the document, so it does not become visible, but the browser nevertheless loads and caches the image data. Later, when the same URL is used for an onscreen image, it can be quickly loaded from the browser's cache, rather than slowly loaded over the network.
The image-rollover code fragment shown in the previous section did not prefetch the rollover image it used, so the user might notice a delay in the rollover effect the first time she moves the mouse over the image. To fix this problem, modify the code as follows:
<script>(new Image( )).src = "images/help_rollover.gif";</script>
<img src="images/help.gif"
onmouseover="this.src='images/help_rollover.gif'"
onmouseout="this.src='images/help.gif'">

Tuesday, January 08, 2008

obj.instance_eval and mod.module_eval(mod.class_eval) usage


class C
def initialize
@x = 1
end
end

c = C.new
c.instance_eval { puts @x }
puts c.instance_variable_get "@x"

C.class_eval do
def some_method
puts "Created in class_eval"
end
end
c = C.new
c.some_method

Where the singleton methods live in Ruby [R4R 13.1.1]

Ruby, as usual, has a simple answer to this tricky question: An object's singleton methods live in the object's singleton class. Every object really has two classes:
■ The class of which it is an instance
■ Its singleton class

Monday, January 07, 2008

WARNING DON’T LEAVE OUT THE DOT WHEN IT’S NEEDED [R4R page 186]

In one situation, you must use the full object-dot-message notation, even if you’re sending the message to the current self: when the method is a setter method—a method whose name ends with an equal sign. You have to do self.venue = "Town Hall" rather than venue = "Town Hall", if you want to call the method venue=. The reason is that Ruby always interprets the sequence: bareword = value as an assignment to a local variable. To call the method venue= on the current object, you need to include the explicit self. Otherwise, you’ll end up with a variable called venue and no call to the setter method.

NOTE CLASS OR MODULE? [R4R page 175]

When you see a construct like :
ActionController::Routing::Route
you can’t tell from that construct what’s a class and what’s a module. If there’s a call to new, you can be pretty sure the last element in the chain is a class, but otherwise the last element could be any constant—class, module, or other—and the elements on the left could be either classes or modules. In many cases, the fact that you can’t tell classes from modules in this kind of context doesn’t matter; what matters is the nesting or chaining of names in a way that makes sense. That’s just as well, because
you can’t tell what’s what without looking at the source code or the documentation. This is a consequence of the fact that classes are modules—the class Class is a subclass of the class Module—and in many respects (with the most notable exception being the fact that classes can be instantiated), their behavior is similar.

NOTE SYNTAX OF require/load VS. SYNTAX OF include[R4R page159]

You may have noticed that when you use require or load, you put the name of the item you’re requiring or loading in quotation marks, but with include, you don’t. require and load take strings as their arguments, whereas include takes the name of a module, in the form of a constant. The requirements to require and load are usually literal strings (in quotation marks), but a string in a variable will also work.

render partial的几个参数说明附例子

由render方法内部代码:
render_partial_collection(partial, collection, options[:spacer_template], options[:locals], options[:status])
引出的render partial的几种用法:
1. 当在render :partial时参数里有传:collection一个对象集合时(如下所示的@users),会自动在当前的view视图里循环此:partial
2. 当在render :partial时参数里有传:local时,在:local这个Hash中的key(var1,var2)可以在partial里作为局部变量调用,如下所示:


Controller:
def partial_methods
@users = User.find(:all)
end
View(partial_methods.rhtml):
<%= render :partial => 'user', :collection => @users, :locals => {:var1 => 'test_local_var1_in_partial(_user)', :var2 => 'test_local_var2_in_partial(_user)'}, :spacer_template => 'spacer_partial' %>
View(_user.rhtml)
<%= user.name %>
<br />
<%= var1 %>
<br />
<%= var2 %>
<br />
View(_spacer_partial.rhtml)
<p>
space line
<%= debug @users %>
</p>

在partial _user.rhtml中可以调用:locals中的var1和var2
3. 当在render :partial时参数里有传:spacer_template时,此参数对应的partial模板会被作为遍历collection进行render :partial的渲染时插入.
4. 在view中render :partial时其中的:status传什么值并不会影响view的渲染.
5. 在:spacer_template的partial中可以使用controller中传过来的变量,但不能取到赋于render :partial的:local变量,如var1,var2

Windows cmd 命令行下 SVN 命令执行结果为乱码的解决方法

在系统属性-高级-环境变量[加在当前的用户变量里即可,不一定要全局环境里设置]:
添加一个值:
APR_ICONV_PATH=${subversion_install_dir}\iconv

另同时从网上看到个关于文件提交后显示乱码的问题(未碰到过),也一起写在这里以备所需:
在环境变量中加参数:
LANG=zh_CN.UTF8

Linux Commands Line

Aticle source of Linux Commands Line

COMMAND DESCRIPTION
System information
arch show architecture of machine
uname -r show used kernel version
dmidecode -q show hardware system components - (SMBIOS / DMI)
hdaparm -i /dev/hda displays the characteristics of a hard-disk
hdparm -tT /dev/sda perform test reading on a hard-disk
cat /proc/cpuinfo show information CPU info
cat /proc/interrupts show interrupts
cat /proc/meminfo verify memory use
cat /proc/swaps show file(s) swap
cat /proc/version show version of the kernel
cat /proc/net/dev show network adpters and statistics
cat /proc/mounts show mounted file system(s)
lspci -tv display PCI devices
lsusb -tv show USB devices
date show system date
cal 2007 show the timetable of 2007
date 041217002007.00? set date and time - MonthDayhoursMinutesYear.Seconds
clock -w

save date changes on BIOS
linux commands line v1.1 - LinuxGuide.it
Shutdown, Restart of a system and Logout
shutdown -h now shutdown system
init 0
telinit 0
shutdown -r hours:minutes & planned shutdown of the system
shutdown -c cancel a planned shutdown of the system
shutdown -r now reboot
reboot
logout leaving session
linux commands line v1.1 - LinuxGuide.it
Files and Directory
cd /home enter to directory '/ home'
cd .. go back one level
cd ../.. go back two levels
cd go to home directory
cd ~utente go to home directory
cd - go to previous directory
pwd show the path of work directory
ls view files of directory
ls -F view files of directory
ls -l show details of files and directory
ls -a show hidden files
ls *[0-9]* show files and directory containing numbers
lstree show files and directories in a tree starting from root
mkdir dir1 create a directory called 'dir1'
mkdir dir1 dir2 create two directories simultaneously
mkdir -p /tmp/dir1/dir2 create a directory tree
rm -f file1 delete file called 'file1'
rmdir dir1 delete directory called 'dir1'
rm -rf dir1 remove a directory called 'dir1' and contents recursively
rm -rf dir1 dir2 remove two directories and their contents recursively
mv dir1 new_dir rename / move a file or directory
cp file1 file2 copying a file
cp dir/* . copy all files of a directory within the current work directory
cp -a /tmp/dir1 . copy a directory within the current work directory
cp -a dir1 dir2 copy a directory
ln -s file1 lnk1? create a symbolic link to file or directory
ln file1 lnk1 create a physical link to file or directory
touch -t 0712250000 fileditest modify timestamp of a file or directory - (YYMMDDhhmm)
linux commands line v1.1 - LinuxGuide.it
File search
find / -name file1 search file and directory into root filesystem from '/'
find / -user user1 search files and directories belonging to 'user1'
find /home/user1 -name \*.bin search files with '. bin' extension within directory '/ home/user1'?
find /usr/bin -type f -atime +100 search binary files are not used in the last 100 days
find /usr/bin -type f -mtime -10 search files created or changed within 10 days
find / -name \*.rpm -exec chmod 755 {} ; search files with '.rpm' extension and modify permits
find / -xdev -name \*.rpm search files with? '.rpm' extension ignoring removable partitions as cdrom, pen-drive, etc.…
locate \*.ps find files with the '.ps' extension - first run 'updatedb' command
whereis halt show location of a binary file, source or man
which halt show full path to a binary / executable
linux commands line v1.1 - LinuxGuide.it
Mounting a Filesystem
mount /dev/hda2 /mnt/hda2 mount disk called hda2 - verify existence of the directory '/ mnt/hda2'
umount /dev/hda2 unmount disk called hda2 - exit from mount point '/ mnt/hda2' first
fuser -km /mnt/hda2 force umount when the device is busy
umount -n /mnt/hda2 run umount without writing the file /etc/mtab - useful when the file is read-only or the hard disk is full
mount /dev/fd0 /mnt/floppy mount a floppy disk
mount /dev/cdrom /mnt/cdrom mount a cdrom / dvdrom
mount /dev/hdc /mnt/cdrecorder mount a cdrw / dvdrom
mount /dev/hdb /mnt/cdrecorder mount a cdrw / dvdrom
mount -o loop file.iso /mnt/cdrom mount a file or iso image
mount -t vfat /dev/hda5 /mnt/hda5 mount a Windows FAT32 file system
mount /dev/sda1 /mnt/usbdisk mount a usb pen-drive or flash-drive
mount -t smbfs -o username=user,password=pass //winclient/share /mnt/share mount a windows network share
linux commands line v1.1 - LinuxGuide.it
Disk Space
df -h show list of partitions mounted
ls -lSr |more show size of the files and directories ordered by size
du -sh dir1 estimate space used by directory 'dir1'
du -sh * | sort -rn? show size of the files and directories sorted by size
rpm -q -a --qf '%10{SIZE}\t%{NAME}\n' | sort -k1,1n show space used by rpm packages installed sorted by size (fedora, redhat and like)
dpkg-query -W -f='${Installed-Size;10}\t${Package}\n' | sort -k1,1n show space used by deb packages installed sorted by size (ubuntu, debian and like)
linux commands line v1.1 - LinuxGuide.it
Users and Groups
groupadd group_name create a new group
groupdel group_name delete a group
groupmod -n new_group_name old_group_name rename a group
useradd -c "Nome Cognome" -g admin -d /home/user1 -s /bin/bash user1 create a new user belongs "admin" group
useradd user1 create a new user
userdel -r user1 delete a user ( '-r' eliminates home directory)
usermod -c "User FTP" -g system -d /ftp/user1 -s /bin/nologin user1 change user attributes
passwd change password
passwd user1 change a user password (only by root)
chage -E 2005-12-31 user1 set deadline for user password
pwck check correct syntax and file format of '/etc/passwd'? and users existence
grpck check correct syntax and file format of '/etc/group'? and groups existence
newgrp group_name log in to a new group to change default group of newly created files
linux commands line v1.1 - LinuxGuide.it
Permits on File - use "+" to set permissions and "-" to remove
ls -lh show permits
ls /tmp | pr -T5 -W$COLUMNS divide terminal into 5 columns
chmod ugo+rwx directory1 set permissions reading (r), write (w) and (x) access to users owner (u) group (g) and others (o)
chmod go-rwx directory1 remove permits reading (r), write (w) and (x) access to users group (g) and others (or
chown user1 file1 change owner of a file
chown user1 -R directory1 change user owner of a directory and all the files and directories contained inside
chgrp gruppo1 file1 change group of files
chown user1:gruppo1 file1 change user and group ownership of a file
find / -perm -u+s view all files on the system with SUID configured
chmod u+s /bin/file_eseguibile set SUID bit on a binary file - the user that running that file gets same privileges as owner
chmod u-s /bin/file_binario disable SUID bit on a binary file
chmod g+s /home/public set SGID bit on a directory - similar to SUID but for directory
chmod g-s /home/public disable SGID bit on a directory
chmod o+t /home/comune set STIKY bit on a directory - allows files deletion only to legitimate owners
chmod o-t /home/comune disable STIKY bit on a directory
linux commands line v1.1 - LinuxGuide.it
Special Attributes on file - use "+" to set permissions and "-" to remove
chattr +a file1 allows write opening of a file only append mode
chattr +c file1 allows that a file is compressed / decompressed automatically by the kernel
chattr +d file1 makes sure that the program ignores Dump the files during backup
chattr +i file1 makes it an immutable file, which can not be removed, altered, renamed or linked
chattr +s file1 allows a file to be deleted safely
chattr +S? file1 makes sure that if a file is modified changes are written in synchronous mode as with sync
chattr +u file1 allows you to recover the contents of a file even if it is canceled
lsattr show specials attributes
linux commands line v1.1 - LinuxGuide.it
Archives and compressed files
bunzip2 file1.bz2 decompress a file called 'file1.bz2'
bzip2 file1 compress a file called 'file1'
gunzip file1.gz decompress a file called 'file1.gz'
gzip file1 compress a file called 'file1'
gzip -9 file1 compress with maximum compression
rar a file1.rar test_file create an archive rar called 'file1.rar'
rar a file1.rar file1 file2 dir1 compress 'file1', 'file2' and 'dir1' simultaneously
rar x file1.rar decompress rar archive
unrar x file1.rar decompress rar archive
tar -cvf archive.tar file1 create a uncompressed tarball
tar -cvf archive.tar file1 file2 dir1 create an archive containing 'file1', 'file2' and 'dir1'
tar -tf archive.tar show contents of an archive
tar -xvf archive.tar extract a tarball
tar -xvf archive.tar -C /tmp extract a tarball into / tmp
tar -cvfj archive.tar.bz2 dir1 create a tarball compressed into bzip2
tar -xvfj archive.tar.bz2 decompress a compressed tar archive in bzip2
tar -cvfz archive.tar.gz dir1 create a tarball compressed into gzip
tar -xvfz archive.tar.gz decompress a compressed tar archive in gzip
zip file1.zip file1 create an archive compressed in zip
zip -r file1.zip file1 file2 dir1 compress in zip several files and directories simultaneously
unzip file1.zip decompress a zip archive
linux commands line v1.1 - LinuxGuide.it
RPM Packages - Fedora, Red Hat and like
rpm -ivh package.rpm install a rpm package
rpm -ivh --nodeeps package.rpm install a rpm package ignoring dependencies requests
rpm -U package.rpm upgrade a rpm package without changing configuration files
rpm -F package.rpm upgrade a rpm package only if it is already installed
rpm -e package_name.rpm remove a rpm package
rpm -qa show all rpm packages installed on the system
rpm -qa | grep httpd show all rpm packages with the name "httpd"
rpm -qi package_name obtain information on a specific package installed
rpm -qg "System Environment/Daemons" show rpm packages of a group software
rpm -ql package_name show list of files provided by a rpm package installed
rpm -qc package_name show list of configuration files provided by a rpm package installed
rpm -q package_name --whatrequires show list of dependencies required for a rpm packet
rpm -q package_name --whatprovides show capability provided by a rpm package
rpm -q package_name --scripts show scripts started during installation / removal
rpm -q package_name --changelog show history of revisions of a rpm package
rpm -qf /etc/httpd/conf/httpd.conf verify which rpm package belongs to a given file
rpm -qp package.rpm? -l show list of files provided by a rpm package not yet installed
rpm --import /media/cdrom/RPM-GPG-KEY import public-key digital signature
rpm --checksig package.rpm verify the integrity of a rpm package
rpm -qa gpg-pubkey verify integrity of all rpm packages installed
rpm -V package_name check file size, permissions, type, owner, group, MD5 checksum and last modification
rpm -Va check all rpm packages installed on the system - use with caution
rpm -Vp package.rpm verify a rpm package not yet installed
rpm2cpio package.rpm | cpio --extract --make-directories? *bin* extract executable file from a rpm package
rpm -ivh /usr/src/redhat/RPMS/`arch`/package.rpm install a package built from a rpm source
rpmbuild --rebuild package_name.src.rpm build a rpm package from a rpm source
linux commands line v1.1 - LinuxGuide.it
YUM packages updater - Fedora, RedHat and like
yum install package_name download and install a rpm package
yum update update all rpm packages installed on the system
yum update package_name upgrade a rpm package
yum remove package_name remove a rpm package
yum list list all packages installed on the system
yum search package_name find a package on rpm repository
yum clean packages clean up rpm cache erasing downloaded packages
yum clean headers remove all files headers that the system uses to resolve dependency
yum clean all remove from the cache packages and headers files
linux commands line v1.1 - LinuxGuide.it
DEB packages - Debian, Ubuntu and like
dpkg -i package.deb install / upgrade a deb package
dpkg -r package_name remove a deb package from the system
dpkg -l show all deb packages installed on the system
dpkg -l | grep httpd show all rpm packages with the name "httpd"
dpkg -s package_name obtain information on a specific package installed on system
dpkg -L package_name show list of files provided by a package installed on system
dpkg --contents package.deb show list of files provided by a package not yet installed
dpkg -S /bin/ping verify which package belongs to a given file
linux commands line v1.1 - LinuxGuide.it
APT packages updater - Debian, Ubuntu e like
apt-get install package_name install / upgrade a deb package
apt-cdrom install package_name install / upgrade a deb package from cdrom
apt-get update update all deb packages installed on system
apt-get remove package_name remove a deb package from system
apt-get check verify correct resolution of dependencies
apt-get clean clean up cache from packages downloaded
linux commands line v1.1 - LinuxGuide.it
View file content
cat file1 view the contents of a file starting from the first row
tac file1 view the contents of a file starting from the last line
more file1 view content of a file along
less file1 similar to 'more' command but which allows backward movement in the file as well as forward movement
head -2 file1 view first two lines of a file
tail -2 file1 view last two lines of a file
tail -f /var/log/messages view in real time what is added to a file
linux commands line v1.1 - LinuxGuide.it
Text Manipulation
cat file_test | [operation: sed, grep, awk, grep, etc] > result.txt syntax to elaborate the text of a file, and write result to a new file
cat file_originale | [operazione: sed, grep, awk, grep, etc] >> result.txt syntax to elaborate the text of a file and append result in existing file
grep Aug /var/log/messages look up words "Aug" on file '/var/log/messages'
grep ^Aug /var/log/messages look up words that begin with "Aug" on file '/var/log/messages'
grep [0-9] /var/log/messages select from file '/var/log/messages' all lines that contain numbers
grep Aug -R /var/log/* search string "Aug" at directory '/var/log' and below
sed 's/stringa1/stringa2/g' example.txt replace "string1" with "string2" in example.txt
sed '/^$/d' example.txt remove all blank lines from example.txt
sed '/ *#/d; /^$/d' example.txt remove comments and blank lines from example.txt
echo 'esempio' | tr '[:lower:]' '[:upper:]' convert from lower case in upper case
sed -e '1d' result.txt eliminates the first line from file example.txt
sed -n '/stringa1/p' view only lines that contain the word "string1"
sed -e 's/ *$//' example.txt remove empty characters at the end of each row
sed -e 's/stringa1//g' example.txt remove only the word "string1" from text and leave intact all
sed -n '1,5p;5q' example.txt view from 1th to 5th row
sed -n '5p;5q' example.txt view row number 5
sed -e 's/00*/0/g' example.txt replace more zeros with a single zero
cat -n file1 number row of a file
cat example.txt | awk 'NR%2==1' remove all even lines from example.txt
echo a b c | awk '{print $1}' view the first column of a line
echo a b c | awk '{print $1,$3}' view the first and third column of a line
paste file1 file2 merging contents of two files for columns
paste? -d? '+' file1 file2 merging contents of two files for columns with '+' delimiter on the center
sort file1 file2 sort contents of two files
sort file1 file2 | uniq sort contents of two files omitting lines repeated
sort file1 file2 | uniq -u sort contents of two files by viewing only unique line
sort file1 file2 | uniq -d sort contents of two files by viewing only duplicate line
comm -1 file1 file2 compare contents of two files by deleting only unique lines from 'file1'
comm -2 file1 file2 compare contents of two files by deleting only unique lines from 'file2'
comm -3 file1 file2 compare contents of two files by deleting only the lines that appear on both files
linux commands line v1.1 - LinuxGuide.it
Character set and Format file conversion
dos2unix filedos.txt fileunix.txt convert a text file format from MSDOS to UNIX
unix2dos fileunix.txt filedos.txt convert a text file format from UNIX to MSDOS
recode ..HTML < page.txt > page.html convert a text file to html
recode -l | more show all available formats conversion
linux commands line v1.1 - LinuxGuide.it
Filesystem Analysis
badblocks? -v? /dev/hda1 check bad blocks in disk hda1
fsck? /dev/hda1 repair / check integrity of linux filesystem on disk hda1
fsck.ext2? /dev/hda1 repair / check integrity of ext2 filesystem on disk hda1
e2fsck? /dev/hda1 repair / check integrity of ext2 filesystem on disk hda1
e2fsck -j /dev/hda1 repair / check integrity of ext3 filesystem on disk hda1
fsck.ext3? /dev/hda1 repair / check integrity of ext3 filesystem on disk hda1
fsck.vfat? /dev/hda1 repair / check integrity of fat filesystem on disk hda1
fsck.msdos? /dev/hda1 repair / check integrity of dos filesystem on disk hda1
dosfsck? /dev/hda1 repair / check integrity of dos filesystems on disk hda1
linux commands line v1.1 - LinuxGuide.it
Format a Filesystem
mkfs /dev/hda1 create a filesystem type linux on hda1 partition
mke2fs /dev/hda1 create a filesystem type linux ext2 on hda1 partition
mke2fs -j /dev/hda1 create a filesystem type linux ext3 (journal) on hda1 partition
mkfs -t vfat 32 -F /dev/hda1 create a FAT32 filesystem
fdformat? -n /dev/fd0 format a floppy disk
mkswap /dev/hda3 create a swap filesystem
linux commands line v1.1 - LinuxGuide.it
SWAP filesystem
mkswap /dev/hda3 create a swap filesystem
swapon /dev/hda3 activating a new swap partition
swapon /dev/hda2 /dev/hdb3? activate two swap partitions
linux commands line v1.1 - LinuxGuide.it
Backup
dump -0aj -f /tmp/home0.bak /home? make a full backup of directory '/home'
dump -1aj -f /tmp/home0.bak /home? make a incremental backup of directory '/home'
restore -if /tmp/home0.bak restoring a backup interactively
rsync -rogpav --delete /home /tmp synchronization between directories
rsync -rogpav -e ssh --delete /home ip_address:/tmp? rsync via SSH tunnel
rsync -az -e ssh --delete ip_addr:/home/public /home/local synchronize a local directory with a remote directory via ssh and compression
rsync -az -e ssh --delete /home/local ip_addr:/home/public synchronize a remote directory with a local directory via ssh and compression
dd bs=1M if=/dev/hda | gzip | ssh user@ip_addr 'dd of=hda.gz' make a backup of a local hard disk on remote host via ssh
tar -Puf backup.tar /home/user make a incremental backup of directory '/home/user'
( cd /tmp/local/ && tar c . ) | ssh -C user@ip_addr 'cd /home/share/ && tar x -p' copy content of a directory on remote directory via ssh
( tar c /home ) | ssh -C user@ip_addr 'cd /home/backup-home && tar x -p'? copy a local directory on remote directory via ssh
tar cf - . | (cd /tmp/backup ; tar xf - ) local copy preserving permits and links from a directory to another
find /home/user1 -name '*.txt' | xargs cp -av --target-directory=/home/backup/ --parents find and copy all files with '.txt' extention from a directory to another
find /var/log -name '*.log' | tar cv --files-from=- | bzip2 > log.tar.bz2 find all files with '.log' extention and make an bzip archive
dd if=/dev/hda of=/dev/fd0 bs=512 count=1 make a copy of MBR (Master Boot Record) to floppy
dd if=/dev/fd0 of=/dev/hda bs=512 count=1 restore MBR from backup copy saved to floppy
linux commands line v1.1 - LinuxGuide.it
CDROM
cdrecord -v gracetime=2 dev=/dev/cdrom -eject blank=fast -force clean a rewritable cdrom
mkisofs /dev/cdrom > cd.iso create an iso image of cdrom on disk
mkisofs /dev/cdrom | gzip > cd_iso.gz create a compressed iso image of cdrom on disk
mkisofs -J -allow-leading-dots -R -V "Label CD" -iso-level 4 -o ./cd.iso data_cd create an iso image of a directory
cdrecord -v dev=/dev/cdrom cd.iso burn an ISO image
gzip -dc cd_iso.gz | cdrecord dev=/dev/cdrom - burn a compressed ISO image
mount -o loop cd.iso /mnt/iso mount an ISO image
cd-paranoia -B rip audio tracks from a CD to wav files
cd-paranoia -- "-3" rip first three audio tracks from a CD to wav files
cdrecord --scanbus scan bus to identify the channel scsi
linux commands line v1.1 - LinuxGuide.it
Networking - LAN and WiFi
ifconfig eth0 show configuration of an ethernet network card
ifup eth0 activate an interface 'eth0'
ifdown eth0 disable an interface 'eth0'
ifconfig eth0 192.168.1.1 netmask 255.255.255.0 configure IP Address
ifconfig eth0 promisc configure 'eth0' in promiscuous mode to gather packets (sniffing)
dhclient eth0 active interface 'eth0' in dhcp mode
route -n show routing table
route add -net 0/0 gw IP_Gateway configura default gateway
route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1 configure static route to reach network '192.168.0.0/16'
route del 0/0 gw IP_gateway remove static route
echo "1" > /proc/sys/net/ipv4/ip_forward activate ip routing
hostname show hostname
host www.linuxguide.it lookup hostname to resolve name to ip address and viceversa
ip link show show link status of all interfaces
mii-tool eth0 show link status of 'eth0'
ethtool eth0 show statistics of network card 'eth0'
netstat -tup show all active network connections and their PID
netstat -tupl show all network services listening on the system and their PID
tcpdump tcp port 80 show all HTTP traffic
iwlist scan show wireless networks
iwconfig eth1 show configuration of a wireless network card
linux commands line v1.1 - LinuxGuide.it
Microsoft Windows networks - SAMBA
nbtscan ip_addr netbios name resolution
nmblookup -A ip_addr netbios name resolution
smbclient -L ip_addr/hostname show remote shares of a windows host
smbget -Rr smb://ip_addr/share like wget can download files from a host windows via smb
mount -t smbfs -o username=user,password=pass //winclient/share /mnt/share mount a windows network share
linux commands line v1.1 - LinuxGuide.it
IPTABLES - firewall
iptables -t filter -L show all chains of filtering table
iptables -t nat -L show all chains of nat table
iptables -t filter -F clear all rules from filtering table
iptables -t nat -F clear all rules from table nat
iptables -t filter -X delete any chains created by user
iptables -t filter -A INPUT -p tcp --dport telnet -j ACCEPT allow telnet connections to input
iptables -t filter -A OUTPUT -p tcp --dport http -j DROP block HTTP connections to output
iptables -t filter -A FORWARD -p tcp --dport pop3 -j ACCEPT allow POP3 connections to forward chain
iptables -t filter -A INPUT -j LOG --log-prefix "DROP INPUT" logging sulla chain di input? Logging on chain input
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE configure a PAT (Port Address Traslation) on eth0 masking outbound packets
iptables -t nat -A PREROUTING -d 192.168.0.1 -p tcp -m tcp --dport 22 -j DNAT --to-destination 10.0.0.2:22 redirect packets addressed to a host to another host
linux commands line v1.1 - LinuxGuide.it
Monitoring and debugging
top display linux tasks using most cpu
ps -eafw displays linux tasks
ps -e -o pid,args --forest displays linux tasks in a hierarchical mode
pstree? mostra un albero dei processi sistema Shows a tree system processes
kill -9 ID_Processo force closure of the process and finish it
kill -1 ID_Processo force a process to reload configuration
lsof -p $$ display a list of files opened by processes
lsof /home/user1 displays a list of open files in a given path system
strace -c ls >/dev/null display system calls made and received by a process
strace -f -e open ls >/dev/null display library calls
watch -n1 'cat /proc/interrupts' display interrupts in real-time
last reboot show history reboot
lsmod display kernel loaded
free -m displays status of RAM in megabytes
smartctl -A /dev/hda monitoring reliability of a hard-disk through SMART
smartctl -i /dev/hda check if SMART is active on a hard-disk
tail /var/log/dmesg show events inherent to the process of booting kernel
tail /var/log/messages show system events
linux commands line v1.1 - LinuxGuide.it
Other useful commands
apropos ...keyword display a list of commands that pertain to keywords of a program , useful when you know what your program does, but you don't know the name of the command
man ping display the on-line manual pages for example on ping command
whatis ...keyword displays description of what a program does
mkbootdisk --device /dev/fd0 `uname -r` create a boot floppy
gpg -c file1 encrypt a file with GNU Privacy Guard
gpg file1.gpg decrypt a file with GNU Privacy Guard
wget -r www.example.com download an entire web site
wget -c www.example.com/file.iso download a file with the ability to stop the download and resume later
echo 'wget -c www.example.com/files.iso' | at 09:00 start a download at any given time
ldd ssh show shared libraries required by ssh program
alias hh='history' set an alias for a command - hh = history