crossz

Archive for the ‘howto’ Category

HOWTO: Version control using BZR vs RCS

In howto, linux on August 3, 2009 at 8:25 pm

No matter programming or documents editing, BZR will work for you to provide easier and better version control.

Here are some simple steps for docs processing:
======================

  1. bzr init
    create a folder, ‘text’, then create a file, ‘test1.txt’, in which we type in a paragraph. Then ‘bzr init’ to let bzr know this is the folder where bzr should monitor.
  2. bzr add
    ‘bzr add test1.txt’. Now bzr knows where and what to monitor.
  3. bzr diff
    add more text into the test1.txt, then run ‘bzr diff’ to test whether there is any changes.
  4. bzr commit -m ‘description’
    if there are some changes, and you want to create another version for that for the current version backup. run ‘bzr commint -m “some description”‘.
  5. bzr log
    to check verisons.

    more changes and more commits here.
  6. bzr branch -r
    For example we just want to retrive the first version, run ‘bzr branch `pwd` -r 1′. A new folder with the name of current folder ‘text’ will be created, in which our text1.txt 1st version is there.

RCS: (same procedure)
===================

  1. create folder RCS
    this step can be ignored, the rcs information will be saved in the same folder with the file you are editing. Otherwise, the file info file will be saved in the RCS folder.
  2. ci -u test1.txt
    ver 1.1 is created. RCS uses the concept of ‘lock’. -l -r -u are similar, to keep the text file locked when new version is registered.
  3. co -l test1.txt
    (if without this step, new version can not be registered. because ‘no lock’, prompted by ‘ci’, is this for synchronization?) So to lock the text file to make it writable (very weird concept, locked == writable???). Then add more text in it.
  4. rcsdiff test1.txt
    To check what’s different from the registered version.
  5. ci -u test1.txt (same with step2)
    The version number increment with 0.1.’ci -r2 -u test1.txt’ to make the version increment by 1.0.

    more changes and more commits here.
  6. co -l1.1 test1.txt
    Retrive version 1.1 to replace the current editing file. -l -r -u are similar, just -u makes the file non-writeable, while -l make the file writeable. Good practice is ‘ci -u’ and ‘co -l’, so that when the new version is registered by ci, the file will become ‘non-writable’='can not modify’='No lock’. (weired)

Note: no space between ‘-r2′ and ‘-u1.1′.

Conclusion:
==================
BZR is more user friendly, and Ubuntu uses it on launchpad.net.
RCS is quite mature (old), LYX uses it as version control. So even I don’t like it, but I have to still use it, because I love Lyx.

HOWTO: autoconf & automake HELLO WORLD

In howto, linux on August 2, 2009 at 7:43 pm

1) Create sources, “Makefile.am”
2) `autoscan`:create configure.scan
3) Rename “configure.scan” to “configure.ac”
4) `autoheader`:create config.h.in for automake
5) Add AM_INIT_AUTOMAKE to “configure.ac”, just after AC_INIT()
6) `aclocal`:create necessary macros in aclocal.m4 for automake.
7) `automake ­­–add-­missing –­­copy`: create Makefile.in from Makefile.am
8) `autoconf`:create configure
9) `./configure`:check and create Makefile
10) `make`
11) `make install`

if you modify your source…
1) Run `autoscan` again
2) Compare configure.scan with configure.ac
* Update configure.ac
3) Run `autoreconf`

***********************
# Makefile.am for hello.c
bin_PROGRAMS=hello
hello_SOURCES=hello.c
***********************

To simplify it:
===============
1) c/cc files, Makefile.am
2) autoscan => mv configure.scan configure.ac => add Add AM_INIT_AUTOMAKE after AC_INIT

3) autoheader
4) aclocal
5) automake

6) autoconf autoscan,(compare configure.ac),autoreconf

7) ./configure && make && make install

Simplest ‘make’
=====================
Hello.c:


#include
int main(int argc, char* argv[])
{
printf(“Hello, world!\n”);
return 0;
}

Makefile:


# Makefile: A standard Makefile for hello.c
all: hello
clean: rm -f hello

Run: make, to create executable bin file.

HOWTO: autoconf & automake

In howto, linux on August 2, 2009 at 3:21 pm
  1. Write makefile.am templates.
  2. Write configure.in.
    2.1 Use autoscan to generate a template.
    2.2 Specialize the generated configure.scan to suit your project.
    2.3 Rename configure.scan to configure.in.
  3. Run automake to generate Makefile.in from Makefile.am (automake scans configure.in to find out more about the project).
  4. Run aclocal to make local copies of all autoconf macros. These macros are then included in the project.
  5. Run autoconf to generate configure.

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

automake
automake, when used in conjunction with autoconf, makes creating Makefiles easy. automake operates on a Makefile.am to generate Makefile.in . Makefile.in is then processed by the configure script to generate Makefile. Makefile.am has macros that are processed by automake. A sample Makefile.am is shown below. Variables surrounded by @’s are automatically propagated without change to Makefile.in. The configure script, when parsing Makefile.in into Makefile, makes the necessary substitutions (for example, @LDFLAGS@ may get expanded to “-lm -lthread).
        
        bin_PROGRAMS = gpstat
        gpstat_SOURCES = about.c interface.c multi-plot.c attach_process.c
        gpstat_LDFLAGS = @LDFLAGS@ @GTK_LIBS@ -lgthread
        INCLUDES = @GTK_CFLAGS@

automake knows the rules to create object files and executables for the platform it is running on. The above sets of macros tell automake that:
1. The final executable is to be named gpstat. 
2. The sources for gpstat are the value of gpstat_SOURCES. 
3. Add @LDFLAGS@, @GTK_LIBS@, and -lgthread to the link line. (The configure script will replace LD_FLAGS and GTK_LIBS with their proper values.) 
4. Include the variable $INCLUDES in the compilation line.

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

autoconf

The configure script is generated from configure.in using autoconf. configure.in is a normal text file that contains several autoconf macros. These macros specify what tests to carry out. General uses of the configure script include:
1. Find machine information (Hostname, version…). 
2. Find the path to a particular program (bison, lex, …). 
3. Find out if a tool supports a feature (for example, if the compiler supports bool). 
4. Check if the required libraries are available on your system. 
5. Process Makefile.in to generate Makefile.

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

automake also provides autoscan, a utility script that will help you create a template configure.in. autoscan scans the program sources and adds suitable macros to configure.in. It creates configure.scan, which then should be renamed configure.in, after making suitable modifications.
automake also provides a program called aclocal. aclocal makes local copies of all autoconf macros, so that other developers can modify the configure.in file.

You can combine the invocation of automake, aclocal, and autoconf as follows:
foo@pastwatch$ aclocal&& automake && autoconf

Sample:
Comments can either begin with dnl or a #. The following is a small, well-documented, self-explanatory configure.in file.
#============================start configure.in============================
dnl Process this file with autoconf to produce a configure script.
dnl notice how comments are preceded by “dnl”
# comments can also begin with a #
dnl This macro is a must, and this tests if the configure
dnl script is running in the correct directory
AC_INIT(src/about.c)
dnl This macro tells the configure script to put
dnl “defines” in a file rather than the command line.
AM_CONFIG_HEADER(config.h)
dnl get the flags
CFLAGS=”${CFLAGS=}”
dnl this macro is used to get the arguments supplied
dnl to the configure script (./configure –enable-debug)
dnl Check if we have enable debug support.
AC_MSG_CHECKING(whether to enable debugging)
debug_default=”yes”
AC_ARG_ENABLE(debug, [ --enable-debug=[no/yes] turn on debugging
[default=$debug_default]],, enable_debug=$debug_default)
dnl Yes, shell scripts can be used
if test “x$enable_debug” = “xyes”; then
CFLAGS=”$CFLAGS -g -DDEBUG”
AC_MSG_RESULT(yes)
else
CFLAGS=”$CFLAGS -O3 -ffast-math -mcpu=v8 -mtune=ultrasparc”
AC_MSG_RESULT(no)
fi
dnl tells us that we require autoconf with version greater than
dnl 2.12 to generate configure
AC_PREREQ(2.12)
dnl get system information
AC_CANONICAL_SYSTEM
dnl Since foo is currently untested on any os other
dnl than solaris, so check the os and quit if not solaris.
UNSUPPORTED_OS=”FOO is currently unsupported on your platform.
If you are interested in making it work on your platform, you are
more than *welcome*. Contact foo@bar.sun.com for details.”
case “${target_os}” in
solaris*)
echo ===========================================================
echo Setting up build environment for ${target_cpu}${target_os}
echo ===========================================================
;;
*)
AC_MSG_ERROR($UNSUPPORTED_OS)
esac

# Build time sanity check…
AM_SANITY_CHECK
dnl get path to install program
AC_PROG_INSTALL
AC_ARG_PROGRAM
VERSION=0.1
PACKAGE=foo
dnl initialize automake
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl Checks for c compiler.
AC_PROG_CC
dnl check for standard c headers
AC_HEADER_STDC
dnl export these variable (so Makefile substitutions
dnl can be made.
AC_SUBST(CFLAGS)
AC_SUBST(LDFLAGS)
dnl Checks for libraries.
dnl AC_CHECK_LIB(gthread, g_thread_init)
dnl AC_CHECK_LIB(pthread, pthread_create)
dnl Check for /proc
AC_CHECK_FILE(/proc,,AC_MSG_ERROR(Cannot
find /proc. See the file ‘README’ for help.))
dnl check for procfs.h
AC_CHECK_HEADER(procfs.h,,
AC_MSG_ERROR(Cannot
find procfs.h. See the file ‘README’ for help.))
dnl Checks for header files.
AC_CHECK_HEADERS(fcntl.h)
AC_CHECK_HEADERS(time.h)
dnl Checks for typedefs, structures, and compiler characteristics.
AC_C_CONST
AC_TYPE_PID_T
dnl Create these files, making substitutions if necessary
AC_OUTPUT([
src/Makefile
Makefile
]
)
#============================end configure.in============================

HOWTO: get stdin from shell in Gedit External Tool

In howto, linux on July 27, 2009 at 11:56 pm

The following code can get the input from Gedit External Tool as you assigned for ‘input’.

#!/bin/bash
search=`xargs`
echo $search

The trick is the command of xargs.

Also available Environment Variables in Gedit External Tool are:
=====================
GEDIT_CURRENT_DOCUMENT_URI
GEDIT_CURRENT_DOCUMENT_NAME
GEDIT_CURRENT_DOCUMENT_SCHEME
GEDIT_CURRENT_DOCUMENT_PATH
GEDIT_CURRENT_DOCUMENT_DIR
GEDIT_DOCUMENTS_URI
GEDIT_DOCUMENTS_PATH

An example: compile java file and run it
=========================
javac $GEDIT_CURRENT_DOCUMENT_NAME && java -cp . `echo $GEDIT_CURRENT_DOCUMENT_NAME | sed s/.java//`

Simplest procedure to TRIPLE BOOT on Macbook

In howto on July 21, 2009 at 8:44 am

The must:

  • Only ONE partition for Linux; Only ONE partition for Windows. (to satisfy Windows)
  • Windows must locates at the last partition. (to satisfy Macbook)
  • Before installing, ensure the partitions are ready and good! (Disk Utility normally can not do this, or do half of this task. Because it will create several ’spare spaces’ between each partitions made by it, these partitions always make the Windows installation fail due to more than 4 primary partitions existing. But Disk Utility can create one more partition from the original one whole partition, then split it using other ways, which includes ‘diskutil’ in Mac, ‘gparted’ from Linux Livecd or even the Windows installer during Windows setup). Any partitions modification will make Windows can not boot up even synced by rEfit.
  • - If Windows has been installed by Boot Camp. Try to change boot.ini in my windows partition (disk util create a new partition between mac and windows and messed up my boot.ini, the partition it tried to boot (third) is now linux Hd instead of windows (become 4th. This might be your problem. It gave me BSoD right after splash screen)

So the procedure:

  1. Partitioning (DO NOT USE BOOT CAMP ASSISTANT)
  2. sync mbr/gpt using rEfit. (maybe can be ignored)
  3. Install Winxp on the 4th (last) partition.
  4. sync mbr/gpt using rEfit.(maybe can be ignored)
  5. Install Linux.

HOWTO: run remote X11 applications

In howto, linux on July 17, 2009 at 4:33 pm

The server is running on Linux. To run the remote server applications on my own machine:

  • On Windows:
    =======================
    1. Install Xming as the X11 server.
    2. Run Putty, as ssh client, with the X11 forwarding arguments: ‘localhost:0′ or ‘:0′, or even with blank only enable forwarding.
  • On Mac OSX
    =======================
    1. run: ssh -X -l username 192.168.1.XXX
    * using Putty: with the X11 forwarding arguments: ‘:0′!!!!!!!!
  • On Linux
    =======================
    1. run: ssh -X -l username 192.168.1.XXX
    * using Putty: with the X11 forwarding arguments: ‘:0′ or blank.

HOWTO: remove files older than N days

In howto, linux on July 8, 2009 at 11:07 pm

Command Syntax

find /path/to/files* -mtime +5 -exec rm {} \;

Note that there are spaces between rm, {}, and \;

Usage:
======================
Extremely useful for Miro, because it doesn’t delete files unwatched. So with this command added in /usr/bin/miro, the Miro library will keep only latest videos no matter you watch it or not.

Explanation
=======================
The first argument is the path to the files. This can be a path, a directory, or a wildcard as in the example above. I would recommend using the full path, and make sure that you run the command without the exec rm to make sure you are getting the right results.
The second argument, -mtime, is used to specify the number of days old that the file is. If you enter +5, it will find files older than 5 days.

The third argument, -exec, allows you to pass in a command such as rm. The {} \; at the end is required to end the command.

Command from: http://www.howtogeek.com/howto/ubuntu/delete-files-older-than-x-days-on-linux/

HOWTO: add shared libraries to lib path in Linux

In howto, linux on July 2, 2009 at 11:21 pm
Permanent way:
  • Create a new file in /etc/ld.so.conf.d/ called .conf
  • Edit the file and add a line per directory of shared libraries (*.so files), it will look something like:
/usr/lib/APPLICATION/libReload the list of system-wide library paths:
  • sudo ldconfig
====================================

Temporary way:

  • export LD_LIBRARY_PATH=/your/lib/path

On Mac, the dynamic library path is $DYLD_LIBRARY_PATH

HOWTO[zen-cart]: disable random on homepage

In howto on May 29, 2009 at 1:56 pm
At beginning.
Copy featured_products.php / new_products.php from /includes/modules/ to /includes/modules/YOURTEMPLATE, then start to edit it.

1. append “order by featured_sort_id DESC” to the two select statements

2. change ExecuteRandomMulti() to Execute()

3. change MoveNextRandom() to MoveNext()

The procedure of Zen-cart display home page

In howto on May 26, 2009 at 8:12 pm
1) tpl_main_page.php
++++++++++++++
require($body_code);
———————-

2) $body_code is defined in /includes/templates/template_default/common/main_template_vars.php
Here, firstly check whether it’s overridden or not by the current template. If not (/not exist overridden main_template_vars.php, then load the default tpl_SOME_PAGE_default.php)
 
3) If overridden, in the zen-cart pages system, /includes/modules/pages/index/main_template_vars.php defines which tpl file should be loaded to display the home page.

  • tpl_index_categories.php // $category_depth==’nested’ 有子分类
  • tpl_index_product_list.php // $category_depth==’products’ || zen_check_url_get_terms() 列出所有
  • tpl_index_default.php // the default tpl_SOME_PAGE_default.php 主页默认内容

HOWTO: Add css for IE within zen-cart

In howto on May 26, 2009 at 7:59 pm
1) Prepare a css file for IE, called ie7.css, located in /includes/templates/template_default/my

2) Add the following codes:
+++++++++++++++++++++++++++++++
echo ‘<!–[if lte IE 7]><link rel=”stylesheet” href=”‘ . $template->get_template_dir(‘.css’,DIR_WS_TEMPLATE, $current_page_base,’my’) . ‘/ie7.css” />’.”\n”.’<![endif]–>’;
————————————————-

around the following codes in /includes/templates/template_default/common/html_header.php
+++++++++++++++++++++++++++++++
/**

 * load all template-specific stylesheets, named like “style*.css”, alphabetically

 */

  $directory_array = $template->get_template_part($template->get_template_dir(‘.css’,DIR_WS_TEMPLATE, $current_page_base,’css’), ‘/^style/’, ‘.css’);

  while(list ($key, $value) = each($directory_array)) {

    echo ‘<link rel=”stylesheet” type=”text/css” href=”‘ . $template->get_template_dir(‘.css’,DIR_WS_TEMPLATE, $current_page_base,’css’) . ‘/’ . $value . ‘” />’.”\n”;

  }
—————————————————

HOWTO: The Zen Cart Execution Process

In howto on May 26, 2009 at 1:39 pm

Zen Cart, like most open-source code, is a largly undocumented.
Luckily for us, it also has a habit of mixing in much of it’s
program/application logic with it’s actual HTML design, so it’s not
only undocumented, it’s also hard to browse the HTML code. To top it
off, it also has a dynamic template loader, which means that the
program logic and HTML templates could be in any one of four different
directories. Also undocumented, and of dubious usefullness.

The result is that it’s not only difficult to browse through the
program logic and HTML code, but you often don’t even know which files
are going to get loaded.

This document is an attempt to sort through the overarching structure of how Zen Cart tends to work.

index.php steps:

Here’s where all of action begins.

  1. it loads ‘includes/application_top.php’
  2. if $main_page isn’t set, it gets set to ‘index’
  3. if the directory ‘includes/modules/pages/$main_page’ doesn’t exist, $main_page gets set to ‘index’
  4. it loads all of the files starting with ‘header_php’ in ‘includes/modules/pages/$main_page’
  5. now it loads ‘html_header.php’ from the first first place it finds it from the following directories
    1. includes/templates/mytemplate/$main_page/
    2. includes/templates/template_default/$main_page/
    3. includes/templates/mytemplate/common/
    4. includes/templates/template_default/common/

  6. now it does the same thing for finding and loading ‘main_template_vars.php’
  7. now it does the same thing for finding and loading ‘tpl_main_page.php’
  8. Finally it displays the ‘</html>’ tag. Why display it here when the ‘<html>’ tag is displayed somewhere else? Who knows.

application_top.php steps:

This file will load in all of general definitions used site-wide,
initialize some site-wide classes ($template, $db) and do other general
stuff.

html_header.php steps:

The default html_header.php file will simply create all of the HTML up to the </head> tag
It loads ‘includes/modules/meta_tags.php’, which uses a bloated switch statement to figure out what the site’s title, meta-keywords, and meta-description should be.
It tries to find the css directory, and loads in it all stylesheets that begin with ’style’ and end with ‘.css’
It does the same thing for the jscript directory, and tries to load all files that begin with ‘jscript_’ and end with ‘.js’

main_template_vars.php steps:

it simply sets $body_code to the first of:

  1. includes/modules/pages/$main_page/main_template_vars.php
  2. includes/templates/mytemplate/$main_page/tpl_{$main_page}_default.php
  3. includes/templates/template_default/$main_page/tpl_{$main_page}_default.php
  4. includes/templates/mytemplate/templates/tpl_{$main_page}_default.php
  5. includes/templates/template_default/templates/tpl_{$main_page}_default.php

that’s it.

tpl_main_page.php steps:

this file lays out the basic page.

  1. <body>
  2. loads the ‘includes/modules/header.php’ file
  3. if the left column is enabled, it loads ‘includes/modules/column_left.php’
  4. it loads the file set in $body_code
  5. if the right column is enabled, it loads ‘includes/modules/column_right.php’
  6. loads ‘includes/modules/footer.php’
  7. </body>

includes/modules/pages/$main_page/main_template_vars.php steps:

this
is where the meat of the actual content if loaded and displayed.
it typically does all of the program logic first, sets all of the
necessary variables, and then loads the template file. As usual, the
template file is loaded from the first of the following:

  1. includes/templates/mytemplate/$main_page/
  2. includes/templates/template_default/$main_page/
  3. includes/templates/mytemplate/templates/
  4. includes/templates/template_default/templates/

The standard is that the template file will be named ‘tpl_SOMENAME.php’. Note that it doesn’t end with ‘_default.php’. The undocumented naming convention is that files that end with ‘_default.php’ are files that get loaded with it can’t find the ‘includes/modules/pages/$main_page/main_template_vars.php’ file.

tpl_{$main_page}_default.php steps:

If it doesn’t find the
above file and it instead finds a tpl_*_default.php file, then it means
that all of the program logic and variables will be mixed up with the
actual displayed HTML code. In Zen-Cart’s defense, this generally means
that there’s not a lot of program logic to be had here, hardly any
really, but it’s still damn annoying to be mixing the program logic
with design. No sir, I don’t like it one bit.

Future Updates

Eventually this document will also cover the process by which the program loads in the language files, such as “english.php” and the content files like “privacy.php” and “conditions.php.”
The Zen Cart creators actually created these files with the idea that
they would be a part of your custom template, which is a clear
violation of the content/design seperation.

This document will also cover sideboxes (which requires a whole
nother custom template directory). As an interesting sidenote, when you
switch to a new template, all of the sideboxes get turned off. The
level of user-unfriendliness of Zen Cart is amazing to me sometimes.

This article is from: http://lifefeed.net/zencart/program_process.php

HOWTO: [MAC] Move User to a different partition

In howto, mac on May 16, 2009 at 1:35 am

Move User to a different partition

As we have hopefully set up a separate partition for our private data, here’s the bash-way of moving a home. (based on this article)

  1. in ‘Disk Utility’ to setup a new partition with ‘Mac OS Extended (Journaled)’ format, I call it ‘home’.
  2. copy the whole home to your new partition:

    # sudo su -

    # cp -Rp /Users/username /Volumes/username
  3. Now we use Directory Services which can be accessed by dscl (Directory Services Command Line):
    
    # sudo su -# dscl localhost> cd /Local/Default/Users> change username dsAttrTypeNative:home /Users/username /Volumes/home/username> exit

Reboot, verify if your user data is at the new spot and then delete it from the old spot (/Users/username).

HOWTO: firefox cannot save username & password on hotmail.com

In bug, howto on April 24, 2009 at 12:17 pm

If it just happens on that site try clearing the hotmail cookies. Select Tools > Options > Privacy – In the Cookies section click “Show Cookies…” to access the option for removing cookies.

If you can not use the “remember me” option on other sites as well, a likely cause is the file that stores cookies is corrupt. To test this close Firefox, go to your profile folder and rename cookies.sqlite to cookies.tmp
Restart Firefox, log into those sites and then see if it remembers the logins.

Also make sure that cookies are being accepted and not being deleted when Firefox closes. Go to Tools > Options > Privacy, on that dialog you can make sure that cookies are being accepted, then in the private data section make sure that Firefox is not set to delete cookies when Firefox closes. Also click on the Exceptions button in the cookies section to make sure cookies from those sites are not being blocked.

Next check any internet security software to make sure it is not blocking or deleting cookies. Some internet security software has privacy options that can block or delete cookies.

HOWTO: gtalk in pidgin

In howto on April 4, 2009 at 3:15 pm

Force old (port 5223) SSL: Checked
Allow plaintext auth over unencrypted streams: Un-Checked
Connect Port: 443
Connect Server: talk.google.com
Proxy type: Use Global Proxy Settings

HOWTO: outer DIV can not cover element with FLOAT style

In bug, css, howto on March 31, 2009 at 12:03 am
Normally, all the content in the outer DIV will inherit the css styles from it, such as background.
But when the float style is used for inner tag, this part of content may come out of the outer DIV. Also, if you are using Firebug in Firefox, when your mouse is hovering on the outer DIV, the browser then will not cover all the parts inside the DIV.

All are because the FLOAT style.

In this article, Simple Clearing of Floats, 4 methods are intorduced to fix this ‘bug’, which appears in Firefox, Chrome, while not in IE, this did supprise me. Normally IE is more buggy in my opinion.

My favorite method is to append the outer style with ‘overflow:auto’. Then, the floated part will be covered by the outer DIV, no matter the background issue or the selection problem in Firebug.

See also: (other conflicts with some attributes)
text-align for normal div tag ( this will not work 100% in table with align attribute, this will be ignored) and align attribute for table: here


style of marquee in div ( style of div will not work 100%)

HOWTO: Joomla CSS drop-down menu (javascript for IE6)

In css, howto, joomla on March 23, 2009 at 7:58 pm
Prolog
===================

At beginning, I compared the two drop-down menu raw methods:
http://docs.joomla.org/Creating_a_CSS_Drop_down_Menu
http://www.alistapart.com/articles/dropdowns

Both of them are using suckerfish CSS methods to diminish javascript usage from DHTML.
Because IE doesn’t support ‘hover’ status on ‘li’, only on ‘a’. to solve this problem, there is some javascript for IE, using ‘onmouseover’.

The difference between the above two javascript methods, one uses 1)’document.THECLASSOFTAG.getElementsByTagName(“LI”)’ to retrieve <li>, while 2) the other uses ‘navRoot.childNodes……’ with loop to find out all <li> within the range, which defined by ‘document.getElementById(“THEIDOFTAG”)’.

Javascript in method 1) is NOT supported by IE 6 and 7, even Firefox. This only affect IE 6, others don’t need javascript to achieve this drop-down menu.

But, the ‘hiding method’, which uses ‘left:-98%’ to hide the submenu from screen is very good and secure, compared with the method using ‘display: none’, which used in method 2).

Method 2) is just traditional way to parse the html document. But it’s for pure HTML practice, not exactly for Joomla.

Therefore, I modified above 2 methods, to make it easily setup on Joomla 1.5.

Make Joomla Drop-Down Menu without install anything
===================================

1. Create your Menu with the following Hierarchy:

Menu 1( globalnews ).

– Menu 1 Sub Menu 1 (test).

– Menu 1 Sub Menu 2 (test).

Menu 2( uknews ). // this menu have no submenu

2. Make sure the parameters are set to.

• Menu Style is set to List.

• Always show sub-menu Items is set to Yes.

• Menu Class Suffix is set to -nav – you can pick you own, but then make sure you change it in CSS & JS files. So you will get your menu within

All the menu strcture will be like this ( this can be found from your scource from IE or Firefox:
————————————————-

<div class="pill_m">
<div id="pillmenu">
<ul class="menu-nav">
<li class="parent item63"><a href="/globalnews"><span>Globalnews</span></a>
<ul>
<li class="item75"><a href="/uknews"><span>test</span></a></li>
<li class="item76"><a href="/uknews"><span>testtest</span></a></li>
</ul>
</li>

<li class="item61"><a href="/uknews"><span>uknews</span></a></li>

</ul>
</div>
</div>

—————————————
here, the ‘div class=”pill_m”‘ and ‘div id=”pillmenu”‘ is what I put in the templates/MYTEMPLATE/index.php to help me setup the css style.

3. Insert this piece of JS in your template index.php ‘head’ tag, or in java script file that’s called from index.php.
—————————————
<!--[if IE]>
<script type="text/javascript">
window.addEvent('domready', function()
{
if (document.getElementById) {
//navRoot = document.getElementById("pillmenu");
ulTag = pillmenu.childNodes(0);//navRoot==pillmenu, which is a 'id'.
for (i=0; i<ulTag.childNodes.length; i++) {
node = ulTag.childNodes[i];
if (node.nodeName=="LI") {
node.onmouseover=function() {
temp_cn=this.className;
this.className=temp_cn.replace(temp_cn, "sfhover")
//this.className+="sfhover";
}
node.onmouseout=function() {
this.className=this.className.replace("sfhover", temp_cn);
}
}
}
}
}
);
</script>
<![endif]-->
—————————————-
Note:

  • Here <!–[if IE]> make this script just work for IE, to improve the performance of Fifrefox,safari, they do need such javascript to make the dorp-down menu.
  • window.onload=INLINE_FUNCTION_NAME, is normally used to make specific javascript runnable when the html document is loaded, BUT, in joomla, there always a lot of javascript block in the pages, and one page only can have one onload function. To solve this, ‘domready’ from mootools helps a lot and improves the loading speed very much. See domready vs load.
  • Even using general javascript function, like “function FUNCTION_NAME() {… }; FUNCTION_NAME();”, will not work properly, because when the function started, maybe the html document is not fully loaded. Still, mootools domready event helps.

4. Insert mootool.js (optional for Joomla, But required for local html test)
—————————————————

<script type="text/javascript" src="mootools.js">

</script>

—————————————————
You should go to mootools.net to download the latest mootools.js.

5. Here the corresponding CSS
—————————————————-
<style type="text/css">
/*****************************************/
/*** Copied menu ***/
/*****************************************/
.pill_m {
text-align: center;
margin: 0 auto;
padding: 0;
background: url(../images/menu.jpg) top center repeat-x;
width: 100%;
height: 41px;
}
#pillmenu {
margin:0 auto;
width:960px;
}
#pillmenu ul {
margin: 0;
padding: 0 22px;
list-style: none;
}
#pillmenu li {
float: left;
margin: 0;
padding: 0;
height: 49px;
background: url(../images/menu_li.jpg) top right no-repeat;
}
#pillmenu li:hover {
}
#pillmenu li a#active_menu-nav {
}
#pillmenu li a {
font-family: Verdana,Helvetica,Arial,sans-serif;
font-size: 13px;
/* float: left;*/
display: block;
line-height: 39px;
padding: 0 24px 0 16px;
color: #111111;/*color: #FFFFFF;*/
text-decoration: none;
font-weight: bold;
text-transform:uppercase;
}
#pillmenu li a:hover {
color: #CCCCCC;
}
.pill_m li ul { /* second-level lists */
position: absolute;
left: -98%; /* using left instead of display to hide menus because display: none isn’t read by screen readers */
}
.pill_m li:hover ul, .pill_m li.sfhover ul { /* lists nested under hovered list items */
left: auto; /* change is to 10px, 20px, etc for indenting the sub menue */
z-index: 100;
}
#pillmenu li.parent ul li, #pillmenu li.sfhover ul li{
height:20px;
background: url(../images/menu.jpg) top center repeat-x;
}
#pillmenu li.parent ul li a, #pillmenu li.sfhover ul li a{
font-size: 10px;
line-height: 20px;
}
</style>
—————————————————-
Here the background can be changed as you want, or set it ‘none’ or other colors.
Have a try, If you got any problems, comment here to let me know.

HOWTO: joomla template

In howto, joomla on March 10, 2009 at 6:18 pm
What’s in joomla template directory?

FOLDERS:
==================

  • /css:(requied)  all kinds of css files.
  • /images:(requied) all the images will be used by the template.
  • /html: (optional) for component/module override. details: http://developer.joomla.org/tutorials/165-understanding-output-overrides-in-joomla.html

FILES:
=================

  • index.php(requied): template html+php file
  • index.html(requied): blank files
  • params.ini(requied): joomla need this file as writeable, to save configuration about his template.
  • template_thumbnail.png(requied): joomla need this file for preview
  • templateDetails.xml(requied): joomla need this file for template installation.
  • favicon.ico: (optional) favicon file.
  • component.php : (optional) for article printable layout, only display selected parts.

HOWTO: joomla template

In howto, joomla on March 10, 2009 at 6:18 pm
What’s in joomla template directory?

FOLDERS:
==================

  • /css:(requied)  all kinds of css files.
  • /images:(requied) all the images will be used by the template.
  • /html: (optional) for component/module override. details: http://developer.joomla.org/tutorials/165-understanding-output-overrides-in-joomla.html

FILES:
=================

  • index.php(requied): template html+php file
  • index.html(requied): blank files
  • params.ini(requied): joomla need this file as writeable, to save configuration about his template.
  • template_thumbnail.png(requied): joomla need this file for preview
  • templateDetails.xml(requied): joomla need this file for template installation.
  • favicon.ico: (optional) favicon file.
  • component.php : (optional) for article printable layout, only display selected parts.

HOWTO: disable horizontal scroll bar using CSS

In howto on January 30, 2009 at 2:03 am
<style>

overflow-x:hidden;

</style>

if you put this in <head> it will disable horizontal scrollbars

HOWTO: disable horizontal scroll bar using CSS

In howto on January 30, 2009 at 2:03 am
<style>

overflow-x:hidden;

</style>

if you put this in <head> it will disable horizontal scrollbars

javascript: enter to execute

In JavaScript, howto on January 13, 2009 at 11:46 am


<html>

<head>

<script type="text/javascript">

    function getrefno(reno, helperMsg){

        if(reno.value.length == 0){

            alert(helperMsg);

            elem.focus();

            return false;

        }else{

            window.location = "http://www.gigibride.co.uk/gallery/category/image-galleries/"+reno.value;

            return true;

        }

    }

function entertoget(e){

var code;

if (!e) var e = window.event;

if (e.keyCode) code = e.keyCode;

else if (e.which) code = e.which;

var character = String.fromCharCode(code);

if(code==13){

var refn=document.getElementById('ref');

var address = refn.value;

alert(address);

}

}

</script>

</head>

<body>

<form>

Reference: <input type='text' id='ref' onkeypress="javascript:entertoget(event);" value='gigigallery' />

<input type='button' onclick="javascript:getrefno(document.getElementById('ref'), 'Please Enter Your Ref No.');" value='Get My Photos' />

</form>

</body>

</html>

HOWTO: vuze (azureus) playing flash plugin

In howto on December 7, 2008 at 5:41 pm
Vuze apparently uses XulRunner as the browser, So copy or link this file:

/usr/lib/mozilla/plugins/libflashplayer.so

to

/usr/lib/xulrunner-1.9/plugins

HOWTO: vuze (azureus) playing flash plugin

In howto on December 7, 2008 at 5:41 pm
Vuze apparently uses XulRunner as the browser, So copy or link this file:

/usr/lib/mozilla/plugins/libflashplayer.so

to

/usr/lib/xulrunner-1.9/plugins

HOWTO: packagekit to check update per login

In fedora, howto on December 4, 2008 at 9:27 pm

PackageKit only checks once per the update interval, by default once every day.
It does not check on every desktop login.

You can change this behaviour by changing
/apps/gnome-packagekit/force_

get_updates_login to TRUE in gconf-editor. The
description of this key is: “Get the update list when the session starts, even
if not scheduled to. This ensures the user has up to date and valid data in the
tray at startup.”

lyx: change Bibliography to Reference

In howto, latex on December 1, 2008 at 5:17 pm

\renewcommand{\bibname}{References}

lyx: insert unnumbered chapter/section to Table of Contents

In howto, latex on December 1, 2008 at 5:06 pm
Just like metioned here:
http://wiki.lyx.org/FAQ/Unsorted1#toc11

To insert unnumbered chapter:
\addcontentsline{toc}{chapter}{THECHAPTERNAME}

To insert unnumbered section:
\addcontentsline{toc}{section}{THESECTIONNAME}

HOWTO: stop imsetting-daemon im-info-daemon

In howto, linux on November 29, 2008 at 3:34 pm
I really don't know how many people will switch between more than 2 input methods, while imsettings, as a project, just provide such a function.This is useless to me, and costing almost 7m memory when booting up fedora.

This is the solution to stop it, and still keeping scim in your system.

Put 'DISABLE_IMSETTINGS=true' in the first line of '/etc/X11/xinit/xinitrc.d/50-xinput.sh'.

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

IMSettings==============IMSettings is a framework that delivers Input Methodsettings and applies the changes immediately. so it willtakes an effect without restarting applications and thedesktop.

Background==============Input Method is used to input some dozens of characters thatcan't be represented with ASCII characters, with someframework such as XIM and SCIM via GTK+/Qtimmodule. particularly which to handle languages that is abit complex to do the same thing with the keyboard layoutsuch as XKB.  In the past, those frameworks has been appliedthrough the environment variables, such as XMODIFIERS andGTK_IM_MODULE. and can't be influenced immediately and can'tbe without restarting the desktop because of its nature -it's being inherited from the parent process unless it'sbeing brought up with the obvious thing from the terminalsay.  Also, there are no such framework to bring up thenecessary process at the run time - of course anyone couldruns it manually though, it's totally out of focus on thisproject.

Features============* Provide the information of Input Method through IMSettings* Provide the DBus service to start/stop process of Input Method* Provide the way to apply Input Method to applications immediately

Scope=========IMSettings may helps when:

* you may want to disable Input Method entirely to use features on any applications, which actually can't use with Input Method because of the key conflicting.* you may try another Input Method without closing current desktop session.* someone may wants to borrow your desktop temporarily, which uses different Input Method.* the appropriate Input Methods needs to be installed by default regardless of you use, such as Live image.

Supported Toolkits======================* GTK+ (with GConf backend)* Xfce (with GConf backend and a plugin for xfce-mcs-manager)* X (with IMSettings XIM server; require libgxim)

Information files for Input Method======================================To make Input Methods available from IMSettings, every InputMethods that hopes so has to have the information file tolet IMSettings know. those files is usually put under adirectory where you can change the default value with--with-xinputdir. the filename has to contain .conf orsomething that you can also change the default value with--with-xinput-suffix to avoid listing every Input Methodsthat might not work for some languages. Input Methodsdoesn't support multiple languages such as XIM doesn't haveto have .conf suffix or so. xim.conf can deals with suchconfiguration files properly for appropriate languagesaccording to current locale.

Available parameters=======================

The following parameters can be described as the shellenvironment variables like FOO=BAR in the information file.

* AUXILIARY_PROGRAM=

 An optional program that may want to bring up for Input Method, such as the panel and the toolbar and so on.

* AUXILIARY_ARGS=

 A list of command line options for AUXILIARY_PROGRAM.

* GTK_IM_MODULE=

 GTK+ immodule name that want to use.

* ICON=

 An icon file to use in GUI.

* IMSETTINGS_IGNORE_ME=

 A parameter to hide Input Method from the inventory. you however can still take an action against such Input Method via IMSettings.

* LONG_DESC=

 An optional long description to explain what this Input Method is.

* PREFERENCE_PROGRAM=

 An optional program that set up Input Method. IMSettings itself do nothing on this parameter. but other tools, such as im-chooser will take an action for that.

* PREFERENCE_ARGS=

 A list of command line options for PREFERENCE_PROGRAM.

* QT_IM_MODULE=

 Qt immodule name that want to use.

* SHORT_DESC=

 An optional short description to explain what this Input Method is. this variable is also sued for the key to do something on IMSettings. e.g. to start/stop Input Method and get the information and so on. so this parameter has to be unique.

* XIM=

 This variable is used for XIM. actually it looks like XMODIFIERS=@im=$XIM.

* XIM_PROGRAM=

 A XIM server be brought up to communicate through XIM protocol.

* XIM_ARGS=

 A list of command line options for XIM_PROGRAM.

Other variables used in xinput.sh====================================

* DISABLE_IMSETTINGS=

 If you want to disable imsettings feature entirely, set true. you'll miss the feature able to change IM on demand but just need to reboot or restart the desktop after changing something.

* IMSETTINGS_DISABLE_DESKTOP_CHECK=

 If your desktop has XSETTINGS manager support and you're sure it also supports imsettings, please file a bug to imsettings. and set true temporarily to ignore checking the desktop.

Processes============

* im-settings-daemon

 A DBus service that provide a facility to start/stop IM processes.

* im-info-daemon

 A DBus service that provide Input Method information.

* gconf-im-settings-daemon

 A DBus service that provide a bridge to communicate GTK+ through GConf.

* imsettings-xim

 A XIM bridge between client applications and real XIM server.

* imsettings-applet

 An applet that provides a facility of changing IM temporarily. this also supports XIM bridge. if imsettings-xim is running, this applet will sends a signal to be terminated.

HOWTO: jython(java) calling c program in console

In howto, java, python on November 27, 2008 at 4:36 pm

import java.lang

proc=java.lang.Runtime.getRuntime().exec(“c:\\app.exe”) // this app.exe is compiled from c
br=java.io.BufferedReader(java.io.InputStreamReader(proc.getInputStream()))
print br.readLine()
java.lang.System.out.println(“last line”)

=========================
Why not using os.popen() from python, is because there is a bug about calling popen. :)

HOWTO: codecs from myplayer_win32

In howto, linux on November 27, 2008 at 3:13 am
if the downloaded codecs file, all-20071007.tar.bz2, is extracted in /usr/lib/codecs

Then, to make these codecs visible to mplayer, do:

su

ln -sf /usr/local/lib/codecs /usr/lib/codecs && ln -sf
/usr/local/lib/codecs /usr/local/lib/win32 && ln -sf
/usr/local/lib/codecs /usr/lib/win32

HOWTO: codecs from myplayer_win32

In howto, linux on November 27, 2008 at 3:13 am
if the downloaded codecs file, all-20071007.tar.bz2, is extracted in /usr/lib/codecs

Then, to make these codecs visible to mplayer, do:

su

ln -sf /usr/local/lib/codecs /usr/lib/codecs && ln -sf
/usr/local/lib/codecs /usr/local/lib/win32 && ln -sf
/usr/local/lib/codecs /usr/lib/win32

HOWTO: Calling c (or other programs) from python

In C/C++, howto, python on November 26, 2008 at 3:29 pm

Calling c (or other programs) from python

1. swig (to generate a python extention from c)
2. dl, python object (to call c shared library)
3. os.popen() (to call other exetuable programs)

In this example, I will use the 3rd method.

1) c program.
This is an example from netbeans, it can print all the arguments, argv[0] is the program name.
# args.c ###################################
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char**argv) {
int i;
// Prints arguments
printf("Arguments:\n");
for (i = 0; i < argc; i++) {
printf("%i: %s\n", i, argv[i]);
}

return 0;
}
#############################
compile it:
####
gcc args.c -o a.out
####

2) python script

# in python script ################
import os
printed = os.popen(‘./a.o hello world’)
>>> printed.readline()
‘Arguments:\n’
>>> printed.readline()
‘0: ./a.o\n’
>>> printed.readline()
‘1: hello\n’
>>> printed.readline()
‘2: world\n’
>>> printed.readline()

##################################
Here printed is an python array object, all the methods for array are available.

mysql, simple commands 2008

In howto, mysql on November 18, 2008 at 5:50 pm
Selecting a database:

mysql> USE database;

Listing databases:

mysql> SHOW DATABASES;

Listing tables in a db:

mysql> SHOW TABLES;

Describing the format of a table:

mysql> DESCRIBE table;

Creating a database:

mysql> CREATE DATABASE db_name;

Creating a table:

mysql> CREATE TABLE table_name (field1_name TYPE(SIZE), field2_name TYPE(SIZE));Ex: mysql> CREATE TABLE pet (name VARCHAR(20), sex CHAR(1), birth DATE);

Load tab-delimited data into a table:

mysql> LOAD DATA LOCAL INFILE "infile.txt" INTO TABLE table_name;(Use \n for NULL)

Inserting one row at a time:

mysql> INSERT INTO table_name VALUES ('MyName', 'MyOwner', '2002-08-31');(Use NULL for NULL)

Retrieving information (general):

mysql> SELECT from_columns FROM table WHERE conditions;All values: SELECT * FROM table;Some values: SELECT * FROM table WHERE rec_name = "value";Multiple critera: SELECT * FROM TABLE WHERE rec1 = "value1" AND rec2 = "value2";

Reloading a new data set into existing table:

mysql> SET AUTOCOMMIT=1; # used for quick recreation of tablemysql> DELETE FROM pet;mysql> LOAD DATA LOCAL INFILE "infile.txt" INTO TABLE table;

Fixing all records with a certain value:

mysql> UPDATE table SET column_name = "new_value" WHERE record_name = "value";

Selecting specific columns:

mysql> SELECT column_name FROM table;

Retrieving unique output records:

mysql> SELECT DISTINCT column_name FROM table;

Sorting:

mysql> SELECT col1, col2 FROM table ORDER BY col2;Backwards: SELECT col1, col2 FROM table ORDER BY col2 DESC;

Date calculations:

mysql> SELECT CURRENT_DATE, (YEAR(CURRENT_DATE)-YEAR(date_col)) AS time_diff [FROM table];MONTH(some_date) extracts the month value and DAYOFMONTH() extracts day.

Pattern Matching:

mysql> SELECT * FROM table WHERE rec LIKE "blah%";(% is wildcard - arbitrary # of chars)Find 5-char values: SELECT * FROM table WHERE rec like "_____";(_ is any single character)

Extended Regular Expression Matching:

mysql> SELECT * FROM table WHERE rec RLIKE "^b$";(. for char, [...] for char class, * for 0 or more instances^ for beginning, {n} for repeat n times, and $ for end)(RLIKE or REGEXP)To force case-sensitivity, use "REGEXP BINARY"

Counting Rows:

mysql> SELECT COUNT(*) FROM table;

Grouping with Counting:

mysql> SELECT owner, COUNT(*) FROM table GROUP BY owner;(GROUP BY groups together all records for each 'owner')

Selecting from multiple tables:

(Example)mysql> SELECT pet.name, comment FROM pet, event WHERE pet.name = event.name;(You can join a table to itself to compare by using 'AS')

Currently selected database:

mysql> SELECT DATABASE();

Maximum value:

mysql> SELECT MAX(col_name) AS label FROM table;

Auto-incrementing rows:

mysql> CREATE TABLE table (number INT NOT NULL AUTO_INCREMENT, name CHAR(10) NOT NULL);mysql> INSERT INTO table (name) VALUES ("tom"),("dick"),("harry");

Adding a column to an already-created table:

mysql> ALTER TABLE tbl ADD COLUMN [column_create syntax] AFTER col_name;

Removing a column:

mysql> ALTER TABLE tbl DROP COLUMN col;(Full ALTER TABLE syntax available at mysql.com.)

Batch mode (feeding in a script):

# mysql -u user -p  source batch_file;

Backing up a database with mysqldump:

# mysqldump --opt -u username -p database > database_backup.sql(Use 'mysqldump --opt --all-databases > all_backup.sql' to backup everything.)(More info at MySQL's docs.)

Join tables:# SELECT * FROM cars JOIN colors ON colors.car_ID=cars.id# SELECT * FROM cars AS cr JOIN colors AS cl ON cl.car_ID=cr.idAfter the ON, we state on wich columns the tables should join. Every color has a reference to a car by the "car_ID" column. Every car has anID, and these two columns are the link between the two tables.

HOWTO: [Lyx] replace the name of bibliography with reference

In howto on November 15, 2008 at 3:40 pm

in lyx, to replace the name of bibliography with reference, using report as document class

\renewcommand{\bibname}{References}
marked as TeX

==================================
\newcommand \renewcommand

\newcommand{cmd}[args][opt]{def}
\renewcommand{cmd}[args][opt]{def}
\providecommand{cmd}[args][opt]{def} — LaTeX2e

These commands define (or redefine) a command.

* cmd The name of the new or redefined command. A \ followed by a string of lower and/or uppercase letters or a \ followed by a single nonletter. For \newcommand the name must not be already defined and must not begin with \end; for \renewcommand it must already be defined. The \providecommand command is identical to the \newcommand command if a command with this name does not exist; if it does already exist, the \providecommand does nothing and the old definition remains in effect.

* args An integer from 1 to 9 denoting the number of arguments of the command being defined. The default is for the command to have no arguments.

* opt (LaTeX2e only) If present, then the first of the number of arguments specified by args is optional with a default value of opt; if absent, then all of the arguments are required.

* def The text to be substituted for every occurrence of cmd; a parameter of the form #n in cmd is replaced by the text of the nth argument when this substitution takes place.

Examples
\newcommand{\water}{H$_2$O}

This would allow one to write, e.g.,

The formula for water is \water.

or

\water\ is the formula for water.

Note, in the second case, the trailing \ followed by a blank is required to ensure a blank space after the H2O; LaTeX ignores the blank following a command, so the space has to be specifically inserted with the \.

As a second example consider

\newcommand{\hypotenuse}{$a^{2}+b^{2}$}

Note that this will produce the desired formula in text (paragraph) mode because of the $…$ in the definition. In math mode, however, the first $ in the definition will cause LaTeX to leave math mode, causing problems.

In LaTeX 2.09 a standard trick for getting around this is to put the math-mode expression in an \mbox, viz.,

\newcommand{\hypotenuse}{\mbox{$a^{2}+b^{2}$}}

In LaTeX2e the \ensuremath command has been provided to alleviate this problem. The argument of the \ensuremath command is always processed in math mode, regardless of the current mode. Using this mechanism the above could be written as

\newcommand{\hypotenuse}{\ensuremath{a^{2}+y^{2}}}

HOWTO: find

In howto, linux on November 6, 2008 at 1:50 pm

From man:
-exec command ;
Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;’ is encountered. The string `{}’ is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\’) or quoted to protect them from expansion by the shell. The command is executed in the starting directory.

find . -type f -exec file ‘{}’ \; # ‘{}’ or {}, and there is a space before ‘\’;

Runs ‘file’ on every file in or below the current directory. Notice
that the braces are enclosed in single quote marks to protect them from
interpretation as shell script punctuation. The semicolon is similarly
protected by the use of a backslash, though single quotes could have
been used in that case also.

—————————————————————–

`{}’ is replaced by the current file name being processed;
\ is used for the iteration of found files.
; is to tell -exec that the job is done.

Example: find . -exec grep ‘title=”Phoca Gallery”‘ {} \; -ls
Normally above example suits our search jobs.

HOWTO: convert amr ringtones or voice recording to mp3/ogg/wav

In howto, linux on October 24, 2008 at 1:33 pm

First you should decode the file to the raw format:
$ amrnb-decoder Sound1.amr Sound2.raw
which should produce something like this:
================================================== =================
TS 26.104
REL-5 V5.4.0 2004-03
REL-6 V6.1.0 2004-03
3GPP AMR Floating-point Speech Decoder
================================================== =================

Secondly, you can convert the resulting .raw file to other preferred format in Audacity.
In Audacity, using ‘File->Import->Raw Data’ to open the raw file by selecting 8000 as the sample rate.

HOWTO: 使用Mutagen来修改Mp3文件的标签信息

In howto on October 23, 2008 at 9:11 am

具体方法如下(只针对GBK/GB18030编码的情况):

安装Mutagen(ubuntu下终端运行 sudo apt-get install python-mutagen)后,在终端执行:

mid3iconv -e gbk *.mp3

如果想转换当前目录下的所有 mp3 (包括子目录):

find . -iname “*.mp3″ -execdir mid3iconv -e gbk {} ;

这里只介绍最常见的情况,更多信息可以查看Nicky的文章,他分析得很详细。

HOWTO: NFS server

In howto, linux on October 22, 2008 at 2:48 pm

Install NFS Server Support
at the terminal type
sudo apt-get install nfs-kernel-server nfs-common portmap
(Optional: sudo dpkg-reconfigure portmap)
sudo /etc/init.d/portmap restart

Editing /etc/exports
the /etc/exports file is used for creating a share on the NFS server

invoke your favorite text editor or
sudo vi /etc/exports

Here are some quick examples of what you could add to your /etc/exports

For Full Read Write Permissions allowing any computer from 192.168.1.1 through 192.168.1.255

  • /files 192.168.1.1/24(rw,no_root_squash,async)
    Here /24 is netmask, meaning the netmask is 24 bits. Therefore, above line can be equivalent to:
  • /files 192.168.1.1/255.255.255.0 (rw,no_root_squash,async)
    details can be found in the reference

Or for Read Only from a single machine

  • /files 192.168.1.2 (ro,async)

save this file and then in a terminal type
sudo /etc/init.d/nfs-kernel-server restart

Also aftter making changes to /etc/exports in a terminal you must type
sudo exportfs -a

Install NFS client support
sudo apt-get install portmap nfs-common

Mounting manually
Example to mount server.mydomain.com:/files to /files. In this example server.mydomain.com is the name of the server containing the nfs share, and files is the name of the share on the nfs server

The mount point /files must first exist on the client machine.
cd /
sudo mkdir files

to mount the share from a terminal type

sudo mount server.mydomain.com:/files /files

Note you may need to restart above services:
sudo /etc/init.d/portmap restart
sudo /etc/init.d/nfs-common restart

Mounting at boot using /etc/fstab
Invoke the text editor using your favorite editor, or
gksudo gedit /etc/fstab

In this example my /etc/fstab was like this:

  • server.mydomain.com:/files /files nfs rsize=8192,wsize=8192,timeo=14,intr

You could copy and paste my line, and change “servername.mydomain.com:/files”, and “/files” to match your server name:share name, and the name of the mount point you created.
It is a good idea to test this before a reboot in case a mistake was made.
type
mount /files
in a terminal, and the mount point /files will be mounted from the server.

Reference:
==========
http://www.cyberciti.biz/tips/ubuntu…nfs-share.html (for client configuration)
http://www.redhat.com/docs/manuals/l…nfs-mount.html (for mounting using fstab)
http://czarism.com/easy-peasy-ubuntu…s-file-sharing (for server configuration)
http://www.freebsd.org/doc/en_US.ISO…twork-nfs.html (contains more info about NFS)
http://www.freebsd.org/cgi/man.cgi?query=exports&sektion=5 (man for exports)
http://www.computerhope.com/jargon/n/netmask.htm (netmask /24 things)

HOWTO: 昂达989+ 白屏

In howto on October 20, 2008 at 4:00 pm
经过一系列的刷机,烧录和几个论坛的折腾,终于找到一条融会贯通,于其他人不太一样的解决办法。

经验说明,一旦白屏,烧录很难解决。
综合其他人的经验加本人989+白屏解决办法,总结如下:

白屏的原因并非软件,而是‘接触不良’的问题。
1.在一个高级一点的单片机论坛里看到,是因为‘虚焊’,
2.在一昂达论坛看到说有人在一个黑色芯片下垫纸解决。
3.本人则是发现用力按下方向键,反而有开机成功的机会。

综上,应该是接触不良的问题。

当把最新的固件保存到根目录下,然后用力按下屏幕中央,再按住‘向下’方向键,再开机,于是发现,可以升级固件了。于是最新固件(此时是1.25)升级成功,白屏基本没有再出现。

HOWTO: 昂达989+ 白屏

In howto on October 20, 2008 at 4:00 pm
经过一系列的刷机,烧录和几个论坛的折腾,终于找到一条融会贯通,于其他人不太一样的解决办法。

经验说明,一旦白屏,烧录很难解决。
综合其他人的经验加本人989+白屏解决办法,总结如下:

白屏的原因并非软件,而是‘接触不良’的问题。
1.在一个高级一点的单片机论坛里看到,是因为‘虚焊’,
2.在一昂达论坛看到说有人在一个黑色芯片下垫纸解决。
3.本人则是发现用力按下方向键,反而有开机成功的机会。

综上,应该是接触不良的问题。

当把最新的固件保存到根目录下,然后用力按下屏幕中央,再按住‘向下’方向键,再开机,于是发现,可以升级固件了。于是最新固件(此时是1.25)升级成功,白屏基本没有再出现。

HOWTO: Remove Input Method(SCIM) from Right Click Menu

In howto, linux on October 20, 2008 at 2:09 pm
Type “ALT+F2″ and start the “gconf-editor”. Then:

desktop –> gnome –> interface

and disable

show_input_method_menu
show_unicode_menu

HOWTO: TAB TO AUTOCOMPLETE COMMAND OPTIONS

In fedora, howto, linux on October 19, 2008 at 12:53 am

yum install bash-completion

Now you will get the ability to use TAB to autocomplete your command and COMMAND OPTIONS.

HOWTO: equivalent yum option to apt-get autoremove

In fedora, howto, linux on October 16, 2008 at 10:38 pm

To remove packages that has been installed as dependencies for the package you are removing if they are only needed for that particular package.

a yum plugin must be installed. Otherwise, yum doesn’t provide the capability.

yum install yum-remove-with-leaves

Now yum will automatically have the same function as apt-get autoremove.

================
more:
yum-changelog is a Yum plugin for viewing package changelogs before/after updating.

Install yum-changelog via:
# yum install yum-changelog

How to use yum-changelog:
# yum update ktechlab –changelog
Loading “changelog” plugin
Loading “installonlyn” plugin
Setting up Update Process
Setting up repositories
[..]
Resolving Dependencies
–> Populating transaction set with selected packages. Please wait.
—> Package ktechlab.i386 0:0.3-6.fc6 set to be updated
–> Running transaction check

Changes in packages about to be updated:

ktechlab – 0.3-6.fc6.i386
* Wed Nov 22 23:00:00 2006 Chitlesh Goorah – 0.3-6
- Rebuilt due to new gpsim-devel release

By default, this plugin will show the changelogs before the updates. However if you want to make it echo those changelogs after the updates, replace when=pre by when=post in the file /etc/yum/pluginconf.d/changelog.conf

HOWTO: yum equivalent function with apt-get

In fedora, howto, linux on October 16, 2008 at 2:39 am

1. Find and review “lost” packages

You can find orphaned packages (ie packages not in the repositories anymore) with the tool package-cleanup from the yum-utils package: yum install yum-utils; package-cleanup --orphans.
Old packages with a failing “%postun” script will remain partly
installed. Remove them with rpm -e package-name-and-version. It’s often
helpful to run this command after the update, too.

But here what ‘package-cleanup –orphans’ found out is the ‘obsolete’ ones in ubuntu words. Namely installed not from repositories.

2. Find yum install or update history

/var/log/yum.log

3. Find orphan packages
sudo package-cleanup –orphans

Note: Here ‘package-cleanup’ must run with sudo or su, otherwise lots of packages will be considered as orphans because of normal users don’t know the relationship between packages and repositories.

HOWTO: wine fonts

In howto, linux on October 13, 2008 at 10:53 am

Wine中对话框默认的字体是Tahoma,在我们的LINUX上,Tahoma字体是无法正常显示中文的。比如Wine configuration中的”确定”"取消”等就变成了”<<”">>”的字样。

解决方法很简单:

在wine的regedit中,找到:

\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\FontSubstitutes

方法1. 直接地将这个键设为空,问题就解决了。

方法2. 将MS Shell Dlg设置为一种自己字库中已有的中文字体即可,如果已经将windows中宋体取来使用了,字库中SimSun对应宋体(这是Windows的,LINUX下默认是没有的),在这里设置为 SimSun即可。

HOWTO: find WINE menu stored in Gnome

In howto, linux on October 13, 2008 at 10:21 am
Everything about the wine menu is stored here in a text mode, while not separately for each item.

  • .config/menus

Especially the file, ‘applications.menu’, a xml file, which describes the Gnome menu structure.
Every menu-edit operation on wine menu will reflected in this file.

  • .config/menus/applications-merged

The ‘wine-program-*’ files, xml files, are the short-cuts appears in the ‘application-wine-Programs’. The rest, not appear here, will listed in the other menu.

  • ~/.local/share/applications/wine/Programs


Where the ‘application-other’ menu retrieve short-cuts directly from
.

HOWTO: codecs for fedora

In howto, linux on October 12, 2008 at 2:49 am
http://www.mplayerhq.hu/MPlayer/releases/codecs/

download “all-20071007.tar.bz2″ to your desktop, then right click and
extract it now rename the folder to codecs, then open a terminal and
type

cd ~/Desktop

su

mv codecs /opt/
ln -sf /opt/codecs /usr/lib/win32
ln -sf /opt/codecs /usr/lib/codecs
ln -sf /opt/codecs /usr/local/lib/win32
ln -sf /opt/codecs /usr/local/lib/codecs

For Totem (gstreamer)
gstreamer-ffmpeg and ffmpeg is essential.
other plugins for gstreamer will be helpful.

HOWTO: Gnome下节省系统资源的输入中文方式

In howto, linux on October 10, 2008 at 12:59 am
最简单的方式输入中文就是在System-Administration-Language Support里选中’enable support to enter complex characters’.但是这样会使得scim的进程一直在后台占用一定的内存,不太‘干净’。

1。每次都是在gnome的popup menu里选择input methods-scim又太过麻烦

2。在~/.profile最后加上(出自man scim)
GTK_IM_MODULE=”scim”
export GTK_IM_MODULE
这样开机会自动启动scim但是可以方便的通过右键点击图标去关闭;如果想在输入中文,只要随便打开gnome的程序,scim会自动跟着打开,关闭gnome程序,scim也会跟着自动关闭。如此可以在不需要输入中文的时候,节省些系统资源。

此种方式的输入法是全局的(global),在所有运行的程序中都可以直接输入中文。

3。在~/.bashrc最后加上(出自man scim)
GTK_IM_MODULE=”scim”
export GTK_IM_MODULE
每次要输入中文,要通过terminal去启动相应gnome程序,否则通过点击快捷图标,不会启动scim。

但是如果要在fedora下,须在这两条命令前执行以下命令,否则输入法会随着login自动启动(ubuntu的.bashrc已经自带此命令)
# If not running interactively, don’t do anything
[ -z "$PS1" ] && return

此种方式的输入法只是针对相应的运行的程序(session),只有在这一个程序内可以直接输入中文。(recommended)

HOWTO: podcast a audio in blog

In howto on October 6, 2008 at 1:44 pm
here we explore some new Flash MP3 players from Google and Yahoo!
that are again light-weight, easy to implement and extremely efficient.

1. Google Reader MP3 Player

Google Reader has an inbuilt MP3 player that is pretty much the same
as Gmail player but it also works on non-Google websites. This player
has volume controls, no Google branding and it auto-detects the
duration of the music file so your readers know how long the song will
last. Here’s a live example followed by the HTML embed code:

To use this MP3 player on your website or blog, copy-paste the
following code and replace the MP3_FILE_URL with the link to your MP3
file.

<embed type=”application/x-shockwave-flash” src=”http://www.google.com/reader/ui/3247397568-audio-player.swf?audioUrl=MP3_FILE_URL
width=”400″ height=”27″ allowscriptaccess=”never” quality=”best”
bgcolor=”#ffffff” wmode=”window” flashvars=”playerMode=embedded” />

2. Yahoo! MP3 Player

If you think normal is boring, check this out. Yahoo! offer a code generator (Easy Listener) to help you create a Flash based MP3 player that matches your website color theme and layout. See example:

Though this Easy Listener MP3 player requires you to pass the
address of the web page that contains the MP3 file(s), you can directly
pass the MP3 link and it will work just fine. Supports auto play and
you can decide where the meta data associated with the MP3 file should
be displayed.

<embed src=”http://webjay.org/flash/dark_player” width=”400″ height=”40″ wmode=”transparent” flashVars=”playlist_url=MP3_FILE_URL&skin_color_1=-145,-89,-4,5&skin_color_2=-141,20,0,0″ type=”application/x-shockwave-flash” />

3. Yahoo! Media Player

If you maintain an MP3 blog or run a podcast and regularly link to
MP3 files, it makes little sense to embed a separate Flash player with
every MP3 file. I would therefore recommend using the Yahoo! Media Player that auto-detects links to MP3 files in your web pages and creates an embedded player for each link.

All you have to do is insert the following link in your blog
template and all MP3 hyperlinks will be converted into inline MP3
players. This also has the shuffle feature and visitors can easily skip
to any song in the playlist. Excellent stuff.

<script type=”text/javascript” src=”http://mediaplayer.yahoo.com/js”></script>

4. Odeo MP3 Player

Odeo offers a pretty impressive MP3 player (see example)
that works perfect in web pages as well as RSS readers but a small
issue is that Odeo Player requires you to type the exact duration of
the song in the embed code. You can skip this step but then the
progress bar won’t reflect the true status when you play the
song. And there are no volume controls.

To use Odeo MP3 player in your website, add the following code replacing MP3_FILE_URL and DURATION with relevant values.

<embed src= “http://www.odeo.com/flash/audio_player_standard_gray.swf” quality=”high” width=”300″ height=”52″ allowScriptAccess=”always” wmode=”transparent”  type=”application/x-shockwave-flash” flashvars= “valid_sample_rate=true&external_url=[MP3 file address]” pluginspage=”http://www.macromedia.com/go/getflashplayer”> </embed>

Summary: With so many choices, how do you pick the right MP3 player for your website ?

HOWTO: use the "label:" query word to search in Gmail

In howto on October 4, 2008 at 3:13 pm
how to use the “label:” query word to search for Multi-Labeled messages
as well as Un-Labeled messages. Thanks to “rishid” on the GmailForums
for submitting this tip…

Say you want to find messages that have multiple Labels. For example,
you want to display all messages with label1, label2 and label3 that
you had previously defined and assigned. Into the basic search field at
the top of any Gmail page, you would enter label:label1 label:label2
label:label3

Note that this is searching for all messages that have label1 AND
label2 AND label3. If you want to include messages that have ANY of
those labels, you can use the “OR” command like this: label:label1 OR
label:label2 OR label:label3 (Note: “OR” must be in uppercase.)

You can optionally add a “-” to the query words to exclude search
criteria. For example, entering -label:label1 label:label2 label:label3
would return all messages that have label 2 AND label 3, but do not
have a label1 Label.

Taking this concept a step further, you can use this method to search
for all “Un-Labeled” messages. Unfortunatly, Gmail does not provide a
choice in the search dropdown that lets you search for unlabeled
messages. If you manage a large number of messages, it can be very
cumbersome to determine which messages are unlabeled. My personal
preference is to ensure that all messages have a Label making it easier
to manage and organize them.

So, if you want to list all unlabeled messages, just create a long
search string containing every label that you have defined. Be sure to
include the “-” character in front of every label. This ensures that
messages with these labels will be EXCLUDED (remember, you are looking
for all messages WITHOUT Labels.) You can also optionally include the
hidden “inbox” Label to exclude anything in your Inbox.

For example, if you have defined the Labels “Family”, “Friends”,
“Ebay”, and “Support”, you would enter the following string into the
search field (note that the labels are not case sensitive) to find all
Unlabeled messaegs:

-label:inbox -label:family -label:friends -label:ebay -label:support

If you have a large number of labels, obviously, this becomes harder
and harder to manage, so I recommend reating a “note” email to yourself
containing the search string for easy future reference.

HOWTO: use the "label:" query word to search in Gmail

In howto on October 4, 2008 at 3:13 pm
how to use the “label:” query word to search for Multi-Labeled messages
as well as Un-Labeled messages. Thanks to “rishid” on the GmailForums
for submitting this tip…

Say you want to find messages that have multiple Labels. For example,
you want to display all messages with label1, label2 and label3 that
you had previously defined and assigned. Into the basic search field at
the top of any Gmail page, you would enter label:label1 label:label2
label:label3

Note that this is searching for all messages that have label1 AND
label2 AND label3. If you want to include messages that have ANY of
those labels, you can use the “OR” command like this: label:label1 OR
label:label2 OR label:label3 (Note: “OR” must be in uppercase.)

You can optionally add a “-” to the query words to exclude search
criteria. For example, entering -label:label1 label:label2 label:label3
would return all messages that have label 2 AND label 3, but do not
have a label1 Label.

Taking this concept a step further, you can use this method to search
for all “Un-Labeled” messages. Unfortunatly, Gmail does not provide a
choice in the search dropdown that lets you search for unlabeled
messages. If you manage a large number of messages, it can be very
cumbersome to determine which messages are unlabeled. My personal
preference is to ensure that all messages have a Label making it easier
to manage and organize them.

So, if you want to list all unlabeled messages, just create a long
search string containing every label that you have defined. Be sure to
include the “-” character in front of every label. This ensures that
messages with these labels will be EXCLUDED (remember, you are looking
for all messages WITHOUT Labels.) You can also optionally include the
hidden “inbox” Label to exclude anything in your Inbox.

For example, if you have defined the Labels “Family”, “Friends”,
“Ebay”, and “Support”, you would enter the following string into the
search field (note that the labels are not case sensitive) to find all
Unlabeled messaegs:

-label:inbox -label:family -label:friends -label:ebay -label:support

If you have a large number of labels, obviously, this becomes harder
and harder to manage, so I recommend reating a “note” email to yourself
containing the search string for easy future reference.

HOWTO: Find which Debian or ubuntu Linux Version you are running

In howto, linux on October 2, 2008 at 2:26 pm

Find or identify which version of Debian Linux you are running

This can be checked in

/etc/debian_version file

Find or identify which version of ubuntu Linux you are running

You can find in different ways in ubuntu

Solution 1

cat /etc/issue

The file /etc/issue holds the version of Ubuntu installed on your system

Solution 2

lsb_release -a

or

cat /etc/lsb-release

Where lsb for Linux Standard Base

HOWTO: fstab backup

In howto, linux on September 21, 2008 at 9:11 pm
# /etc/fstab: static file system information.
#
#              
proc            /proc           proc    defaults        0       0
# /dev/sda5
UUID=ac407051-9b61-4cdf-8ee5-931ee60ca142 /               ext3    relatime,errors=remount-ro 0       1
# /dev/sda2
UUID=a1c7cec0-e0ce-428d-b358-9a28121c78ab /boot           ext3    relatime        0       2
# /dev/sda8
UUID=c2fdb6c9-c9c3-4f2c-8415-f0a447dcadd3 /home           ext3    relatime        0       2
# /dev/sda7
UUID=c6222043-d2dc-4c2c-9d28-7048164a3fbe /usr/local      ext3    relatime        0       2
# /dev/sda6
UUID=b377178f-e7b5-4c44-8f20-39befffb85a5 none            swap    sw              0       0
/dev/scd0       /media/cdrom0   udf,iso9660 user,noauto,exec,utf8 0       0

# my ntfs partitions
/dev/sda4    /home/Personal    ntfs-3g    default    0    0
/dev/sda1    /home/Win_C    ntfs-3g    default    0    0

HOWTO: fstab backup

In howto, linux on September 21, 2008 at 9:11 pm
# /etc/fstab: static file system information.
#
#              
proc            /proc           proc    defaults        0       0
# /dev/sda5
UUID=ac407051-9b61-4cdf-8ee5-931ee60ca142 /               ext3    relatime,errors=remount-ro 0       1
# /dev/sda2
UUID=a1c7cec0-e0ce-428d-b358-9a28121c78ab /boot           ext3    relatime        0       2
# /dev/sda8
UUID=c2fdb6c9-c9c3-4f2c-8415-f0a447dcadd3 /home           ext3    relatime        0       2
# /dev/sda7
UUID=c6222043-d2dc-4c2c-9d28-7048164a3fbe /usr/local      ext3    relatime        0       2
# /dev/sda6
UUID=b377178f-e7b5-4c44-8f20-39befffb85a5 none            swap    sw              0       0
/dev/scd0       /media/cdrom0   udf,iso9660 user,noauto,exec,utf8 0       0

# my ntfs partitions
/dev/sda4    /home/Personal    ntfs-3g    default    0    0
/dev/sda1    /home/Win_C    ntfs-3g    default    0    0

HOWTO: find out ‘orphaned’ packages

In howto, linux on September 18, 2008 at 6:11 pm
1. Enable the Extra Repos (http://ubuntuguide.org/#extrarepositories)

2. Install deborphan

$ sudo apt-get install deborphan

3. Open Synaptic and click the ‘Custom’ button in the lower-left corner.

You should already see sections such as ‘Broken’ and ‘Marked Changes’.

4. From Synaptic’s main menu choose Settings > Filters

It should look similar to this:

http://img.photobucket.com/albums/v469/camplear/forums/synaptic70b.png

5. Click on the ‘New’ button.

In the Dialogue box type in ‘Orphaned’ in place of ‘New Filter 1′

This will name the filter (choose any name you prefer).

6. Click the ‘Deselect All’ box then tick the ‘Orphaned’ box.

It should look similar to this:

http://img.photobucket.com/albums/v469/camplear/forums/synaptic71b.png

7. Click ‘Okay’

8. Highlight the ‘Orphaned’ option and view the selected packages.

Choose any/all of them and ‘Mark For Removal’ with right-click.

It should look similar to this:

http://img.photobucket.com/albums/v469/camplear/forums/synaptic72b.png

HOWTO: find out ‘orphaned’ packages

In howto, linux on September 18, 2008 at 6:11 pm
1. Enable the Extra Repos (http://ubuntuguide.org/#extrarepositories)

2. Install deborphan

$ sudo apt-get install deborphan

3. Open Synaptic and click the ‘Custom’ button in the lower-left corner.

You should already see sections such as ‘Broken’ and ‘Marked Changes’.

4. From Synaptic’s main menu choose Settings > Filters

It should look similar to this:

http://img.photobucket.com/albums/v469/camplear/forums/synaptic70b.png

5. Click on the ‘New’ button.

In the Dialogue box type in ‘Orphaned’ in place of ‘New Filter 1′

This will name the filter (choose any name you prefer).

6. Click the ‘Deselect All’ box then tick the ‘Orphaned’ box.

It should look similar to this:

http://img.photobucket.com/albums/v469/camplear/forums/synaptic71b.png

7. Click ‘Okay’

8. Highlight the ‘Orphaned’ option and view the selected packages.

Choose any/all of them and ‘Mark For Removal’ with right-click.

It should look similar to this:

http://img.photobucket.com/albums/v469/camplear/forums/synaptic72b.png

howto: format SD cards

In howto, linux on September 8, 2008 at 9:59 am

To check the mounted usb device:

sudo fdisk -l

Umount it:

sudo umount /media/disk

Format it:

sudo mkfs.vfat /dev/sdc1

Howto: conky

In howto, linux on September 2, 2008 at 11:43 pm
My content of .conkyrc:

=============================
background yes
font Zekton:size=7
xftfont Zekton:size=7
use_xft yes
xftalpha 0.1
update_interval 2.0
total_run_times 0
own_window yes
own_window_type override
own_window_transparent yes
own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager
double_buffer yes
draw_shades no
draw_outline no
draw_borders no
draw_graph_borders no
minimum_size 220 5
maximum_width 220
default_color d7d7d7
default_shade_color black
default_outline_color black
alignment bottom_right
gap_x 10
gap_y 10
no_buffers yes
cpu_avg_samples 2
override_utf8_locale no
uppercase no # set to yes if you want all text to be in uppercase
use_spacer no

TEXT
${font Zekton:style=Bold:pixelsize=42}${alignc}${time %H:%M:%S}${font Zekton:size=7}
SYSTEM ${hr 1 }

Hostname: $alignr$nodename
Kernel: $alignr$kernel
Uptime: $alignr$uptime
Processes: ${alignr}$processes ($running_processes running)
Load: ${alignr}$loadavg
Battery ${battery_time BAT0} ${alignr}(${battery BAT0})
${battery_bar 4 BAT0}

FILESYSTEM ${hr 1}${color}

Root: ${alignr}${fs_free /} / ${fs_size /}
${fs_bar 4 /}
Home: ${alignr}${fs_free /home} / ${fs_size /home}
${fs_bar 4 /}

NETWORK ${hr 1}${color}

Down ${downspeed wlan0} k/s ${alignr}Up ${upspeed wlan0} k/s
${downspeedgraph wlan0 25,107} ${alignr}${upspeedgraph wlan0 25,107}
Total ${totaldown wlan0} ${alignr}Total ${totalup wlan0}

SYSTEM RESOURCE ${hr 1}${color}

Highest CPU $alignr CPU% MEM%
${top name 1}$alignr${top cpu 1}${top mem 1}
${top name 2}$alignr${top cpu 2}${top mem 2}
${top name 3}$alignr${top cpu 3}${top mem 3}

Highest MEM $alignr CPU% MEM%
${top_mem name 1}$alignr${top_mem cpu 1}${top_mem mem 1}
${top_mem name 2}$alignr${top_mem cpu 2}${top_mem mem 2}
${top_mem name 3}$alignr${top_mem cpu 3}${top_mem mem 3}

CPU ${alignc} ${freq}MHz / ${acpitemp}C ${alignr}(${cpu cpu1}%)
${cpubar 4 cpu1}
${cpugraph}
RAM ${alignr}$mem / $memmax ($memperc%)
${membar 4}

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

Howto: conky

In howto, linux on September 2, 2008 at 11:43 pm
My content of .conkyrc:

=============================
background yes
font Zekton:size=7
xftfont Zekton:size=7
use_xft yes
xftalpha 0.1
update_interval 2.0
total_run_times 0
own_window yes
own_window_type override
own_window_transparent yes
own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager
double_buffer yes
draw_shades no
draw_outline no
draw_borders no
draw_graph_borders no
minimum_size 220 5
maximum_width 220
default_color d7d7d7
default_shade_color black
default_outline_color black
alignment bottom_right
gap_x 10
gap_y 10
no_buffers yes
cpu_avg_samples 2
override_utf8_locale no
uppercase no # set to yes if you want all text to be in uppercase
use_spacer no

TEXT
${font Zekton:style=Bold:pixelsize=42}${alignc}${time %H:%M:%S}${font Zekton:size=7}
SYSTEM ${hr 1 }

Hostname: $alignr$nodename
Kernel: $alignr$kernel
Uptime: $alignr$uptime
Processes: ${alignr}$processes ($running_processes running)
Load: ${alignr}$loadavg
Battery ${battery_time BAT0} ${alignr}(${battery BAT0})
${battery_bar 4 BAT0}

FILESYSTEM ${hr 1}${color}

Root: ${alignr}${fs_free /} / ${fs_size /}
${fs_bar 4 /}
Home: ${alignr}${fs_free /home} / ${fs_size /home}
${fs_bar 4 /}

NETWORK ${hr 1}${color}

Down ${downspeed eth1} k/s ${alignr}Up ${upspeed eth1} k/s
${downspeedgraph eth1 25,107} ${alignr}${upspeedgraph eth1 25,107}
Total ${totaldown eth1} ${alignr}Total ${totalup eth1}

SYSTEM RESOURCE ${hr 1}${color}

Highest CPU $alignr CPU% MEM%
${top name 1}$alignr${top cpu 1}${top mem 1}
${top name 2}$alignr${top cpu 2}${top mem 2}
${top name 3}$alignr${top cpu 3}${top mem 3}

Highest MEM $alignr CPU% MEM%
${top_mem name 1}$alignr${top_mem cpu 1} ${top_mem mem_res 1}
${top_mem name 2}$alignr${top_mem cpu 2} ${top_mem mem_res 2}
${top_mem name 3}$alignr${top_mem cpu 3} ${top_mem mem_res 3}

CPU ${alignc} ${freq}MHz / ${acpitemp}C ${alignr}(${cpu cpu1}%)
${cpubar 4 cpu1}
${cpugraph}
RAM ${alignr}$mem / $memmax ($memperc%)
${memgraph}

=============================
or: using ‘mem_res’ instead of ‘mem’, which is percentage
${top_mem name 1} ${top_mem cpu 1}$alignr${top_mem mem_res 1}

a PHP script to transfer files between iphone and linux/mac computer

In howto, php on August 3, 2008 at 8:23 pm
#!/usr/bin/php

<?php
# requirement:
# a)the work directory on PC/laptop is /home/cross/iphone, which you should modify to suit your situation.
# b)install php on iphone.

# To transfer file from PC to iphone:
# php trans.php FILETOTRANSFER
# To transfer file from iphone to pc:
# php trans.php -[anything] FILETOTRANSFER

$port_lsbu = 150;
$port_home = 75;

$athome = shell_exec(“ifconfig”); // check where are you now.

if (substr($argv[1],0,1)==’-') { // get the first argument, if it starts with ‘-’, then transfer from iphone
if(stristr($athome, ‘192.168.1.57′) == FALSE) { // ip address of iphone at home is this, this command can find out where i am.
echo ‘from iphone to lsbu pc’;
$output = shell_exec(“scp ./{$argv[2]} cross@136.148.98.{$port_lsbu}://home/cross/iphone/”); //using scp to transfer.
}else{
echo ‘from iphone to home laptop’;
$output = shell_exec(“scp ./{$argv[2]} cross@192.168.1.{$port_home}://home/cross/iphone/”);
}
}else{ // no option, which start with ‘-’. only what file to transfer.
if(stristr($athome, ‘192.168.1.57′) == FALSE) {
echo ‘from lsbu pc to iphone’;
$output = shell_exec(“scp cross@136.148.98.{$port_lsbu}://home/cross/iphone/{$argv[1]} .”);
}else{
echo ‘from home laptop to iphone’;
$output = shell_exec(“scp cross@192.168.1.{$port_home}://home/cross/iphone/{$argv[1]} .”);
}
}

echo $output;
echo “done!”;
?>

a PHP script to transfer files between iphone and linux/mac computer

In howto, php on August 3, 2008 at 8:23 pm
#!/usr/bin/php

<?php
# requirement:
# a)the work directory on PC/laptop is /home/cross/iphone, which you should modify to suit your situation.
# b)install php on iphone.

# To transfer file from PC to iphone:
# php trans.php FILETOTRANSFER
# To transfer file from iphone to pc:
# php trans.php -[anything] FILETOTRANSFER

$port_lsbu = 150;
$port_home = 75;

$athome = shell_exec(“ifconfig”); // check where are you now.

if (substr($argv[1],0,1)==’-') { // get the first argument, if it starts with ‘-’, then transfer from iphone
if(stristr($athome, ‘192.168.1.57′) == FALSE) { // ip address of iphone at home is this, this command can find out where i am.
echo ‘from iphone to lsbu pc’;
$output = shell_exec(“scp ./{$argv[2]} cross@136.148.98.{$port_lsbu}://home/cross/iphone/”); //using scp to transfer.
}else{
echo ‘from iphone to home laptop’;
$output = shell_exec(“scp ./{$argv[2]} cross@192.168.1.{$port_home}://home/cross/iphone/”);
}
}else{ // no option, which start with ‘-’. only what file to transfer.
if(stristr($athome, ‘192.168.1.57′) == FALSE) {
echo ‘from lsbu pc to iphone’;
$output = shell_exec(“scp cross@136.148.98.{$port_lsbu}://home/cross/iphone/{$argv[1]} .”);
}else{
echo ‘from home laptop to iphone’;
$output = shell_exec(“scp cross@192.168.1.{$port_home}://home/cross/iphone/{$argv[1]} .”);
}
}

echo $output;
echo “done!”;
?>

howto: php: quote usage

In Blogged, howto, php on August 1, 2008 at 4:12 pm

Step 1 – PHP string basic

You can set a string in three different ways. It’s up to you what method do you use, all have pros.

  1. The
    first and most known way is to specify a string in single quotes.
    Similar to other programing languages you need to use backslash ‘\’ if
    you want to display a single quote in your text.
    Code:
    1. <?php
    2. $str_1 = 'Demo text';
    3. $str_2 = 'Demo text with single quote(\')';
    4. echo $str_1;
    5. echo $str_2;
    6. ?>
  2. The
    second option to use double quotes. Between double quotes you can use
    more escape character in your string. Besides this if you put a
    variable in the string then PHP will interpret it and display the
    content of the variable.
    Code:
    1. <?php
    2. $str_1 = "Demo text";
    3. $str_2 = "Demo text with double quote(\")\r\n";
    4. $demo = "Internal";
    5. $str_3 = "This is a $demo string";
    6. echo $str_1;
    7. echo $str_2;
    8. echo $str_3;
    9. ?>

    Here the most important part is the string defined as $str_3 and its output in line 8 will result this:

    Output:
    This is a Internal string
  3. And
    last you can use heredoc as well. In this case you define your text
    between heredoc identifiers. In this case it is DEMO. You need to start
    it with the operator <<< and then the identifier. If you are
    ready you need to close the heredoc part by adding the identifier again
    at the beginning of a new line like this:
    Code:
    1. <?php
    2. $str_1 = <<<DEMO
    3. This is a heredoc message
    4. Text.
    5. DEMO;
    6. echo $str_1;
    7. ?>

    As
    you can see the output is in the same formatting – text indent, new
    lines – as it was defined. You can use variables in case of heredoc as
    well as in case of double quoted strings.

The 2.
case is the most interesting string definition version so let’s see a
bit more how to insert a variable inside a string. (You can use
variables in case 3. as well but heredoc is not so common.)

Step 2 – Variable parsing in string

Time to time you need to compose a complete text from sub strings
and variables. For example if you want to greet your visitor you want
to display a text like:

“Hello Peter, nice to see you again!”

Of
course you can not hard code the user name but you want to use a
variable like $userName. If you use single quoted strings then you can
display your text like this:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo 'Hello '.$userName.', nice to see you again!';
  4. ?>

Using double quotes you can make it more simple:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "Hello $userName, nice to see you again!";
  4. ?>

The more variable you need to use the bigger is the difference.

After the basic case let’s see some more complex variable parsing. What if you want to display the text:

“Peters website”

Using the above examples the $userName variable contains only the string Peter and if you compose your string as before:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "$userNames website";
  4. ?>

You will get a warning and the result is not what you expected:

Output:
Notice: Undefined variable: userNames in Z:\wdocs\test.php on line 4 website

To solve this problem you need to enclose the variable in curly braces like in the following example:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "${userName}s website";
  4. echo "{$userName}s website";
  5. ?>

As you can see it is possible to enclose only the variable name without the $ sign or the complete variable.

You have to use this solution in case of arrays as well in the following way:

Code:
  1. <?php
  2. $users = array('U1' => "Peter");
  3. echo "Hello {$users['U1']}, nice to see you again!";
  4. ?>

howto: php: quote usage

In Blogged, howto, php on August 1, 2008 at 4:12 pm

Step 1 – PHP string basic

You can set a string in three different ways. It’s up to you what method do you use, all have pros.

  1. The
    first and most known way is to specify a string in single quotes.
    Similar to other programing languages you need to use backslash ‘\’ if
    you want to display a single quote in your text.
    Code:
    1. <?php
    2. $str_1 = 'Demo text';
    3. $str_2 = 'Demo text with single quote(\')';
    4. echo $str_1;
    5. echo $str_2;
    6. ?>
  2. The
    second option to use double quotes. Between double quotes you can use
    more escape character in your string. Besides this if you put a
    variable in the string then PHP will interpret it and display the
    content of the variable.
    Code:
    1. <?php
    2. $str_1 = "Demo text";
    3. $str_2 = "Demo text with double quote(\")\r\n";
    4. $demo = "Internal";
    5. $str_3 = "This is a $demo string";
    6. echo $str_1;
    7. echo $str_2;
    8. echo $str_3;
    9. ?>

    Here the most important part is the string defined as $str_3 and its output in line 8 will result this:

    Output:
    This is a Internal string
  3. And
    last you can use heredoc as well. In this case you define your text
    between heredoc identifiers. In this case it is DEMO. You need to start
    it with the operator <<< and then the identifier. If you are
    ready you need to close the heredoc part by adding the identifier again
    at the beginning of a new line like this:
    Code:
    1. <?php
    2. $str_1 = <<<DEMO
    3. This is a heredoc message
    4. Text.
    5. DEMO;
    6. echo $str_1;
    7. ?>

    As
    you can see the output is in the same formatting – text indent, new
    lines – as it was defined. You can use variables in case of heredoc as
    well as in case of double quoted strings.

The 2.
case is the most interesting string definition version so let’s see a
bit more how to insert a variable inside a string. (You can use
variables in case 3. as well but heredoc is not so common.)

Step 2 – Variable parsing in string

Time to time you need to compose a complete text from sub strings
and variables. For example if you want to greet your visitor you want
to display a text like:

“Hello Peter, nice to see you again!”

Of
course you can not hard code the user name but you want to use a
variable like $userName. If you use single quoted strings then you can
display your text like this:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo 'Hello '.$userName.', nice to see you again!';
  4. ?>

Using double quotes you can make it more simple:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "Hello $userName, nice to see you again!";
  4. ?>

The more variable you need to use the bigger is the difference.

After the basic case let’s see some more complex variable parsing. What if you want to display the text:

“Peters website”

Using the above examples the $userName variable contains only the string Peter and if you compose your string as before:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "$userNames website";
  4. ?>

You will get a warning and the result is not what you expected:

Output:
Notice: Undefined variable: userNames in Z:\wdocs\test.php on line 4 website

To solve this problem you need to enclose the variable in curly braces like in the following example:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "${userName}s website";
  4. echo "{$userName}s website";
  5. ?>

As you can see it is possible to enclose only the variable name without the $ sign or the complete variable.

You have to use this solution in case of arrays as well in the following way:

Code:
  1. <?php
  2. $users = array('U1' => "Peter");
  3. echo "Hello {$users['U1']}, nice to see you again!";
  4. ?>

Howto: trash files from other partitions into ‘bin’ on Ubuntu

In howto, linux on July 31, 2008 at 10:40 am
Issue:
—————————
When you want to delete some files from another partition which is mounted, ubuntu will prompt you warns dialog, saying “Cannot move file to the Deleted Items folder, do you want to delete permanently?”.

I always worried if I delete some files by impulse, because such kind of thing was done by me on Windows.

Solution:
—————————
For example, I am used to create a separate partition for ‘/usr/local’ to install some third party big programs.

cross@crossphoto:~$ cd /usr/local/
cross@crossphoto:/usr/local$ sudo mkdir .Trash-1000
cross@crossphoto:/usr/local$ sudo chown cross:root .Trash-1000/

Now /usr/local just like my ‘home’ folders, if I delete something, I can find them in the ‘deleted items’.

Trick/hint:
————————–
When other partitions are mounted by the boot, actually they are mounted by the user ‘root’. So you, the current user, have no permission to move anything to other folder-bin on that partition.
So create one for yourself, and using sudo to give you the permission to ‘write’ in that folder. Done.

Howto: trash files from other partitions into ‘bin’ on Ubuntu

In howto, linux on July 31, 2008 at 10:40 am
Issue:
—————————
When you want to delete some files from another partition which is mounted, ubuntu will prompt you warns dialog, saying “Cannot move file to the Deleted Items folder, do you want to delete permanently?”.

I always worried if I delete some files by impulse, because such kind of thing was done by me on Windows.

Solution:
—————————
For example, I am used to create a separate partition for ‘/usr/local’ to install some third party big programs.

cross@crossphoto:~$ cd /usr/local/
cross@crossphoto:/usr/local$ sudo mkdir .Trash-1000
cross@crossphoto:/usr/local$ sudo chown cross:root .Trash-1000/

Now /usr/local just like my ‘home’ folders, if I delete something, I can find them in the ‘deleted items’.

Trick/hint:
————————–
When other partitions are mounted by the boot, actually they are mounted by the user ‘root’. So you, the current user, have no permission to move anything to other folder-bin on that partition.
So create one for yourself, and using sudo to give you the permission to ‘write’ in that folder. Done.

Java/Jython to read file

In howto, java on July 12, 2008 at 12:19 pm
All the programs is quite preliminary and in Jython environment.

1. BufferedReader + FileReader
====================
import java.io as ji
fr=ji.FileReader(‘a.txt’)
br=ji.BufferedReader(fr)
text=br.readLine()

2. FileInputStream + BufferedInputStream + DataInputStream
====================
import java.io as ji
fis=ji.FileInputStream(‘a.txt’)
bis=ji.BufferedInputStream(fis)
dis=ji.DataInputStream(bis)
text=dis.readLine()

3. FileInputStream + BufferedInputStream + InputStreamReader + BufferedReader
====================
import java.io as ji
fis=ji.FileInputStream(‘a.txt’)
bis=ji.BufferedInputStream(fis)
isr=ji.InputStreamReader(bis)
br=ji.BufferedReader(isr)
text=br.readLine()

Java/Jython to read file

In howto, java on July 12, 2008 at 12:19 pm
All the programs is quite preliminary and in Jython environment.

1. BufferedReader + FileReader
====================
import java.io as ji
fr=ji.FileReader(‘a.txt’)
br=ji.BufferedReader(fr)
text=br.readLine()

2. FileInputStream + BufferedInputStream + DataInputStream
====================
import java.io as ji
fis=ji.FileInputStream(‘a.txt’)
bis=ji.BufferedInputStream(fis)
dis=ji.DataInputStream(bis)
text=dis.readLine()

3. FileInputStream + BufferedInputStream + InputStreamReader + BufferedReader
====================
import java.io as ji
fis=ji.FileInputStream(‘a.txt’)
bis=ji.BufferedInputStream(fis)
isr=ji.InputStreamReader(bis)
br=ji.BufferedReader(isr)
text=br.readLine()

Regular Expressions for grep, sed, awk

In howto, linux on July 2, 2008 at 12:54 pm
One of the examples in last week’s tip used the following awk statement to extract, from a file named unixfile, lines (records) that contained the string “learn” in them:

awk ‘/learn/ { print $2 ” ” $1 }’ unixfile

The string “learn” in this statement is a regular expression that is delimited on each end by the forward slash (/) character. In addition to awk, regular expressions are often used with other UNIX utilities such as grep, sed, and vi.

Regular expressions, often abbreviated as regex or regexp, describe a pattern or particular sequence of characters and are used to search for and replace strings.

Most characters used in a regex will represent themselves, but there are special characters (known as metacharacters) that take on special meaning in the context of the UNIX utility/tool in which they are used.

Since the topic of regular expressions is quite extensive, this brief overview will only focus on two of its frequently used positional or anchor metacharacters, the caret (^) and the dollar sign ($).

The caret is used to match at the beginning of a line, and the dollar sign is used to match at the end of a line. Carets will logically be found on the left-hand side of a regex, and dollar signs on the right.

To demonstrate the usage of these two positional metacharacters, the same data file used for last week’s tip will be used again this week. The only change made was the insertion of 4 blank lines between each line of text. The file unixfile now contains the following data:

unix training

learn unix

unix class

learning unix

unix course

Using grep, all lines in unixfile that begin with “unix” will be extracted with the help of the caret metacharacter:

# grep ‘^unix’ unixfile
unix training
unix class
unix course

Removing the caret from the beginning of the regex and adding a dollar sign to the end will cause grep to display lines ending with “unix”:

# grep ‘unix$’ unixfile
learn unix
learning unix

These two metacharacters can also be combined in a single regex to identify/manipulate blank lines. The -c option for grep will be used with a regex containing both the caret and the dollar sign to count the number of blank lines in unixfile:

# grep -c ‘^$’ unixfile
4

You may recognize that this regex would be useful for removing blank lines from a file when needed.

Experienced UNIX system administrators and shell script programmers understand that becoming skilled in the use of regular expressions is essential for using standard UNIX utilities (e.g. grep, awk, sed, and vi) to their fullest potential.

GREP

grep searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.”

AWK

Awk scans each input file for lines that match any of a set of patterns specified literally in prog or in one or more files specified as -f progfile. With each pattern there can be an associated action that will be performed when a line of a file matches the pattern. Each line is matched against the pattern portion of every pattern-action statement; the associated action is performed for each matched pattern.”

SED

“The sed utility is a stream editor that reads one or more text files, makes editing changes according to a script of editing commands, and writes the results to standard output.”

# 在file 1中找到含有firststring那行,并在第二个空格之后加入secondstring。
# 注意 s/set1/set2/g, g用来代表全局替换,而2则表示再第二次出现的时候替换。
sed -i ‘/firststring/ s/ / secondstring/2′ file1

# 在file 1中最后那行的末尾加入finalstring。
sed -i ‘$ s/$/finalstring/’ file1


REGULAR EXPRESSIONS

Regular expressions allow you to use variables in your commands. Most of us are at least familiar with *, where *.db means “every file ending in .db”. There are however many useful regular expressions, and they are the key to executing the above commands efficiently. Brush up on regular expressions here.

PIPES AND REDIRECTS

In order to send the results from one command to another command you need to “pipe” them together. An example:

cat *.txt | grep "blatti.net"

cat *.txt will display the contents of every file that ends in “.txt” to the standard output. By piping those results, they become the input for the second command. grep "blatti.net" will take the standard input, and display each line that contains “blatti.net” on the standard output. So when these two commands are piped together, we will get every line that contains “blatti.net” in every file that ends in “.txt” in the working directory.

While most of your work can be done with standard input and output, you’ll probably want to write your results to a file. Enter redirection. Using the example above, lets say we wanted to take our results and write it to a file. This is done with the > redirector.

cat *.txt | grep "blatti.net" > results.txt

This command will take every line that contains “blatti.net” in every file that ends in “.txt” in the working director, and write them to the file “results.txt”. Note that this will overwrite any existing “results.txt” file that exists in the working directory. Which begs the question “What if I want to append instead of overwrite?” Well then use >> instead of >. The >> redirector is especially useful if you are creating logs.

Now you too can create obnoxious commands with limited knowledge! The command below is one I created using the resources listed in this article. It is part of a piece of software that pulls text out of a PDF and returns a specified section in a text file. (I’m sure it is inefficient – so someone chime in and tell me how to make it better so I’ll know for next time)

sed 's/^[0-9]$/Period &/’ /tmp/skypdf.txt | sed ’s/[A-Z]*$/&,/’ | sed ‘/Period/G’ | sed ‘$!N;s/\\n/ /’ | sed ‘/Period/{x;p;x;}’ | sed ’s/^ //’ > ~/Desktop/full.txt”

Now say that 10 times fast!

Php console came out

In howto, linux on July 2, 2008 at 11:18 am
install php-cli you will have the console similar to python for php programming.

  • php -a: console environment
  • php -r <command>: run single php command line like what ‘python -c’ does. ( must end with ‘;’)
  • php -f <php file>: just for pure php codes, if there are some html codes, it still works, but will pup up a lot of html tag.

Php console came out

In howto, linux on July 2, 2008 at 11:18 am
install php-cli you will have the console similar to python for php programming.

  • php -a: console environment
  • php -r <command>: run single php command line like what ‘python -c’ does. ( must end with ‘;’)
  • php -f <php file>: just for pure php codes, if there are some html codes, it still works, but will pup up a lot of html tag.

Howto setup share folder within VirtualBox

In howto, linux on May 30, 2008 at 7:08 pm

1.setup share folder with VirtualBox (for example: the folder name is SHARED), and share it.
2.In the guest OS of windows, use this command to mount it: net use z: \\vboxsvr\SHARED.

Gnome-Do, super! set it up.

In howto, linux on May 6, 2008 at 4:19 pm

1. Install it.
2. Download extra plugins for it from its official website: https://wiki.ubuntu.com/GnomeDo/Plugins
3. Try to run every plugins, in this way, the corresponding config files will be generated. (You should goto ‘gconf-editor’->apps->gnome-do->plugins to modify most of them.)

4(Optional). Goto ~/.config/gnome-dos/FileItemSource.config to modify the search path and depth.

Linux Log files and usage

In howto, linux on May 6, 2008 at 9:14 am
=&gt; /var/log/messages : General log messages

=&gt; /var/log/boot : System boot log

=&gt; /var/log/debug : Debugging log messages

=&gt; /var/log/auth.log : User login and authentication logs

=&gt; /var/log/daemon.log : Running services such as squid, ntpd and others log message to this file

=&gt; /var/log/dmesg : Linux kernel ring buffer log

=&gt; /var/log/dpkg.log : All binary package log includes package installation and other information

=&gt; /var/log/faillog : User failed login log file

=&gt; /var/log/kern.log : Kernel log file

=&gt; /var/log/lpr.log : Printer log file

=&gt; /var/log/mail.* : All mail server message log files

=&gt; /var/log/mysql.* : MySQL server log file

=&gt; /var/log/user.log : All userlevel logs

=&gt; /var/log/xorg.0.log : X.org log file

=&gt; /var/log/apache2/* : Apache web server log files directory

=&gt; /var/log/lighttpd/* : Lighttpd web server log files directory

=&gt; /var/log/fsck/* : fsck command log

=&gt; /var/log/apport.log : Application crash report / log file

To view log files at shell prompt

Use tail, more, less and grep command.

tail -f /var/log/apport.log

more /var/log/xorg.0.log

cat /var/log/mysql.err

less /var/log/messages

grep -i fail /var/log/boot

View log files using GUI tools using the GNOME System Log Viewer

System Log Viewer is a graphical, menu-driven viewer that you can
use to view and monitor your system logs. System Log Viewer comes with
a few functions that can help you manage your logs, including a
calendar, log monitor and log statistics display. System Log Viewer is
useful if you are new to system administration because it provides an
easier, more user-friendly display of your logs than a text display of
the log file. It is also useful for more experienced administrators, as
it contains a calendar to help you locate trends and track problems, as
well as a monitor to enable you to continuously monitor crucial logs.

You can start System Log Viewer in the following ways:

Click on System menu &gt; Choose Administration &gt; System Log:

(The GNOME System Log Viewer)

Note you can start the GNOME System Log Viewer from a shell prompt, by entering the following command:

$ gnome-system-log &

Wine Go for Chinese Fonts

In howto, linux on May 4, 2008 at 8:28 pm
首先wine自己的系统中必须有中文字体,我的Ubuntu系统中已经安装了宋体,这也是Windows Vista之前的几个版本的系统使用的中文字体,所以:

cd ~/.wine/drive_c/windows/fonts

ln -s /usr/share/fonts/truetype/simsun.ttf simsun.ttc

当然,也可以将该字体复制到fonts目录,这里直接建立连接,省空间。

然后修改wine的注册表:

vi ~/.wine/system.reg

找到“[System\\CurrentControlSet\\Hardware Profiles\\Current\\Software\\Fonts]”,将其中的““LogPixels”=dword:00000060”改成““LogPixels”=dword:00000070“。

再找到”[Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes] 1144897563“项,将其中的”MS Shell Dlg“相关的两项修改成如下内容(即更换字体为宋体):

“MS Shell Dlg”=”SimSun”

“MS Shell Dlg 2″=”SimSun”

然后:

vi ~/.wine/drive_c/windows/win.ini

将”Desktop“块修改成如下内容(即增大字体):

[Desktop]

menufontsize=13

messagefontsize=13

statusfontsize=13

IconTitleSize=13

Wine Go for Chinese Fonts

In howto, linux on May 4, 2008 at 8:28 pm
首先wine自己的系统中必须有中文字体,我的Ubuntu系统中已经安装了宋体,这也是Windows Vista之前的几个版本的系统使用的中文字体,所以:

cd ~/.wine/drive_c/windows/fonts

ln -s /usr/share/fonts/truetype/simsun.ttf simsun.ttc

当然,也可以将该字体复制到fonts目录,这里直接建立连接,省空间。

然后修改wine的注册表:

vi ~/.wine/system.reg

找到“[System\\CurrentControlSet\\Hardware Profiles\\Current\\Software\\Fonts]”,将其中的““LogPixels”=dword:00000060”改成““LogPixels”=dword:00000070“。

再找到”[Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes] 1144897563“项,将其中的”MS Shell Dlg“相关的两项修改成如下内容(即更换字体为宋体):

“MS Shell Dlg”=”SimSun”

“MS Shell Dlg 2″=”SimSun”

然后:

vi ~/.wine/drive_c/windows/win.ini

将”Desktop“块修改成如下内容(即增大字体):

[Desktop]

menufontsize=13

messagefontsize=13

statusfontsize=13

IconTitleSize=13

Restore All Installed packages in Ubuntu Hardy Heron and to a New machine

In Blogged, howto, linux on May 2, 2008 at 5:19 pm

The following command creates a list of all the installed packages at the present time:

sudo dpkg –get-selections &gt; /etc/package.selections

Now
we created our package list and we can copy this list to a new ubuntu
computer and install the same packages in the list to the new machine
or, restore the packages to the time you created the package list:

sudo dpkg –set-selections &lt; /etc/package.selections && apt-get dselect-upgrade

The above command will uninstall all packages installed after you created your restore list.

Restore All Installed packages in Ubuntu Hardy Heron and to a New machine

In Blogged, howto, linux on May 2, 2008 at 5:19 pm

The following command creates a list of all the installed packages at the present time:

sudo dpkg –get-selections &gt; /etc/package.selections

Now
we created our package list and we can copy this list to a new ubuntu
computer and install the same packages in the list to the new machine
or, restore the packages to the time you created the package list:

sudo dpkg –set-selections &lt; /etc/package.selections && apt-get dselect-upgrade

The above command will uninstall all packages installed after you created your restore list.

linux memory management: buffer and cache

In howto, linux on April 27, 2008 at 4:43 pm
free

  free 命令相对于top 提供了更简洁的查看系统内存使用情况:

  $ free

  # free
   total used free shared buffers cached
  Mem: 255988 231704 24284 0 6432 139292
  -/+ buffers/cache: 85980 170008
  Swap: 746980 0 746980

  Mem:表示物理内存统计

  -/+ buffers/cached:表示物理内存的缓存统计

  Swap:表示硬盘上交换分区的使用情况,这里我们不去关心。

  系统的总物理内存:255268Kb(256M),但系统当前真正可用的内存b并不是第一行free 标记的 16936Kb,它仅代表未被分配的内存。

  我们使用total1、used1、free1、used2、free2 等名称来代表上面统计数据的各值,1、2 分别代表第一行和第二行的数据。

  total1:表示物理内存总量。
  used1:表示总计分配给缓存(包含buffers 与cache )使用的数量,但其中可能部分缓存并未实际使用。
  free1:未被分配的内存。
  shared1:共享内存,一般系统不会用到,这里也不讨论。
  buffers1:系统分配但未被使用的buffers 数量。
  cached1:系统分配但未被使用的cache 数量。buffer 与cache 的区别见后面。
  used2:实际使用的buffers 与cache 总量,也是实际使用的内存总量。
  free2:未被使用的buffers 与cache 和未被分配的内存之和,这就是系统当前实际可用内存。

  可以整理出如下等式:

  total1 = used1 + free1total1 = used2 + free2used1 = buffers1 + cached1 + used2free2 = buffers1 + cached1 + free1

  buffer 与cache 的区别

 
 A buffer is something that has yet to be “written” to disk. A cache is
something that has been “read” from the disk and stored for later use.

linux memory management: buffer and cache

In howto, linux on April 27, 2008 at 4:43 pm
free

  free 命令相对于top 提供了更简洁的查看系统内存使用情况:

  $ free

  # free
   total used free shared buffers cached
  Mem: 255988 231704 24284 0 6432 139292
  -/+ buffers/cache: 85980 170008
  Swap: 746980 0 746980

  Mem:表示物理内存统计

  -/+ buffers/cached:表示物理内存的缓存统计

  Swap:表示硬盘上交换分区的使用情况,这里我们不去关心。

  系统的总物理内存:255268Kb(256M),但系统当前真正可用的内存b并不是第一行free 标记的 16936Kb,它仅代表未被分配的内存。

  我们使用total1、used1、free1、used2、free2 等名称来代表上面统计数据的各值,1、2 分别代表第一行和第二行的数据。

  total1:表示物理内存总量。
  used1:表示总计分配给缓存(包含buffers 与cache )使用的数量,但其中可能部分缓存并未实际使用。
  free1:未被分配的内存。
  shared1:共享内存,一般系统不会用到,这里也不讨论。
  buffers1:系统分配但未被使用的buffers 数量。
  cached1:系统分配但未被使用的cache 数量。buffer 与cache 的区别见后面。
  used2:实际使用的buffers 与cache 总量,也是实际使用的内存总量。
  free2:未被使用的buffers 与cache 和未被分配的内存之和,这就是系统当前实际可用内存。

  可以整理出如下等式:

  total1 = used1 + free1total1 = used2 + free2used1 = buffers1 + cached1 + used2free2 = buffers1 + cached1 + free1

  buffer 与cache 的区别

 
 A buffer is something that has yet to be “written” to disk. A cache is
something that has been “read” from the disk and stored for later use.

why I love twitter

In howto, life on April 22, 2008 at 11:24 am
1)Mini Blog
我用twitter主要是记事,比如买了iphone,或者今天看了火箭对犹他的比赛,犹他打得总是那么丑陋还能赢,我只想说这一句,就不用劳师动众写到blog里了,所以这叫mini blog。

Twitter in Plain English from leelefever on Vimeo.

2)Share Status
然后在twitter上加我为好友的人,就能看到我这些话,就知道了我在做什么,同时我也会知道我的朋友们都在干什么。对友善的人,这个很有帮助。(自闭的就不用考虑这个了)

3)Time Line
还有一个很重要的意义就是,比如今天网络公司给我打电话说给我一个什么offer,说完全免费,我就留在twitter里,否则,日后它收我钱,我都忘记他们哪天给我打的电话。没办法和他们理论。或者向我那个iphone,几年后,我都会知道我那个电话跟了我多久了,像我以前那些经典电话Matrix 1中的nokia 8088,Nokia QD, Blackberry我都忘了什么时候的事了,或者与谁相识多久也都全靠猜和估计了,有了twitter,也不用总记得哪天是与女友的周年庆了。

4)Widely Supported
用twitter可以更新同步facebook,blog上的status,很方便,如此可以把facebook上的status都保存记录在一起,可以自己回顾最近都做了些什么,facebook上是不能记录以往的status的,twitter正好弥补。而且还可以用Messenger去更新twitter。真正的体现了web 2.0 的mashup。支持twitter的网站和程序数以百计了,而且不错的点子层出不穷。比如twittervision.com/local/london,就能看到london在twitter的人所在的位置(目前这个网站还是beta,有些bug,不过类似的网站数百计了。很多twitter的应用)。
国内有个中文的叫饭否,但是就支持程度和与其他网站协作的能力饭否还差很远。

5) Alternative Email
与一些新结识的朋友留下联系方式,不用bla bla bla说上很长还容易错的email了,直接留twitter,方便好记,还不怕junk。越来越多的IT geek都用这个作为联系方式了。

iphone passwd change from alpine to anything

In bug, howto, iphone on April 21, 2008 at 9:42 pm
passwd, this command not work properly in iphone (currently 1.1.4), it will cause endless loop, you must restore the system using itune. So this is the way how to change it.

Login to your iPhone using SSH, or use the Terminal Application, type vi /etc/master.passwd, and look for this line :

root:YOUROUTPUTHERE:0:0::0:0:System Administrator:/var/root:/bin/sh

Replace the content immediately after the root: with the output from that command we used early on. Done, password changed.
Maybe do the same for the mobile User, which is also a line in the same file.

NOTE:
Someone mailed me and stated that the above method did not work for him at all. Quite the opposite, he had to reinstall his Firmware again. Annoying. According to him, the
following snipped to generate the Password Hash worked fine.

openssl passwd -crypt -salt /s myNewPasswd

Personally right now i don’t have another iPhone to try this on, but i think i should still mention his method here.

from: http://www.overridersworld.com/?p=74
=================================

Some discussion:
Before I tested your method I wanted to make sure the output with the default pw ‘alpine’ would be equal to the crypted pw in mast.passwd.

master.passwd: /smx7MYTQIi2M

Perl method:
perl -e ‘print crypt(”alpine”, “XX”).”\n”‘
XXCLVpuFl/zmI

hmm…

OpenSSL method:
openssl passwd -crypt -salt /s djsr71bb
/smx7MYTQIi2M

So the OpenSSL provided the correct output.
I have now changed the pw to my own pw and everything works fine.
So I guess the perl method would not have worked with me.

Title bar for blogspot

In google, howto on April 13, 2008 at 2:42 pm

1.Goto http://www.dynamicdrive.com/style to pick up one style you fancy. Click it, of course, then.

2.There are two parts of codes come to you, one is the CSS codes used to feed BLOGGER DASHBOARD-LAYOUT-EDIT TEMPLATE.
Search “</head>”, put the CSS codes just before that. Save the template.

3.The other codes is for BLOGGER DASHBOARD-LAYOUT-PAGE ELEMENT.
From “Add a Page Element” select HTML/Javascript, feed those codes there without title. Save it.

4.You are almost there, but be careful in the step 2, because the CSS uses some images as button background, where relative url is used for the allocations of those images. Even if you hacked where those stored, namely absolute url, some time those images is not accessible. So my solution is use some photo album service, such as Picasaweb, which can provide absolute url of your photos. Then use this url to replace those relative ones in that CSS codes. Done.

Two examples of matlab implement java

In howto, java, matlab on March 27, 2008 at 6:15 pm

Example 1: print a line
===================
import java.lang.System;
System.out.println(‘zhengxin’);

% in Java environment, java.lang.* is automatically imported, so no need to import it when programming with java. But in Matlab, this package/classes must be imported manually.

Example 2: show a dialog
===================
import java.awt.*;
import javax.swing.*;

title = ‘Frame Title’;
frame = JFrame(title);
comp = JTextArea();
frame.getContentPane.add(comp, BorderLayout.CENTER);
width = 300;
height = 300;
frame.setSize(width, height);
frame.show();

Blocking China

In howto, linux on March 18, 2008 at 1:11 pm

The last few days there are so many connections to our mirror server
from China that I started to block certain subnets. There are usually
around 10 clients connecting via HTTP and each is opening over 50
connections to our server. They are downloading mainly ISO images and
other big files. I can see that each client is starting to download
lots of different things. From Fedora 3 to Fedora 7 ISO images, Ubuntu ISO images,
openSUSE ISO images and other old and large files.

I started to block individual IP addresses but there are just too many so
that I started to block whole subnets. I am using the following command to get
an overview about which clients are opening many connections at once:

lynx -dump -width=2000 http://localhost/server-status | awk -F\ ‘{ print $11} ‘ | sort -n | uniq -c | sort -n.

The output looks something like this:

21 122.48.129.75
23 210.21.106.229
24 218.17.228.216
26 220.175.101.252
27 222.67.18.227
30 222.27.89.136
39 123.116.101.186
52 121.231.17.153
63
63 ::1

With the following command I am calculating the netmask which will be blocked:

$ whois 121.231.17.153 | grep inetn | sed -e “s, – ,:,g” | awk ‘ { print “netmask “$2 }’ | sh

121.224.0.0/12

And then I am using a simple iptables rule to drop any traffic coming from that network:

iptables -A INETIN -s 121.224.0.0/12 -j DROP

Currently this is the only idea I have how to get rid of those ~500 connections which seem to be some kind of abuse.

Blocking China

In howto, linux on March 18, 2008 at 1:11 pm

The last few days there are so many connections to our mirror server
from China that I started to block certain subnets. There are usually
around 10 clients connecting via HTTP and each is opening over 50
connections to our server. They are downloading mainly ISO images and
other big files. I can see that each client is starting to download
lots of different things. From Fedora 3 to Fedora 7 ISO images, Ubuntu ISO images,
openSUSE ISO images and other old and large files.

I started to block individual IP addresses but there are just too many so
that I started to block whole subnets. I am using the following command to get
an overview about which clients are opening many connections at once:

lynx -dump -width=2000 http://localhost/server-status | awk -F\ ‘{ print $11} ‘ | sort -n | uniq -c | sort -n.

The output looks something like this:

21 122.48.129.75
23 210.21.106.229
24 218.17.228.216
26 220.175.101.252
27 222.67.18.227
30 222.27.89.136
39 123.116.101.186
52 121.231.17.153
63
63 ::1

With the following command I am calculating the netmask which will be blocked:

$ whois 121.231.17.153 | grep inetn | sed -e “s, – ,:,g” | awk ‘ { print “netmask “$2 }’ | sh

121.224.0.0/12

And then I am using a simple iptables rule to drop any traffic coming from that network:

iptables -A INETIN -s 121.224.0.0/12 -j DROP

Currently this is the only idea I have how to get rid of those ~500 connections which seem to be some kind of abuse.

Facebook application: Invitation page

In howto, php on March 17, 2008 at 2:43 pm


<?php

require_once 'facebook.php';

$appapikey = '1111111111111111111111111';

$appsecret = '111111111111111111111111111';

$facebook = new Facebook($appapikey, $appsecret);

$user = $facebook->require_login();

// Build your invite text

$invfbml = <<<FBML

You have been invited to join YQLM notifier.

<fb:name uid="$user" firstnameonly="true" shownetwork="false"/> wants you to add YQLM googlegroups Notifier. so that you can join

<fb:pronoun possessive="true" uid="$user"/>London YQLM GoogleGroups! <fb:req-choice url="http://www.facebook.com/add.php?api_key=$appapikey" label="Add this application" />

FBML;

?>

<fb:request-form type="YQLM Notifier" action="./index.php" content="<?=htmlentities($invfbml)?>" invite="true">

<fb:multi-friend-selector max="20" actiontext="Select your friends to add this application!" showborder="true" rows="3">

</fb:request-form>

Facebook application: Rss notifier

In howto, php on March 14, 2008 at 2:48 pm


<?php //create 1 hour life cookie to prevent duplicate news

feed story.

/*

session_start();

if(isset($_SESSION['views']))

  $_SESSION['views']=$_SESSION['views']+1;

else

  $_SESSION['views']=1;

echo "Total Visits: ". $_SESSION['views'];

//*/

////////// session or cookie /////////////////

if (isset($_COOKIE["updatetime"])){

}

else{

setcookie("updatetime", time(), time()+3600);

}

?>

<?php

require_once 'facebook.php';

$appapikey = '3d3fabe3276d1dd50ddf78353c719af4';

$appsecret = 'fe4754d97d24392ba9e40105f0ea0a08';

$facebook = new Facebook($appapikey, $appsecret);

$user_id = $facebook->require_login();

// Greet the currently logged-in user!

echo "<p>Hello, <fb:name uid=\"$user_id\" useyou=\"false\"

/>!<br/>"." There are new messages on the YQLM group.</p>";

?>

<?php

// Parse the Rss feed.

$doc = new DOMDocument();

$doc->load

('http://groups.google.co.uk/group/londonppl/feed/atom_v1_0_ms

gs.xml');

//$doc->load

('http://feeds.feedburner.com/YqlmLondonGoogleGroup');

$arr = array();

foreach ($doc->getElementsByTagName('entry') as $node) {

$itemRSS = array (

'author' => $node->getElementsByTagName

('name')->item(0)->nodeValue,

'email' => $node->getElementsByTagName

('email')->item(0)->nodeValue,

'date' => $node->getElementsByTagName

('updated')->item(0)->nodeValue,

'link' => $node->getElementsByTagName('link')

->item(0)->getAttribute("href"),

'title' => $node->getElementsByTagName

('title')->item(0)->nodeValue,

'desc' => $node->getElementsByTagName

('summary')->item(0)->nodeValue);

array_push($arr, $itemRSS);

}

?>

<?php

// Show Rss contents in facebook canvas.

$dashbutton = <<<EndHereDoc

<fb:dashboard> <fb:create-button

href="http://www.facebook.com/apps/application.php?

id=11393681690">Add/Remove this application</fb:create-button>

</fb:dashboard>

EndHereDoc;

echo $dashbutton;

for ($i=0;$i<10;$i++){

echo '<br/>'.'==================='.'<br/>';

$item = $arr[$i];

$author = ($item['author']=="")?$item['email']:$item

['author'];

$content = '<b>'.$author.'</b><i> said on </i>'.$item

['date'].'<br/>'.'<a href="'.$item['link'].'">'.$item

['title'].'</a><br/><li>'.$item['desc'].'</li>';

echo $content;

}

?>

<?php

// Generate short contents in users' profile file.

$profilecontent = '<a

href="http://apps.facebook.com/googlegroupsnotifier">YQLM

Group</a><br/>';

for ($i=0;$i<2;$i++){

$pitem = $arr[$i];

$author = ($pitem['author']=="")?$pitem

['email']:$pitem['author'];

$profilecontent =

$profilecontent.'==================='.'<br/><b>'.$author.'</b>

<i> said on </i>'.$pitem['date'].'<br/><i>'.$pitem

['title'].'</i><br/><li>'.$pitem['desc'].'</li><br/>';

}

?>

<?php

///*

// This is for fbml_setRefHandle

$fbml = <<<EndHereDoc

<fb:wide>

$profilecontent

<fb:editor

action="http://apps.facebook.com/googlegroupsnotifier">

<fb:editor-button value="More messages"/>

</fb:editor>

</fb:wide>

<fb:narrow>

$profilecontent

<fb:editor

action="http://apps.facebook.com/googlegroupsnotifier">

<fb:editor-button value="More messages"/>

</fb:editor>

</fb:narrow>

EndHereDoc;

$facebook->api_client->fbml_setRefHandle

("googlegroupsnotifier",$fbml);

// */

$refinprofile = '<fb:ref handle="googlegroupsnotifier" />';

$facebook->api_client->profile_setFBML

($refinprofile,$user_id);

?>

<?php

// This is for news feed/mini feed.

$title_template = "{actor} viewed the group";

$title_data = null;

$body_template = null;

$body_data = null;

$fitem = $arr[0];

$author = ($fitem['author']=="")?$fitem

['email']:$fitem['author'];

$feedcontent = '<br/>'.$author.' said

<br/><b>'.$fitem['desc'].'</b><br/> in the topic of

'.'<i>'.$fitem['title'].'</i>';

$body_general = 'The latest post : <br/>'.$feedcontent;

//print_r($_COOKIE);

//echo time()-$_COOKIE["updatetime"];

if (time()-$_COOKIE["updatetime"]>3600){

echo "<br/><i>A new news feed will be published in the

next 1 hour.</i>";

try{

$facebook->api_client-

>feed_publishTemplatizedAction

($title_template,$title_data,$body_template,$body_data,$body_g

eneral);

}catch(Exception $e) {

//this will clear cookies for your app and

redirect them to a login prompt

echo "<br/><br/><i>"."Update the news feed too

many times, no news will appear today."."</i>";

$facebook->set_user(null, null);

}

}

else

echo "<br/><i>No news feed will be published in the

next 1 hour.</i>";

?>

Accessing an SMB Share With Linux MachinesAccessing an SMB Share With Linux Machines

In howto, linux on March 11, 2008 at 3:38 pm

Linux (UNIX) machines can also browse and mount SMB shares. Note that this can be done whether the server is a Windows machine or a Samba server!

An SMB client program for UNIX machines is included with the Samba distribution. It provides an ftp-like interface on the command line. You can use this utility to transfer files between a Windows ’server’ and a Linux client.

Most Linux distributions also now include the useful smbfs package, which allows one to mount and umount SMB shares. More on smbfs below.

To see which shares are available on a given host, run:


    /usr/bin/smbclient -L host

where ‘host’ is the name of the machine that you wish to view. this will return a list of ’service’ names – that is, names of drives or printers that it can share with you. Unless the SMB server has no security configured, it will ask you for a password. Get it the password for the ‘guest’ account or for your personal account on that machine.

For example:


    smbclient -L zimmerman

The output of this command should look something like this:



Server time is Sat Aug 10 15:58:27 1996Timezone is UTC+10.0Password:Domain=[WORKGROUP] OS=[Windows NT 3.51] Server=[NT LAN Manager 3.51]

Server=[ZIMMERMAN] User=[] Workgroup=[WORKGROUP] Domain=[]

       Sharename      Type      Comment       ---------      ----      -------       ADMIN$         Disk      Remote Admin       public         Disk      Public       C$             Disk      Default share       IPC$           IPC       Remote IPC       OReilly        Printer   OReilly       print$         Disk      Printer Drivers

This machine has a browse list:

       Server               Comment       ---------            -------       HOPPER               Samba 1.9.15p8       KERNIGAN             Samba 1.9.15p8       LOVELACE             Samba 1.9.15p8       RITCHIE              Samba 1.9.15p8       ZIMMERMAN           

The browse list shows other SMB servers with resources to share on the network.

To use the client, run:


    /usr/bin/smbclient service 

where ’service’ is a machine and share name. For example, if you are trying to reach a directory that has been shared as ‘public’ on a machine called zimmerman, the service would be called \\zimmerman\public. However, due to shell restrictions, you will need to escape the backslashes, so you end up with something like this:


    /usr/bin/smbclient \\\\zimmerman\\public mypasswd

where ‘mypasswd’ is the literal string of your password.

You will get the smbclient prompt:



Server time is Sat Aug 10 15:58:44 1996Timezone is UTC+10.0Domain=[WORKGROUP] OS=[Windows NT 3.51] Server=[NT LAN Manager 3.51]smb: \>

Type ‘h’ to get help using smbclient:



smb: \> hls             dir            lcd            cd             pwd           get            mget           put            mput           rename        more           mask           del            rm             mkdir         md             rmdir          rd             prompt         recurse       translate      lowercase      print          printmode      queue         cancel         stat           quit           q              exit          newer          archive        tar            blocksize      tarmode       setmode        help           ?              !             smb: \>

If you can use ftp, you shouldn’t need the man pages for smbclient.

Although you can use smbclient for testing, you will soon tire of it for real work. For that you will probably want to use the smbfs package. Smbfs comes with two simple utilties, smbmount and smbumount. They work just like mount and umount for SMB shares.

One important thing to note: You must have smbfs support compiled into your kernel to use these utilities!

The following shows a typical use of smbmount to mount an SMB share called “customers” from a machine called “samba1″:



[root@postel]# smbmount "\\\\samba1\\customers" -U rtg2t -c 'mount /customers -u 500 -g 100'Added interface ip=192.168.35.84 bcast=192.168.255.255 nmask=255.255.0.0Got a positive name query response from 192.168.168.158 ( 192.168.168.158 )Server time is Tue Oct  5 10:27:36 1999Timezone is UTC-4.0Password:Domain=[IPM] OS=[Unix] Server=[Samba 2.0.3]security=user

Issuing a mount command will now show the share mounted, just as if it were an NFS export:



[root@postel]# mount                                                                                                   /dev/hda2 on / type ext2 (rw)none on /proc type proc (rw)none on /dev/pts type devpts (rw,mode=622)//SAMBA1/CUSTOMERS on /customers type smbfs (0)

Please see the manual pages for smbmount and smbumount for details on the above operation.

A simple ajax example

In JavaScript, howto on March 10, 2008 at 5:22 pm


A simple ajax example

<html><body>

<script language="javascript" type="text/javascript">

var inputs = 0;

function addContact(){

var table = document.getElementById('contacts');

var tr = document.createElement('TR');

var td1 = document.createElement('TD');

var td2 = document.createElement('TD');

var td3 = document.createElement('TD');

var inp1 = document.createElement('INPUT');

var inp2 = document.createElement('INPUT');

///////////////

var link = document.createElement('a');

var U = document.createElement('u');

var text = document.createTextNode('del');

link.onclick = function(){

removeContact(tr);

//inputs--;

}

U.appendChild(text);

link.appendChild(U);

td1.appendChild(link);

///////////////

inp1.setAttribute("Name", "Name" +inputs);

inp2.setAttribute("Name", "Email"+inputs);

table.appendChild(tr);

tr.appendChild(td1);

tr.appendChild(td2);

tr.appendChild(td3);

td2.appendChild(inp1);

td3.appendChild(inp2);

inputs++;

}

function removeContact(tr){

tr.parentNode.removeChild(tr);

}

</script>

<table>

<tbody id="contacts">

    <tr>

        <a href="javascript:addContact();">Add a Contact</a>

    </tr>

    <tr>

        <td></td>

        <td>Name</td>

        <td>Email</td>

        </tr>

</tbody>

</table>

<script type="text/javascript">

    addContact();

</script>

</body></html>

develop, deploy and run java servlet

In howto, java on March 9, 2008 at 2:18 am

///////////1. Java Class ///////////////////////////
If you are not using Java EE SDK, you must download Java Servlet Api:servlet-2_5-api.jar, than put it in the classpath.

// HW.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HW extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“”);
out.println(“”);
out.println(“Hello World!”);
out.println(“”);
out.println(“”);
out.println(“Hello World!”);
out.println(“By Cross”);
out.println(“”);
out.println(“”);
}
}

/////////// Deploy it ///////////////////////////////
Put the class in \Tomcat\webapps\ROOT\WEB-INF\classes
Edit web.xml by append following ‘xml’ element.

// web.xml in \Tomcat\webapps\ROOT\WEB-INF

myHelloWorld
HW

myHelloWorld
/myHello

////////// Run it ///////////////////////////////////
Start Tomcat, then run it like this:
http://localhost/myHello

P.S.: use ” to replace ” to escape Blogspot parsing html tag.
How getParameters from request, see here:
http://java.sun.com/developer/technicalArticles/RMI/rmi/
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/Servlets/Q_22996074.html?eeSearch=true

retrive XML in ajax way: xmlhttprequest

In JavaScript, howto on March 7, 2008 at 12:49 pm


Following codes is the minimum 4 steps for XMLHttpRequest.

<script language="javascript">

////////////////// initial xmlhttprequest ///////////////////////////

// 1. new XMLHttpRequest()

if (window.XMLHttpRequest) {

req = new XMLHttpRequest();

}

else{

try {

req = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

alert('Old Microsoft.XMLHTTP activexobject before IE 5.5');

try {

req = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {}

}

}

////////////////// configure and get xmlhttprequest ///////////////////////////

try{// this try/catch is only for firefox: if you installed firebug,disable it.

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");

//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

}catch (e){}

// 2. request.open()

try{

//req.open("GET", "http://crosszheng.spaces.live.com/feed.rss", true);

req.open("GET", "feed.rss", true);

//alert('get successfully');

}

catch(e){

alert(e.toString());

}

// 3. define request.onreadystatechange function, which is a event handler.

req.onreadystatechange = function() {

try

{

if((req.readyState == 4) && (req.status == 200))

{

try{

xmlobject = (new DOMParser()).parseFromString(req.responseText, "text/xml");

}catch(e){

xmlobject=new ActiveXObject("Microsoft.XMLDOM");

xmlobject.async="false";

xmlobject.loadXML(req.responseText);

}

// get a reference to the root-element "rss"

var root = xmlobject.getElementsByTagName('rss')[0];

// get reference to "channel" element

var channels = root.getElementsByTagName("channel");

// now get all "item" tags in the channel

var items = channels[0].getElementsByTagName("item");

// in the "item" we have a description, so get that

var descriptions = items[0].getElementsByTagName("description");

var desc = descriptions[0].firstChild.nodeValue;

document.write(desc);

document.close();

}

}

catch(e){

alert(e.toString());

}

}

// 4. request.send(null)

req.send(null);

</script>

more details on:http://developer.apple.com/internet/webcontent/xmlhttpreq.html

document.write flush your page or can not append new contents

In JavaScript, howto on March 6, 2008 at 4:20 pm
Html actually is multithread.

Let’s talk about onclick and setTimeout in html code and javascript.

The function invoked by onclick of form button and setTimeout of javascript all start a new thread to do jobs. If you run command “document.write(SOMETHING)” in the function invoked by above two ways, the SOMETHING will flush your current page, then use SOMETHING to rewrite the page. Namely, this “document” are not the original “document”.

More details are on:
http://www.howtocreate.co.uk/tutorials/javascript/writing

javascript’s OO and function as object as well

In JavaScript, howto on March 5, 2008 at 7:51 pm

Functions stored in variables

Just
to make sure you’re completely clear on how all this works, make sure you fully
understand the difference between these two pieces of code:

function MyFunc() {
    alert('hi');
}

and, by comparison, this:

MyFunc2 = function() {
    alert('there');
}

The first of these creates a function called MyFunc. The second of these
creates a function, but doesn’t give it a name, and then stores the function in
the MyFunc2 variable. From there, you can call either using MyFunc() and
MyFunc2().

Next, think about how a function is, in fact, an object. Consider this code,
which uses the preceding MyFunc2 variable:

MyFunc3 = MyFunc2;
MyFunc3.somemember = 10;
alert(MyFunc3.somemember);

This first line of this code copies the value of MyFunc2 to MyFunc3. Since
the value of MyFunc2 is the unnamed function, the value of MyFunc3 is this same
function. The second line adds a new member to the function called somemember,
and sets its value to 10. Although I’m using the MyFunc3 variable to do this,
the two variables refer to the same function object. Thus, in the third line,
when I do an alert on the MyFunc3 value’s somemember, I’ll see the 10 that I
assigned. Thus, these two variables refer to the same single function object.
Changing one changes the “other”, since they’re both, in fact, the
same object.

Now let’s continue our discussion. Note: To create the examples for this
article, I used FireFox and the FireBug tool, simply because it’s easy to
quickly try out JavaScript code.

JavaScript and Prototypes

To fully understand the object
system, however, it’s important to understand the whole architecture behind it.
JavaScript uses an approach called a prototype architecture.

First, remember that JavaScript is
run line-by-line. Prior to the declaration of the Counter1 function above, the
function does not exist. Also remember that nearly everything in JavaScript is
an object. Thus, Counter1 is itself an object.

But what type are the objects stored
in my obj1 and obj2 variables? Their type is object and nothing more.
These objects are not instances of Counter1, although in our own minds
it’s okay to think of them as such. Counter1 is not a class; rather, it’s
simply a function that, when used in conjunction with the new keyword, creates
a new object.

If you want to give the members to
the objects created by the Counter1 function, you can do so inside the Counter1
function, as I did with this line:

this.value
= 0;

However, there’s another way to do
this. Objects in JavaScript can optionally include a member called prototype.
This member is itself an object, and as its name implies, it provides a
prototype for objects created based on the object.

That’s a mouthful, so let’s look at
an example. Consider the Counter1 function. When you created this function (via
the function keyword), you created a function object, which automatically came
with a member object called prototype. If you’re trying out the code in
FireBug, you can inspect this member. Try an alert:

alert(Counter1.prototype)

This will open an alert box
displaying the words [object Object], which simply means it’s an object.
Initially, this object doesn’t contain anything. But if you add members to this
object, the objects you create by calling new Counter1 will get copies of
these members
.

Let’s try another example with the
help of a new function called Counter2. Here’s the code:

function
Counter2() {

}

Not much there… yet. Follow with
this code:

Counter2.prototype.value
= 0;

Counter2.prototype.increment
= function() {

this.value++;

}

This adds two members to the
Counter2 function’s prototype object, one called value and one called increment.
When you create a new object using the new keyword and calling this Counter2
function, your new object will automatically inherit copies of the members of
this prototype. Try it out:

c1
= new Counter2();

c1.increment();

c1.increment();

alert(c1.value);

When the alert box opens, you’ll see
the value 2; thus, c1 has the value and increment members. In FireBug, you can
inspect the object using FireFox’s built in dir function:

&gt;&gt;&gt;
dir(c1)

value 2

increment function()

But now try inspecting the Counter2
function’s prototype object:

&gt;&gt;&gt;dir(Counter2.prototype)

value 0

increment function()

Prototypes are an important part of
JavaScript as they provide a handy means by which objects can be given members.
Remember, however, the prototype member is just an object itself, a member of
the Counter2 object.

javascript’s OO and function as object as well

In JavaScript, howto on March 5, 2008 at 7:51 pm

Functions stored in variables

Just
to make sure you’re completely clear on how all this works, make sure you fully
understand the difference between these two pieces of code:

function MyFunc() {
    alert('hi');
}

and, by comparison, this:

MyFunc2 = function() {
    alert('there');
}

The first of these creates a function called MyFunc. The second of these
creates a function, but doesn’t give it a name, and then stores the function in
the MyFunc2 variable. From there, you can call either using MyFunc() and
MyFunc2().

Next, think about how a function is, in fact, an object. Consider this code,
which uses the preceding MyFunc2 variable:

MyFunc3 = MyFunc2;
MyFunc3.somemember = 10;
alert(MyFunc3.somemember);

This first line of this code copies the value of MyFunc2 to MyFunc3. Since
the value of MyFunc2 is the unnamed function, the value of MyFunc3 is this same
function. The second line adds a new member to the function called somemember,
and sets its value to 10. Although I’m using the MyFunc3 variable to do this,
the two variables refer to the same function object. Thus, in the third line,
when I do an alert on the MyFunc3 value’s somemember, I’ll see the 10 that I
assigned. Thus, these two variables refer to the same single function object.
Changing one changes the “other”, since they’re both, in fact, the
same object.

Now let’s continue our discussion. Note: To create the examples for this
article, I used FireFox and the FireBug tool, simply because it’s easy to
quickly try out JavaScript code.

JavaScript and Prototypes

To fully understand the object
system, however, it’s important to understand the whole architecture behind it.
JavaScript uses an approach called a prototype architecture.

First, remember that JavaScript is
run line-by-line. Prior to the declaration of the Counter1 function above, the
function does not exist. Also remember that nearly everything in JavaScript is
an object. Thus, Counter1 is itself an object.

But what type are the objects stored
in my obj1 and obj2 variables? Their type is object and nothing more.
These objects are not instances of Counter1, although in our own minds
it’s okay to think of them as such. Counter1 is not a class; rather, it’s
simply a function that, when used in conjunction with the new keyword, creates
a new object.

If you want to give the members to
the objects created by the Counter1 function, you can do so inside the Counter1
function, as I did with this line:

this.value
= 0;

However, there’s another way to do
this. Objects in JavaScript can optionally include a member called prototype.
This member is itself an object, and as its name implies, it provides a
prototype for objects created based on the object.

That’s a mouthful, so let’s look at
an example. Consider the Counter1 function. When you created this function (via
the function keyword), you created a function object, which automatically came
with a member object called prototype. If you’re trying out the code in
FireBug, you can inspect this member. Try an alert:

alert(Counter1.prototype)

This will open an alert box
displaying the words [object Object], which simply means it’s an object.
Initially, this object doesn’t contain anything. But if you add members to this
object, the objects you create by calling new Counter1 will get copies of
these members
.

Let’s try another example with the
help of a new function called Counter2. Here’s the code:

function
Counter2() {

}

Not much there… yet. Follow with
this code:

Counter2.prototype.value
= 0;

Counter2.prototype.increment
= function() {

this.value++;

}

This adds two members to the
Counter2 function’s prototype object, one called value and one called increment.
When you create a new object using the new keyword and calling this Counter2
function, your new object will automatically inherit copies of the members of
this prototype. Try it out:

c1
= new Counter2();

c1.increment();

c1.increment();

alert(c1.value);

When the alert box opens, you’ll see
the value 2; thus, c1 has the value and increment members. In FireBug, you can
inspect the object using FireFox’s built in dir function:

&gt;&gt;&gt;
dir(c1)

value 2

increment function()

But now try inspecting the Counter2
function’s prototype object:

&gt;&gt;&gt;dir(Counter2.prototype)

value 0

increment function()

Prototypes are an important part of
JavaScript as they provide a handy means by which objects can be given members.
Remember, however, the prototype member is just an object itself, a member of
the Counter2 object.

javascript’s OO and function as object as well

In JavaScript, howto on March 5, 2008 at 7:51 pm

Functions stored in variables

Just
to make sure you’re completely clear on how all this works, make sure you fully
understand the difference between these two pieces of code:

function MyFunc() {
    alert('hi');
}

and, by comparison, this:

MyFunc2 = function() {
    alert('there');
}

The first of these creates a function called MyFunc. The second of these
creates a function, but doesn’t give it a name, and then stores the function in
the MyFunc2 variable. From there, you can call either using MyFunc() and
MyFunc2().

Next, think about how a function is, in fact, an object. Consider this code,
which uses the preceding MyFunc2 variable:

MyFunc3 = MyFunc2;
MyFunc3.somemember = 10;
alert(MyFunc3.somemember);

This first line of this code copies the value of MyFunc2 to MyFunc3. Since
the value of MyFunc2 is the unnamed function, the value of MyFunc3 is this same
function. The second line adds a new member to the function called somemember,
and sets its value to 10. Although I’m using the MyFunc3 variable to do this,
the two variables refer to the same function object. Thus, in the third line,
when I do an alert on the MyFunc3 value’s somemember, I’ll see the 10 that I
assigned. Thus, these two variables refer to the same single function object.
Changing one changes the “other”, since they’re both, in fact, the
same object.

Now let’s continue our discussion. Note: To create the examples for this
article, I used FireFox and the FireBug tool, simply because it’s easy to
quickly try out JavaScript code.

JavaScript and Prototypes

To fully understand the object
system, however, it’s important to understand the whole architecture behind it.
JavaScript uses an approach called a prototype architecture.

First, remember that JavaScript is
run line-by-line. Prior to the declaration of the Counter1 function above, the
function does not exist. Also remember that nearly everything in JavaScript is
an object. Thus, Counter1 is itself an object.

But what type are the objects stored
in my obj1 and obj2 variables? Their type is object and nothing more.
These objects are not instances of Counter1, although in our own minds
it’s okay to think of them as such. Counter1 is not a class; rather, it’s
simply a function that, when used in conjunction with the new keyword, creates
a new object.

If you want to give the members to
the objects created by the Counter1 function, you can do so inside the Counter1
function, as I did with this line:

this.value
= 0;

However, there’s another way to do
this. Objects in JavaScript can optionally include a member called prototype.
This member is itself an object, and as its name implies, it provides a
prototype for objects created based on the object.

That’s a mouthful, so let’s look at
an example. Consider the Counter1 function. When you created this function (via
the function keyword), you created a function object, which automatically came
with a member object called prototype. If you’re trying out the code in
FireBug, you can inspect this member. Try an alert:

alert(Counter1.prototype)

This will open an alert box
displaying the words [object Object], which simply means it’s an object.
Initially, this object doesn’t contain anything. But if you add members to this
object, the objects you create by calling new Counter1 will get copies of
these members
.

Let’s try another example with the
help of a new function called Counter2. Here’s the code:

function
Counter2() {

}

Not much there… yet. Follow with
this code:

Counter2.prototype.value
= 0;

Counter2.prototype.increment
= function() {

this.value++;

}

This adds two members to the
Counter2 function’s prototype object, one called value and one called increment.
When you create a new object using the new keyword and calling this Counter2
function, your new object will automatically inherit copies of the members of
this prototype. Try it out:

c1
= new Counter2();

c1.increment();

c1.increment();

alert(c1.value);

When the alert box opens, you’ll see
the value 2; thus, c1 has the value and increment members. In FireBug, you can
inspect the object using FireFox’s built in dir function:

&gt;&gt;&gt;
dir(c1)

value 2

increment function()

But now try inspecting the Counter2
function’s prototype object:

&gt;&gt;&gt;dir(Counter2.prototype)

value 0

increment function()

Prototypes are an important part of
JavaScript as they provide a handy means by which objects can be given members.
Remember, however, the prototype member is just an object itself, a member of
the Counter2 object.

java applet <> javascript

In JavaScript, howto, java on March 5, 2008 at 12:39 pm

1. javascript call java applet: http://www.rgagnon.com/javadetails/java-0170.html

* make the variable you want to call public in the applet.
* in javascript just: document.myapplet.myfunction(some parametres);

2.1 java applet call variable or function defined in javascript:

* You can try an easy method, by calling a specially crafted URL using the showDocument() method, like this :
getAppletContext().showDocument(new URL(“javascript:alert(Hello World);));
This doesn’t work anymore using Internet Explorer as of a certain IE update from Microsoft dated some time ago this year, so it is easily broken.

* You can use the LiveConnect objects that are implemented in IE on Windows, Mozilla/Firefox on anything, Safari on Mac, etc.. it works almost everywhere.
For this you have to declare that your applet MAYSCRIPT, by adding a special parameter in the OBJECT/EMBED tag in your web page. (google for it if you need examples).
Then you have to add the “jaws.jar” (or “plugin.jar” if there’s no jaws.jar) from the lib of the JRE to compile your Applet.
This jar should include the LiveConnext classes, and netscape.javascript.JSObject is the one you need.
Then You can then do something like this to achieve the same as solution one above :
JSObject browserWindow = JSObject.getWindow(this); //here ‘this’ is the JApplet
browserWindow.eval(buffer.toString());
Or you can navigate the DOM javascript tree of the WebPage using the methods of JSObject. (google for it if you need more info).

2.2 java applet call variable defined in html:
Just use the parametre of applet, for example:

java applet <> javascript

In JavaScript, howto, java on March 5, 2008 at 12:39 pm

1. javascript call java applet: http://www.rgagnon.com/javadetails/java-0170.html

* make the variable you want to call public in the applet.
* in javascript just: document.myapplet.myfunction(some parametres);

2.1 java applet call variable or function defined in javascript:

* You can try an easy method, by calling a specially crafted URL using the showDocument() method, like this :
getAppletContext().showDocument(new URL(“javascript:alert(Hello World);));
This doesn’t work anymore using Internet Explorer as of a certain IE update from Microsoft dated some time ago this year, so it is easily broken.

* You can use the LiveConnect objects that are implemented in IE on Windows, Mozilla/Firefox on anything, Safari on Mac, etc.. it works almost everywhere.
For this you have to declare that your applet MAYSCRIPT, by adding a special parameter in the OBJECT/EMBED tag in your web page. (google for it if you need examples).
Then you have to add the “jaws.jar” (or “plugin.jar” if there’s no jaws.jar) from the lib of the JRE to compile your Applet.
This jar should include the LiveConnext classes, and netscape.javascript.JSObject is the one you need.
Then You can then do something like this to achieve the same as solution one above :
JSObject browserWindow = JSObject.getWindow(this); //here ‘this’ is the JApplet
browserWindow.eval(buffer.toString());
Or you can navigate the DOM javascript tree of the WebPage using the methods of JSObject. (google for it if you need more info).

2.2 java applet call variable defined in html:
Just use the parametre of applet, for example:

shell history

In howto, linux on March 4, 2008 at 2:48 pm
For bash:

ctrl + r: will prompt you corresponding history when you type.

simplest way to config java security policy

In howto, java on March 4, 2008 at 2:06 am
In my case, on xp, these security policy files are stored here:
C:\Program Files\Java\jre1.6.0_04\lib\security

So, when applet need to access local or remote file, the “java.policy” should be modified.

Eclipse will generate a very dangerous java.policy.applet by default for testing, you can copy the setting permission line in to java.policy, in this case, your applet can reading files. But it’s dangerous.

My way is to put such code in the java.policy. where the path is the place where my applet class file exists.

grant codeBase “file:///D:/My%20Documents/workspace/2008.3.applet/bin/” {
permission java.security.AllPermission;
};

simplest way to config java security policy

In howto, java on March 4, 2008 at 2:06 am
In my case, on xp, these security policy files are stored here:
C:\Program Files\Java\jre1.6.0_04\lib\security

So, when applet need to access local or remote file, the “java.policy” should be modified.

Eclipse will generate a very dangerous java.policy.applet by default for testing, you can copy the setting permission line in to java.policy, in this case, your applet can reading files. But it’s dangerous.

My way is to put such code in the java.policy. where the path is the place where my applet class file exists.

grant codeBase “file:///D:/My%20Documents/workspace/2008.3.applet/bin/” {
permission java.security.AllPermission;
};

open file dialog by click

In JavaScript, howto on March 3, 2008 at 9:14 pm

open file dialog by click

In JavaScript, howto on March 3, 2008 at 9:14 pm

css for rss, that I always use

In howto, xml on March 2, 2008 at 11:58 pm
put this command in rss/xml file:
&lt;?xml-stylesheet href=”rss.css” type=”text/css”?&gt;
======================

rss
{
margin:10px;
}

channel
{
display:block;
border:solid 1px #000;
overflow:auto;
height:300px;
width:280px;
background-color:#eee;
font: 12px verdana;
}

item
{
display: block;
//padding:10px;
background-color:#fff;
}

item&gt;link
{
display:none;
}

channel&gt;title, item&gt;title
{
font:12px arial;
font-weight:bold;
font-size: 24px;
}

channel&gt;title, channel&gt;description, item&gt;title
{
display: block;
}

css for rss, that I always use

In howto, xml on March 2, 2008 at 11:58 pm
put this command in rss/xml file:
&lt;?xml-stylesheet href=”rss.css” type=”text/css”?&gt;
======================

rss
{
margin:10px;
}

channel
{
display:block;
border:solid 1px #000;
overflow:auto;
height:300px;
width:280px;
background-color:#eee;
font: 12px verdana;
}

item
{
display: block;
//padding:10px;
background-color:#fff;
}

item&gt;link
{
display:none;
}

channel&gt;title, item&gt;title
{
font:12px arial;
font-weight:bold;
font-size: 24px;
}

channel&gt;title, channel&gt;description, item&gt;title
{
display: block;
}

java copy file

In howto, java on March 2, 2008 at 12:03 pm

[Old technique (pre JDK1.4)]

import java.io.*;

public class FileUtils{ public static void copyFile(File in, File out) throws Exception {   FileInputStream fis  = new FileInputStream(in);   FileOutputStream fos = new FileOutputStream(out);   try {       byte[] buf = new byte[1024];       int i = 0;       while ((i = fis.read(buf)) != -1) {           fos.write(buf, 0, i);       }   }   catch (Exception e) {       throw e;   }   finally {       if (fis != null) fis.close();       if (fos != null) fos.close();   } }

 public static void main(String args[]) throws Exception{   FileUtils.copyFile(new File(args[0]),new File(args[1])); }}

[JDK1.4 using the java.nio package (faster)]

import java.io.*;import java.nio.channels.*;

public class FileUtils{   public static void copyFile(File in, File out)       throws IOException   {       FileChannel inChannel = new           FileInputStream(in).getChannel();       FileChannel outChannel = new           FileOutputStream(out).getChannel();       try {           inChannel.transferTo(0, inChannel.size(),                   outChannel);       }       catch (IOException e) {           throw e;       }       finally {           if (inChannel != null) inChannel.close();           if (outChannel != null) outChannel.close();       }   }

   public static void main(String args[]) throws IOException{       FileUtils.copyFile(new File(args[0]),new File(args[1])); }}

NOTE:
In win2000 , the transferTo() does not transfer files > than 2^31-1 bytes. it throws an exception of “java.io.IOException: The parameter is incorrect”
In solaris8 , Bytes transfered to Target channel are 2^31-1 even if the source channel file is greater than 2^31-1
In LinuxRH7.1 , it gives an error of java.io.IOException: Input/output error

more details are on:http://www.rgagnon.com/javadetails/java-0064.html

make your website rss activated

In howto, xml on February 29, 2008 at 2:36 pm
To use such a tag in your html:

&lt;LINK REL=”alternate” TITLE=”Shared RSS” href=”http://www…..rss” TYPE=”application/rss+xml”&gt;


HTML &lt;link&gt; tag


Definition and Usage

This element defines the relationship between two linked documents.

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

make your website rss activated

In howto, xml on February 29, 2008 at 2:36 pm
To use such a tag in your html:

&lt;LINK REL=”alternate” TITLE=”Shared RSS” href=”http://www…..rss” TYPE=”application/rss+xml”&gt;


HTML &lt;link&gt; 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

In howto, java on February 29, 2008 at 1:53 pm
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();
}

}

}

java download file program

In howto, java on February 29, 2008 at 1:53 pm
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

In howto, xml on February 29, 2008 at 1:45 pm
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 &lt;rss&gt;……&lt;/rss&gt;
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&lt;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
}

Rss server generate whole rss feed from separate rss files

In howto, xml on February 29, 2008 at 1:45 pm
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 &lt;rss&gt;……&lt;/rss&gt;
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&lt;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
}

java文件操作

In howto, java on February 28, 2008 at 3:06 am

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

In howto, xml on February 28, 2008 at 2:56 am
Following codes are a kind of INTERNAL SUBSET DTD style <

< !DOCTYPE people_list[

]>

Fred Bloggs
27/11/2008
Male

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

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

1. xml file:

Fred Bloggs
27/11/2008
Male

2. dtd file:

about mount

In howto, linux on February 26, 2008 at 7:28 pm
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.

about mount

In howto, linux on February 26, 2008 at 7:28 pm
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

In howto, linux on February 26, 2008 at 6:55 pm

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

In howto, linux on February 26, 2008 at 2:13 pm
  • 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.

AddSwapPartition in colinux

In howto, linux on February 26, 2008 at 2:13 pm
  • 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.

java dialog: simplest prompt

In howto, java on February 25, 2008 at 1:35 pm

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

System.out.println(temp);

java dialog: simplest prompt

In howto, java on February 25, 2008 at 1:35 pm

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

System.out.println(temp);

linux command: dd

In howto, linux on February 25, 2008 at 1:27 pm

虚拟机技术 – 把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个步骤。

linux command: dd

In howto, linux on February 25, 2008 at 1:27 pm

虚拟机技术 – 把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个步骤

  • 生成虚拟块设备文件。主要使用dd命令。
  • 在虚拟块设备文件上创建文件系统。主要使用mkfs等工具。
  • 挂接虚拟块设备文件。主要使用mount命令。
  • 安装Linux到虚拟块设备文件。针对不同的Linux发型版,可以使用debootstrap和cdebbootstrap,rpmstrap
  • 善后工作

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

xming address setup

In howto, linux on February 24, 2008 at 1:27 am

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.

xming address setup

In howto, linux on February 24, 2008 at 1:27 am

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.

two ways to synchronized in Java

In howto, java on February 21, 2008 at 5:26 pm

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

In howto, java on February 21, 2008 at 3:19 pm

具体到应用比较复杂,举两个例子:
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用法

In howto, java on February 21, 2008 at 3:18 pm
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()――这样,调用端得到的就是对象副
本的引用了。

java中synchronized用法

In howto, java on February 21, 2008 at 3:18 pm
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()――这样,调用端得到的就是对象副
本的引用了。

turn off Vista index search

In Windows, howto on February 19, 2008 at 5:30 pm

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.

keybinding = shortcut in Ubuntu

In howto, linux on February 18, 2008 at 2:27 pm

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.

keybinding = shortcut in Ubuntu

In howto, linux on February 18, 2008 at 2:27 pm

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.

Get Ip address in Java

In howto, java on February 15, 2008 at 12:45 pm
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

Get Ip address in Java

In howto, java on February 15, 2008 at 12:45 pm
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

Get Ip address in Java

In howto, java on February 15, 2008 at 12:45 pm
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

Java Ubuntu alternative option

In howto, java, linux on February 14, 2008 at 12:22 pm

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.

Java Ubuntu alternative option

In howto, java, linux on February 14, 2008 at 12:22 pm

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.

java variable to be initialized to null

In howto, java on February 13, 2008 at 2:00 pm
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:

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.

java variable to be initialized to null

In howto, java on February 13, 2008 at 2:00 pm
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:

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.

python run system command: os.exec…..

In howto, python on February 12, 2008 at 2:05 pm

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.

python change working directory

In howto, python on February 9, 2008 at 11:36 am
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.

python change working directory

In howto, python on February 9, 2008 at 11:36 am
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

In howto, linux on February 9, 2008 at 11:31 am
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.

Bash Programming Cheat Sheet

In howto, linux on February 9, 2008 at 11:31 am
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.

Tkinter layout/alignment control

In howto, python on February 8, 2008 at 5:39 pm
The following example uses packer management for the Tkinter layout.

Reference: http://docs.python.org/lib/node695.html

from Tkinter import *

root=Tk()

b3=Button(root, text=’click me!!’)
b3.pack(padx=10,pady=5)

b1=Button(root, text=’click me’,padx=10,pady=5)
b1.pack(side = “left”)

b2=Button(root, text=’click me’,padx=10,pady=5)
b2.pack(side = ‘right’,expand = 1)

b4=Button(root, text=’click me’,padx=10,pady=5)
b4.pack()

root.mainloop()

Powered by ScribeFire.

VMware command

In howto, vmware on February 5, 2008 at 5:32 pm

For VMware server, a free version of VMware family. It can run as a server, on which most of the OS can run well.

P.S.:
1. Preconfigure is essential, especially, VMware server is updated, you should run [vmware-config.pl] to reconfigure it.
2. Using vmware-cmd, you must provide the full path.

Now here is how it works.
1. With SSH, user can connect to that server.
2. vmware-cmd /the/full/path/of/vmx getstate
vmware-cmd /the/full/path/of/vmx start
When you first time run this command with such option- start, it will prompt you with such an error:
VMControl error -16: Virtual machine requires user input to continue.
To solve it, run this command to input your option:
vmware-cmd /the/full/path/of/vmx answer

vmware-cmd /the/full/path/of/vmx stop

vi configuration

In howto, linux on February 4, 2008 at 2:45 pm

~/.vimrc
is the place to store vi start options.

put such command in it:
syn on

This is used to turn on Syntax function, namely syntax color highlight.

vi shortcuts: autocomplete

In howto, linux on February 4, 2008 at 12:04 am

Topics on this page in alphabetic order


Why use vi?

When I first tried using vi I thought that you could not have a more obscure and difficult-to-use text editor, but I found that after memorising half-a-dozen commands that it was really quite simple to use. And, quite powerful. For example, you can do something like “find all lines with ’swordfish’ in them, and for those lines only, change ‘cat’ to ‘dog’”. Try doing that with your normal editor!

The other reason is you can usually find vi on almost any Unix installation. If you get used to “my favourite editor” – whatever that is – and connect to a different site for troubleshooting, you may well find it is not installed, or only runs under Xwindows, or some other such restriction.

Further, you can do quite fancy things (see below) like do a “make” from inside vi, and then with a single keystroke go to each error message (even in different files), with the cursor being placed on the line in error, so you can fix it. This is quite a time-saver. Similarly with doing “grep” on a group of files.


The basics

If you start doing something and change your mind you can generally press Ctrl+C to cancel it.

Edit a file, look at it, stop editing

Edit a file from command prompt vi
Edit a file from command prompt for reading only vi -R
Edit a file from within vi :e
Edit a new file from within vi, discard changes to current file :e!
Reload current file, discarding changes :e!
Go forwards a page Ctrl+F (or PgDn)
Go backwards a page Ctrl+B (or PgUp)
Move around single lines or characters Arrow keys
Save changes :w
Save changes and override protected (read-only) files :w!
Save changes and exit vi ZZ
Quit :q
Quit and discard changes :q!
Get general help :help
Get help on a command (eg. :set) :help set

Notes

  1. Whether keys like PgUp and PgDn work will depend on your keymappings. I find recently that they tend to work without needing to make any changes. In some cases you may need to type “vim (file)” at the command prompt rather than “vi (file)” if both are installed. Otherwise you may set up an alias (at your shell prompt) to equate vi to vim.
  2. Any command starting with these characters:
    • : (colon) – starts a command sequence
    • / (slash) – starts a forwards search
    • ? (question mark) – starts a backwards search

    needs you to press to execute them. Until you have done that you can backspace and make corrections.

    These commands are echoed on the bottom line of the screen, so you can see what you are typing. If you have started typing one of those, you see the command being echoed, and change your mind, press Ctrl+C to cancel the command.

Simple example

Let’s edit comm.c and then exit …

vi -R comm.c(PgDn to look at file):q

If you are experimenting then it might be wise to either edit a file you don’t care about (eg. a copy) or use the -R option (read-only).

Alternatively, set read-only mode once you have edited the file:

Set read-only mode :set ro

Go to lines, find matching text

Go to line 1234 (do not see typing) 1234G
Go to line 1234 (see typing) :1234
Go to start of file 1G
Go to end of file G
Find (forwards) a line containing “swordfish” /swordfish
Find (forwards) a line using a regular expression /you see .* here
Repeat last search n
Repeat last search in opposite direction N
Find (backwards) a line containing “swordfish” ?swordfish
Find (backwards) a line using a regular expression ?you see .* here
Search case insensitive (Ignore Case) :set ic
Search with case sensitivity :set noic
Wrap searches back to start of file :set wrapscan
Do not wrap searches :set nowrapscan

Notes – these are probably the most frequent things I do. ‘Go to line number’, especially if you have a compiler error which gives a line number is very handy. Type the line number directly followed by “G”, and you are taken there. Or, if you don’t know the line, type “/” followed by a word or regular expression you are looking for. The second way of going to a line number (:1234) is probably easier to use because you can see the number as you type it. If you type “1234G” the number (1234) is not echoed to the screen as you type.

Highlighting – searching with “/” or “?” normally highlights the found word. Sometimes this can be quite annoying, especially if you have searched for something which occurs frequently, like a space. You can turn this off:

:hi clear search

Case-sensitivity – using “:set ic” lets you search with or without matching the exact case of the word you are searching for (eg. if you search for “dog” do you want to match “DOG”?).

Simple example

Let’s edit comm.c and go to line 5522. Then find “const”.

vi comm.c:5522/const:q

Line numbers

Sometimes it is handy to know what line you are at, or what each line number is.

Show line numbers on the left :set nu
Do not show line numbers on the left :set nonu
Show the current line number :.=
Show total lines in file :=
Show file name, total lines, and current line number Ctrl+G
Show line number of first matching pattern :/pattern/=

Notes – showing lines numbers is particularly useful when you are relating things like error messages (or instructions) to a line number. Also the Ctrl+G trick is useful to remind yourself of what file you are editing.

Simple example

Let’s edit comm.c, show line numbers, find the first line with “const” in it (line 70) and go to it:

vi comm.c:set nu:/const/=:70:q

Changing text

OK, we can move around the file and find things. Let’s start changing stuff …

Undoing things

When you start going into “change things” mode you will probably need to undo your mistakes. Two useful commands:

Undo last change u
Undo all changes on current line U

If things get out of hand, remember:

Quit editor without saving changes :q!
Reload current file, discarding changes :e!

Insert text

All of the changing commands (except “replace next character”) go into “insert mode” (usually shown by “– INSERT –” or “– REPLACE –” at the bottom of the screen). To exit from Insert Mode, press the Esc key.

Insert after cursor i
Insert before cursor a
Insert at beginning of line I
Insert at end of line (append) A
Open (start) new line below cursor o
Open (start) new line above cursor O

The last two are the letter “oh” not a zero. I use the “O” and “o” commands quite a bit to start entering a new line above or below where the cursor currently is.

Change existing text

Replace next character r
Type over following characters R
Replace to end of line C

Note – the “r” command is useful if you just want to make a minor correction (eg. change “A” to “B”). This does not go into Insert Mode, so you don’t need to then cancel Insert Mode. To change the character under the cursor to a “B” you would just type “rB”.

Delete text

Delete character under cursor x
Delete character to left of cursor X
Delete to end of line D
Delete entire line dd

These are your basic deletion commands. “x” to scrub out the character under the cursor, “dd” to delete the entire line.

Advanced deletion

Delete next 5 lines 5dd
Delete to end of line d$
Delete to start of line d0
Delete to word “swordfish” d/swordfish
Delete to the letter “x” dfx
Delete lines 10 to 20 :10,20d
Delete current line and another 5 lines :.,+5d
Delete all lines :%d
Delete current word dw
Find line containing pattern, delete it :/pattern/d
Find line containing “dog”, delete until line containing “cat” :/dog/,/cat/d
Delete from current line to line containing “foo” :.,/foo/d

Copying, cutting and pasting

If you delete some text using the deletion commands described above you have “cut” the text. However it is saved in an internal buffer and can be pasted somewhere else. Simply move the cursor to where you want it and:

Paste after cursor p
Paste before cursor P

vi calls copying “yanking”, and thus uses the letter Y.

To copy text without deleting it you need to “yank” it. The yank commands are similar to the deletion commands, like this:

Yank to end of line y$
Yank to start of line y0
Yank to word “swordfish” y/swordfish
Yank to letter “g” yfg
Yank entire line Y
Yank lines 5 to 10 5,10y

After yanking you can paste as described above (or there is no point to yanking in the first place).


Advanced movement commands

Go forwards a word w
Go backwards a word b
Go to end of word e
Go to start of line 0
Go to end of line $
Go to top of screen H
Go to middle of screen M
Go to bottom of screen L
Go (forwards) to letter “x” on current line fx
Go (backwards) to letter “x” on current line Fx
Go to next occurrence of word under cursor *
Go to previous occurrence of word under cursor #
Find a control character (eg. Tab) /(Ctrl+V)(Tab)
Go backwards a sentence (
Go forwards a sentence )
Go backwards a paragraph {
Go forwards a paragraph }

The command “go to start of line” is a zero, not an “oh”. You can use Ctrl+V in insert or command mode to literally insert the next character.


Repeat counts

Most commands have a “repeat count” that you can optionally type first. To do a repeat count just type the number before the command. It will not be echoed, so type carefully!

For example:

Delete 5 lines 5dd
Delete 5 characters 5x
Delete 5 words 5dw
Replace next 5 characters 5r
Yank (copy) next 7 lines 7Y
Go to line 1000 1000G
Paste copy buffer 10 times 10p
Insert 40 hyphens 40i-
Insert the line “swordfish” 10 times 10oswordfish
Find the 5th occurrence of “swordfish” 5/swordfish

In the above examples means press the Esc key.


Splitting and joining lines

Split a line (insert a return) i
Join two lines (current and next) J
Join next 10 lines 10J
Join lines 10 to 20 :10,20j

Splitting is basically breaking a line into two by inserting a newline. Joining is reversing that process by removing the newline.


Search and replace

Change “nick” to “fred” on current line :s/nick/fred/
Change “nick” to “fred” on the next 5 lines :.,+4 s/nick/fred/
Change “nick” to “fred” on lines 100 to 200, all occurrences :100,200 s/nick/fred/g
Capitalise every word in the entire file :% s/\<./\u&/g
Insert “>” at the start of every line :% s/^/>/
Insert “// nick” at the end of every line :% s;$;// nick;

Special characters for line sequences:

  • . is the current line
  • $ is the last line
  • % is every line
  • +5 means 5 lines from current line
  • -5 means 5 lines before current line

Applying commands to certain lines

You can use the “:g” (global) command to find matching lines (using a regular expression) and then apply a command to those lines. For example:

Find lines containing “fruit” and change “apple” to “orange” on them :g/fruit/s/apple/orange/g
Delete all blank lines :g/^$/d
Find lines NOT containing “nick”, append “oops” to them :g! /nick/normal A oops

The third example above shows you you can use the “normal” command inside a command, to tell vi to use a normal character (in this case A for append) as part of a command.


Shell and filter commands

List directory :! ls
See processes :! ps
Sort lines 20 to 30 :20,30 ! sort
Sort entire file !G sort
Translate next sentence to upper case !) tr '[a-z]' '[A-Z]'
Word count file (save first) :!wc %
Look up manual entry for strstr :!man strstr
Insert “ls” command output into window :r !ls

Tags

Tags let you go to the definition of a function (in C or C++) without having to scan lots of source files (with grep) and work out which ones contain the function and which merely refer to it.

First, make a tag file, like this:

ctags *.c *.cpp *.h

(In recent versions of Linux I have had to use gctags instead of ctags).

This should produce a file “tags” in the current directory.

Now you can go straight to a function, without knowing which file it is in, like this:

vi -t game_loop

Once inside vi you can put the cursor on a word and go to its definition:

Go to function under cursor Ctrl+]
Go back Ctrl+T
Go to function xyz :tag xyz

Automating things

Compiling from within vi and going to errors

You can save your changes, run “make” to compile, and view errors, very easily …

Save file :w
Run “make” :make
Go to next error :cn
Go to previous error :cp

This is fabulously powerful. It lets you skim through all your errors, with vi opening the right file and positioning the cursor on the line in error.

See below for how to map actions (like “:cn”) to function keys to speed up the process.

Mapping actions to function keys

Map the action :cnext to :map :cnext
Map the action :cprevious to :map :cprevious
Map the action :make to :map :make
Map the action :close to :map :close

After entering the above commands you could compile by simply hitting F8, then look at each error by hitting F6.


More useful tips for programmers

Go to definition of word under cursor gd
Go to global definition gD
Find matching bracket, brace, #if, #endif %
Do a grep :grep foo *.c
After grep, go to next occurrence :cn
Get a file (eg. an #include file) whose name is under cursor gf
Auto complete (in insert mode) – match forwards Ctrl+X Ctrl+N
Auto complete (in insert mode) – match previous Ctrl+X Ctrl+P
Make an abbreviation (eg. cca = “const char *”) :ab cca const char *
Turn syntax colouring on :syntax on
Turn syntax colouring off :syntax off
Execute any shell command :! command
Indent selected lines with C-style indenting =

For formatting of C code there are also other options you can use like “autoindent”, “smartindent”, “cindent”, and “indentexpr”. (Use :help (topic) to see more about those options). You can turn these on (eg. :set cindent) to automatically indent your coding as you type. Also, in conjunction with syntax colouring, you can see if you have made a syntax error (eg. not closed a quote, left off a bracket), as the syntax colouring algorithm will highlight in red sequences that do not seem correct.


Spellcheck file

Save file first :w!
Spell check it :! ispell %
Edit fixed file :e %

Tab management

Tabs can be annoying in source files, as they do not necessarily line up when you use different value tab stops. You can manage them in vi like this:

Set tabs to every 4 characters :set ts=4
Convert tabs to spaces in future :set et
Do not expand tabs :set noet
Fix existing tabs (convert to spaces) :%retab
Show tabs visually, and end-of-lines :set list
Do not show tabs and end-of-lines :set nolist

Visual mode

vi can be a bit difficult to follow when you are trying to do something to a block of lines (for example, do I want line 8843 through to 8903 or 8904?), so vim has a “visual mode” where you can actually see lines highlighted in inverse.

First, “mark” a block of lines (or characters) by going to the start of the block, and then using one of the following:

Character mode v
Line mode V
Block mode Ctrl+V
Re-mark previous block gv

The differences are:

  • Character mode – from somewhere inside one line to somewhere inside another (ie. can be a part line)
  • Line mode – will be whole lines
  • Block mode – from (say) column 5 at line 10, to column 60 in line 20 (a square block of text)

Then use the cursor movement commands (search, arrow, go to line, whatever) to mark the other end of the block, and either:

Do some command (see below)
Cancel visual mode Esc
Go to other end of block o

Other ways of establishing a visual block

A word (with white space) vaw
Inner word viw
A WORD (with white space) vaW
Inner WORD viW
A sentence (with white space) vas
Inner sentence vis
A paragraph (with white space) vap
Inner paragraph vip
A ( … ) block (includes brackets) vab
Inner ( … ) block vib
A { … } block (includes braces) vaB
Inner { … } block viB

A “word” is a sequence of letters, numbers, underscores. A “WORD” is a sequence that is terminated by spaces. The difference would apply in cases like a(b) – if the cursor is on “a” a “word” is “a” however a “WORD” is “a(b)”.

Here is an example, from C source code. Say you have the following code, and you want to select the code inside the inner { … } characters. Put the cursor in the middle (eg. on CON_EDITING) and type “viB” and the “inner block” (text in bold) will be highlighted.

if ( d->pagepoint ){if ( !pager_output(d) ){ if ( d->character && ( d->connected == CON_PLAYING ||   d->connected == CON_EDITING ) )     save_char_obj( d->character ); d->outtop = 0; close_socket(d, FALSE);}}

Here is another method of selecting a visual block of C code. Say we have the following code and we want to highlight everything inside the “while” loop. Put the cursor on the first “{” and type “v%”. That will go into visual mode and move to the end of the block. The highlighted code will be in bold.

while ( usecDelta >= 1000000 ){ usecDelta -= 1000000; secDelta  += 1;}

Visual mode commands

See below for meanings of notes in brackets.

Switch case ~
Delete d
Change (4) c
Yank y
Shift right (4) >
Shift left (4) <
Filter through external command (1) !
Filter through ‘equalprg’ option command (1) =
Format lines to ‘textwidth’ length (1) gq

You can also do the following on the selected block:

Start ex command for highlighted lines (1) :
Change (4) r
Change s
Change (2)(4) C
Change (2) S
Change (2) R
Delete x
Delete (3) D
Delete (2) X
Yank (2) Y
Join (1) J
Make uppercase U
Make lowercase u
Find tag Ctrl+]
Block insert I
Block append A

Notes

  1. Always whole lines
  2. Whole lines when not using CTRL-V.
  3. Whole lines when not using CTRL-V, delete until the end of the line when using CTRL-V.
  4. When using CTRL-V operates on the block only.

An example of visual mode?

OK, let’s say we have a visual block highlighted. Try these:

Delete it d
Copy it Y
Change “apple” to “orange” in the block :s/apple/orange/g
Turn into C++ comments :s.^.//.
Turn into C comments :s-^.*$-/* & */-

Marking your work

If you need to jump backwards and forwards between a couple of places you can “mark” them …

Mark current position as “x” mx
Go to position “x” `x
Show list of known marks :marks

That character before the “x” is a back-quote – on my keyboard on the top-left corner, under the tilde (~) symbol. Marks can be in a different file to the current one.


Recording commands

Finally, let’s do an example of recording commands for repeating later.

Record a sequence q(letter)(commands)q
Play back sequence @(letter)
See what is in registers :reg

You record a sequence into a lower-case register (a-z), eg.

qa:s/fish/chips/q

The command above (starting and ending with “q”) records into register “a” the sequence “:s/fish/chips/”.

Then whenever you want to repeat that command you can type “@a”.

Example of recording

Whilst writing this page I wanted to convert every second sequence of:

(something)

to:

(something)

Doing a “find and replace” would have been tedious, as I would have had to skip every second item found. I was able to do it quite quickly by recording a macro. To do this I typed:

qa2/:s///:s$$$$q

The sequence above did the following:

  1. Start recording (q) under register “a”
  2. Search for the second occurence of (hence the leading “2″ on the line)
  3. Change “” to “"
  4. On the same line change “” to “
  5. “. I used a $ as the search delimiter because the character “/” was in the text to be searched for.

  6. Go to the end of the current line ($) so the next search would begin at the next
  7. Stop recording (q)

Then I moved to the start of the file (1G), turned search wrapping off (:set nowrapscan) and typed “999@a”. This executed macro “a” 999 times. In fact, it stopped before 999 times because the search failed after it got to the end of file.


Setting up your personal favourite settings

If you have some personal favourite settings like:

  • Spaces for tabs
  • Whether searches are highlighted or not
  • Syntax colouring on or off
  • Mapping function keys to special functions

you can have them processed automatically by putting them into a file named “.vimrc” in your home directory (see “:help vimrc” inside vim for more details).

For example, your .vimrc file might have in it:

set ts=4   " tab stops every 4 charactersset expandtab  " tabs to spaces

map  :cnext   " next error after a make or grepmap  :cprevious " previous errormap  :close    " close current window (eg. help)

syntax on  " syntax colouring on

hi clear search  " do not highlight searched-for words 

From: http://www.gammon.com.au/smaug/vi.htm

vi shortcuts: autocomplete

In howto, linux on February 4, 2008 at 12:04 am

Topics on this page in alphabetic order


Why use vi?

When I first tried using vi I thought that you could not have a more obscure and difficult-to-use text editor, but I found that after memorising half-a-dozen commands that it was really quite simple to use. And, quite powerful. For example, you can do something like “find all lines with ’swordfish’ in them, and for those lines only, change ‘cat’ to ‘dog’”. Try doing that with your normal editor!

The other reason is you can usually find vi on almost any Unix installation. If you get used to “my favourite editor” – whatever that is – and connect to a different site for troubleshooting, you may well find it is not installed, or only runs under Xwindows, or some other such restriction.

Further, you can do quite fancy things (see below) like do a “make” from inside vi, and then with a single keystroke go to each error message (even in different files), with the cursor being placed on the line in error, so you can fix it. This is quite a time-saver. Similarly with doing “grep” on a group of files.


The basics

If you start doing something and change your mind you can generally press Ctrl+C to cancel it.

Edit a file, look at it, stop editing

Edit a file from command prompt vi
Edit a file from command prompt for reading only vi -R
Edit a file from within vi :e
Edit a new file from within vi, discard changes to current file :e!
Reload current file, discarding changes :e!
Go forwards a page Ctrl+F (or PgDn)
Go backwards a page Ctrl+B (or PgUp)
Move around single lines or characters Arrow keys
Save changes :w
Save changes and override protected (read-only) files :w!
Save changes and exit vi ZZ
Quit :q
Quit and discard changes :q!
Get general help :help
Get help on a command (eg. :set) :help set

Notes

  1. Whether keys like PgUp and PgDn work will depend on your keymappings. I find recently that they tend to work without needing to make any changes. In some cases you may need to type “vim (file)” at the command prompt rather than “vi (file)” if both are installed. Otherwise you may set up an alias (at your shell prompt) to equate vi to vim.
  2. Any command starting with these characters:
    • : (colon) – starts a command sequence
    • / (slash) – starts a forwards search
    • ? (question mark) – starts a backwards search

    needs you to press to execute them. Until you have done that you can backspace and make corrections.

    These commands are echoed on the bottom line of the screen, so you can see what you are typing. If you have started typing one of those, you see the command being echoed, and change your mind, press Ctrl+C to cancel the command.

Simple example

Let’s edit comm.c and then exit …

vi -R comm.c(PgDn to look at file):q

If you are experimenting then it might be wise to either edit a file you don’t care about (eg. a copy) or use the -R option (read-only).

Alternatively, set read-only mode once you have edited the file:

Set read-only mode :set ro

Go to lines, find matching text

Go to line 1234 (do not see typing) 1234G
Go to line 1234 (see typing) :1234
Go to start of file 1G
Go to end of file G
Find (forwards) a line containing “swordfish” /swordfish
Find (forwards) a line using a regular expression /you see .* here
Repeat last search n
Repeat last search in opposite direction N
Find (backwards) a line containing “swordfish” ?swordfish
Find (backwards) a line using a regular expression ?you see .* here
Search case insensitive (Ignore Case) :set ic
Search with case sensitivity :set noic
Wrap searches back to start of file :set wrapscan
Do not wrap searches :set nowrapscan

Notes – these are probably the most frequent things I do. ‘Go to line number’, especially if you have a compiler error which gives a line number is very handy. Type the line number directly followed by “G”, and you are taken there. Or, if you don’t know the line, type “/” followed by a word or regular expression you are looking for. The second way of going to a line number (:1234) is probably easier to use because you can see the number as you type it. If you type “1234G” the number (1234) is not echoed to the screen as you type.

Highlighting – searching with “/” or “?” normally highlights the found word. Sometimes this can be quite annoying, especially if you have searched for something which occurs frequently, like a space. You can turn this off:

:hi clear search

Case-sensitivity – using “:set ic” lets you search with or without matching the exact case of the word you are searching for (eg. if you search for “dog” do you want to match “DOG”?).

Simple example

Let’s edit comm.c and go to line 5522. Then find “const”.

vi comm.c:5522/const:q

Line numbers

Sometimes it is handy to know what line you are at, or what each line number is.

Show line numbers on the left :set nu
Do not show line numbers on the left :set nonu
Show the current line number :.=
Show total lines in file :=
Show file name, total lines, and current line number Ctrl+G
Show line number of first matching pattern :/pattern/=

Notes – showing lines numbers is particularly useful when you are relating things like error messages (or instructions) to a line number. Also the Ctrl+G trick is useful to remind yourself of what file you are editing.

Simple example

Let’s edit comm.c, show line numbers, find the first line with “const” in it (line 70) and go to it:

vi comm.c:set nu:/const/=:70:q

Changing text

OK, we can move around the file and find things. Let’s start changing stuff …

Undoing things

When you start going into “change things” mode you will probably need to undo your mistakes. Two useful commands:

Undo last change u
Undo all changes on current line U

If things get out of hand, remember:

Quit editor without saving changes :q!
Reload current file, discarding changes :e!

Insert text

All of the changing commands (except “replace next character”) go into “insert mode” (usually shown by “– INSERT –” or “– REPLACE –” at the bottom of the screen). To exit from Insert Mode, press the Esc key.

Insert after cursor i
Insert before cursor a
Insert at beginning of line I
Insert at end of line (append) A
Open (start) new line below cursor o
Open (start) new line above cursor O

The last two are the letter “oh” not a zero. I use the “O” and “o” commands quite a bit to start entering a new line above or below where the cursor currently is.

Change existing text

Replace next character r
Type over following characters R
Replace to end of line C

Note – the “r” command is useful if you just want to make a minor correction (eg. change “A” to “B”). This does not go into Insert Mode, so you don’t need to then cancel Insert Mode. To change the character under the cursor to a “B” you would just type “rB”.

Delete text

Delete character under cursor x
Delete character to left of cursor X
Delete to end of line D
Delete entire line dd

These are your basic deletion commands. “x” to scrub out the character under the cursor, “dd” to delete the entire line.

Advanced deletion

Delete next 5 lines 5dd
Delete to end of line d$
Delete to start of line d0
Delete to word “swordfish” d/swordfish
Delete to the letter “x” dfx
Delete lines 10 to 20 :10,20d
Delete current line and another 5 lines :.,+5d
Delete all lines :%d
Delete current word dw
Find line containing pattern, delete it :/pattern/d
Find line containing “dog”, delete until line containing “cat” :/dog/,/cat/d
Delete from current line to line containing “foo” :.,/foo/d

Copying, cutting and pasting

If you delete some text using the deletion commands described above you have “cut” the text. However it is saved in an internal buffer and can be pasted somewhere else. Simply move the cursor to where you want it and:

Paste after cursor p
Paste before cursor P

vi calls copying “yanking”, and thus uses the letter Y.

To copy text without deleting it you need to “yank” it. The yank commands are similar to the deletion commands, like this:

Yank to end of line y$
Yank to start of line y0
Yank to word “swordfish” y/swordfish
Yank to letter “g” yfg
Yank entire line Y
Yank lines 5 to 10 5,10y

After yanking you can paste as described above (or there is no point to yanking in the first place).


Advanced movement commands

Go forwards a word w
Go backwards a word b
Go to end of word e
Go to start of line 0
Go to end of line $
Go to top of screen H
Go to middle of screen M
Go to bottom of screen L
Go (forwards) to letter “x” on current line fx
Go (backwards) to letter “x” on current line Fx
Go to next occurrence of word under cursor *
Go to previous occurrence of word under cursor #
Find a control character (eg. Tab) /(Ctrl+V)(Tab)
Go backwards a sentence (
Go forwards a sentence )
Go backwards a paragraph {
Go forwards a paragraph }

The command “go to start of line” is a zero, not an “oh”. You can use Ctrl+V in insert or command mode to literally insert the next character.


Repeat counts

Most commands have a “repeat count” that you can optionally type first. To do a repeat count just type the number before the command. It will not be echoed, so type carefully!

For example:

Delete 5 lines 5dd
Delete 5 characters 5x
Delete 5 words 5dw
Replace next 5 characters 5r
Yank (copy) next 7 lines 7Y
Go to line 1000 1000G
Paste copy buffer 10 times 10p
Insert 40 hyphens 40i-
Insert the line “swordfish” 10 times 10oswordfish
Find the 5th occurrence of “swordfish” 5/swordfish

In the above examples means press the Esc key.


Splitting and joining lines

Split a line (insert a return) i
Join two lines (current and next) J
Join next 10 lines 10J
Join lines 10 to 20 :10,20j

Splitting is basically breaking a line into two by inserting a newline. Joining is reversing that process by removing the newline.


Search and replace

Change “nick” to “fred” on current line :s/nick/fred/
Change “nick” to “fred” on the next 5 lines :.,+4 s/nick/fred/
Change “nick” to “fred” on lines 100 to 200, all occurrences :100,200 s/nick/fred/g
Capitalise every word in the entire file :% s/\<./\u&/g
Insert “>” at the start of every line :% s/^/>/
Insert “// nick” at the end of every line :% s;$;// nick;

Special characters for line sequences:

  • . is the current line
  • $ is the last line
  • % is every line
  • +5 means 5 lines from current line
  • -5 means 5 lines before current line

Applying commands to certain lines

You can use the “:g” (global) command to find matching lines (using a regular expression) and then apply a command to those lines. For example:

Find lines containing “fruit” and change “apple” to “orange” on them :g/fruit/s/apple/orange/g
Delete all blank lines :g/^$/d
Find lines NOT containing “nick”, append “oops” to them :g! /nick/normal A oops

The third example above shows you you can use the “normal” command inside a command, to tell vi to use a normal character (in this case A for append) as part of a command.


Shell and filter commands

List directory :! ls
See processes :! ps
Sort lines 20 to 30 :20,30 ! sort
Sort entire file !G sort
Translate next sentence to upper case !) tr '[a-z]' '[A-Z]'
Word count file (save first) :!wc %
Look up manual entry for strstr :!man strstr
Insert “ls” command output into window :r !ls

Tags

Tags let you go to the definition of a function (in C or C++) without having to scan lots of source files (with grep) and work out which ones contain the function and which merely refer to it.

First, make a tag file, like this:

ctags *.c *.cpp *.h

(In recent versions of Linux I have had to use gctags instead of ctags).

This should produce a file “tags” in the current directory.

Now you can go straight to a function, without knowing which file it is in, like this:

vi -t game_loop

Once inside vi you can put the cursor on a word and go to its definition:

Go to function under cursor Ctrl+]
Go back Ctrl+T
Go to function xyz :tag xyz

Automating things

Compiling from within vi and going to errors

You can save your changes, run “make” to compile, and view errors, very easily …

Save file :w
Run “make” :make
Go to next error :cn
Go to previous error :cp

This is fabulously powerful. It lets you skim through all your errors, with vi opening the right file and positioning the cursor on the line in error.

See below for how to map actions (like “:cn”) to function keys to speed up the process.

Mapping actions to function keys

Map the action :cnext to :map :cnext
Map the action :cprevious to :map :cprevious
Map the action :make to :map :make
Map the action :close to :map :close

After entering the above commands you could compile by simply hitting F8, then look at each error by hitting F6.


More useful tips for programmers

Go to definition of word under cursor gd
Go to global definition gD
Find matching bracket, brace, #if, #endif %
Do a grep :grep foo *.c
After grep, go to next occurrence :cn
Get a file (eg. an #include file) whose name is under cursor gf
Auto complete (in insert mode) – match forwards Ctrl+X Ctrl+N
Auto complete (in insert mode) – match previous Ctrl+X Ctrl+P
Make an abbreviation (eg. cca = “const char *”) :ab cca const char *
Turn syntax colouring on :syntax on
Turn syntax colouring off :syntax off
Execute any shell command :! command
Indent selected lines with C-style indenting =

For formatting of C code there are also other options you can use like “autoindent”, “smartindent”, “cindent”, and “indentexpr”. (Use :help (topic) to see more about those options). You can turn these on (eg. :set cindent) to automatically indent your coding as you type. Also, in conjunction with syntax colouring, you can see if you have made a syntax error (eg. not closed a quote, left off a bracket), as the syntax colouring algorithm will highlight in red sequences that do not seem correct.


Spellcheck file

Save file first :w!
Spell check it :! ispell %
Edit fixed file :e %

Tab management

Tabs can be annoying in source files, as they do not necessarily line up when you use different value tab stops. You can manage them in vi like this:

Set tabs to every 4 characters :set ts=4
Convert tabs to spaces in future :set et
Do not expand tabs :set noet
Fix existing tabs (convert to spaces) :%retab
Show tabs visually, and end-of-lines :set list
Do not show tabs and end-of-lines :set nolist

Visual mode

vi can be a bit difficult to follow when you are trying to do something to a block of lines (for example, do I want line 8843 through to 8903 or 8904?), so vim has a “visual mode” where you can actually see lines highlighted in inverse.

First, “mark” a block of lines (or characters) by going to the start of the block, and then using one of the following:

Character mode v
Line mode V
Block mode Ctrl+V
Re-mark previous block gv

The differences are:

  • Character mode – from somewhere inside one line to somewhere inside another (ie. can be a part line)
  • Line mode – will be whole lines
  • Block mode – from (say) column 5 at line 10, to column 60 in line 20 (a square block of text)

Then use the cursor movement commands (search, arrow, go to line, whatever) to mark the other end of the block, and either:

Do some command (see below)
Cancel visual mode Esc
Go to other end of block o

Other ways of establishing a visual block

A word (with white space) vaw
Inner word viw
A WORD (with white space) vaW
Inner WORD viW
A sentence (with white space) vas
Inner sentence vis
A paragraph (with white space) vap
Inner paragraph vip
A ( … ) block (includes brackets) vab
Inner ( … ) block vib
A { … } block (includes braces) vaB
Inner { … } block viB

A “word” is a sequence of letters, numbers, underscores. A “WORD” is a sequence that is terminated by spaces. The difference would apply in cases like a(b) – if the cursor is on “a” a “word” is “a” however a “WORD” is “a(b)”.

Here is an example, from C source code. Say you have the following code, and you want to select the code inside the inner { … } characters. Put the cursor in the middle (eg. on CON_EDITING) and type “viB” and the “inner block” (text in bold) will be highlighted.

if ( d->pagepoint ){if ( !pager_output(d) ){  if ( d->character  && ( d->connected == CON_PLAYING  ||   d->connected == CON_EDITING ) )      save_char_obj( d->character );  d->outtop = 0;  close_socket(d, FALSE);}}

Here is another method of selecting a visual block of C code. Say we have the following code and we want to highlight everything inside the “while” loop. Put the cursor on the first “{” and type “v%”. That will go into visual mode and move to the end of the block. The highlighted code will be in bold.

while ( usecDelta >= 1000000 ){  usecDelta -= 1000000;  secDelta  += 1;}

Visual mode commands

See below for meanings of notes in brackets.

Switch case ~
Delete d
Change (4) c
Yank y
Shift right (4) >
Shift left (4) <
Filter through external command (1) !
Filter through ‘equalprg’ option command (1) =
Format lines to ‘textwidth’ length (1) gq

You can also do the following on the selected block:

Start ex command for highlighted lines (1) :
Change (4) r
Change s
Change (2)(4) C
Change (2) S
Change (2) R
Delete x
Delete (3) D
Delete (2) X
Yank (2) Y
Join (1) J
Make uppercase U
Make lowercase u
Find tag Ctrl+]
Block insert I
Block append A

Notes

  1. Always whole lines
  2. Whole lines when not using CTRL-V.
  3. Whole lines when not using CTRL-V, delete until the end of the line when using CTRL-V.
  4. When using CTRL-V operates on the block only.

An example of visual mode?

OK, let’s say we have a visual block highlighted. Try these:

Delete it d
Copy it Y
Change “apple” to “orange” in the block :s/apple/orange/g
Turn into C++ comments :s.^.//.
Turn into C comments :s-^.*$-/* & */-

Marking your work

If you need to jump backwards and forwards between a couple of places you can “mark” them …

Mark current position as “x” mx
Go to position “x” `x
Show list of known marks :marks

That character before the “x” is a back-quote – on my keyboard on the top-left corner, under the tilde (~) symbol. Marks can be in a different file to the current one.


Recording commands

Finally, let’s do an example of recording commands for repeating later.

Record a sequence q(letter)(commands)q
Play back sequence @(letter)
See what is in registers :reg

You record a sequence into a lower-case register (a-z), eg.

qa:s/fish/chips/q

The command above (starting and ending with “q”) records into register “a” the sequence “:s/fish/chips/”.

Then whenever you want to repeat that command you can type “@a”.

Example of recording

Whilst writing this page I wanted to convert every second sequence of:

(something)

to:

(something)

Doing a “find and replace” would have been tedious, as I would have had to skip every second item found. I was able to do it quite quickly by recording a macro. To do this I typed:

qa2/:s///:s$$$$q

The sequence above did the following:

  1. Start recording (q) under register “a”
  2. Search for the second occurence of (hence the leading “2″ on the line)
  3. Change “” to “"
  4. On the same line change “” to “
  5. “. I used a $ as the search delimiter because the character “/” was in the text to be searched for.

  6. Go to the end of the current line ($) so the next search would begin at the next
  7. Stop recording (q)

Then I moved to the start of the file (1G), turned search wrapping off (:set nowrapscan) and typed “999@a”. This executed macro “a” 999 times. In fact, it stopped before 999 times because the search failed after it got to the end of file.


Setting up your personal favourite settings

If you have some personal favourite settings like:

  • Spaces for tabs
  • Whether searches are highlighted or not
  • Syntax colouring on or off
  • Mapping function keys to special functions

you can have them processed automatically by putting them into a file named “.vimrc” in your home directory (see “:help vimrc” inside vim for more details).

For example, your .vimrc file might have in it:

set ts=4   " tab stops every 4 charactersset expandtab  " tabs to spaces

map  :cnext   " next error after a make or grepmap  :cprevious " previous errormap  :close    " close current window (eg. help)

syntax on  " syntax colouring on

hi clear search  " do not highlight searched-for words

From: http://www.gammon.com.au/smaug/vi.htm

howto use /usr/local/

In howto, linux on February 2, 2008 at 9:01 pm
Normally when I partition my hard disk for installation of Linux. I will make it like this:
1. 1.5G Swap
2. 10G /
3. 20G /home
4. <10G /usr/local/

/usr/local and its subdirectories are used for the installation of software and other files for use on the local machine. What this really means is that software that is not part of the official distribution (which usually goes in /usr/bin) goes here.

/usr/local/ is the item when I try to keep some partitions not to be formatted, the system prompted me, says some partitions must be formatted, such as /, while some like /home, /usr/local can be kept unformatted. From this on, I leave a partition of /usr/local there. More and more I realized that how to use it: 1. When you “make” program form src, most of the geeks use such a command: sudo ./configure [--prefix=/usr/loca/xxx ......]
This means the programs compiled by you will be kept here, no matter whether you reinstall your system or not, it will always be there. Comparisons with program from .deb, which brings standard destinations and parameters when you install it.
2. /usr/local/bin, where can be a place you put all your favorite “links” here.
3. Some huge programs with licenses, such as Matlab, which just need be installed once, can be stored here. /home can be the places for your documents, while /usl/local is for your programs. (And I found if Matlab is installed in /opt, some java classes compiled by yourself for Matlab will not run correctly, for example, I ever made a java class to be called by Matlab to get configurations from .conf files, when I reinstalled Matlab from /opt to /usr/local, it works correctly, quite weird.)

howto use /usr/local/

In howto, linux on February 2, 2008 at 9:01 pm
Normally when I partition my hard disk for installation of Linux. I will make it like this:
1. 1.5G Swap
2. 10G /
3. 20G /home
4. <10G /usr/local/

/usr/local and its subdirectories are used for the installation of software and other files for use on the local machine. What this really means is that software that is not part of the official distribution (which usually goes in /usr/bin) goes here.

/usr/local/ is the item when I try to keep some partitions not to be formatted, the system prompted me, says some partitions must be formatted, such as /, while some like /home, /usr/local can be kept unformatted. From this on, I leave a partition of /usr/local there. More and more I realized that how to use it: 1. When you “make” program form src, most of the geeks use such a command: sudo ./configure [--prefix=/usr/loca/xxx ......]
This means the programs compiled by you will be kept here, no matter whether you reinstall your system or not, it will always be there. Comparisons with program from .deb, which brings standard destinations and parameters when you install it.
2. /usr/local/bin, where can be a place you put all your favorite “links” here.
3. Some huge programs with licenses, such as Matlab, which just need be installed once, can be stored here. /home can be the places for your documents, while /usl/local is for your programs. (And I found if Matlab is installed in /opt, some java classes compiled by yourself for Matlab will not run correctly, for example, I ever made a java class to be called by Matlab to get configurations from .conf files, when I reinstalled Matlab from /opt to /usr/local, it works correctly, quite weird.)

坏硬盘分区

In hardware, howto on February 1, 2008 at 1:51 pm
一、用软件来解决

1.在天极网Ftp://ftp1.mydown.com/home1/soft34/fbdisk10.zip下载一个大小仅19.8KB的小软件
FBDISK(坏盘分区器)。它可将有坏磁道的硬盘自动重新分区,将坏磁道设为隐藏分区。在DOS下运行FBDISK,屏幕提示Start scan
hard disk?(Y/N),输入Y,开始扫描硬盘,并将坏道标出来,接着提示Write to disk?(Y/N),选Y。坏道就会被隔离。

2.用PartitionMagic对硬盘进行处理。先用PartitionMagic中的“Check”命令来扫描磁盘,大概找出坏簇所在的硬盘分区,
然后在Operations菜单下选择“Advanced/bad Sector Retest”。再通过Hide
Partition菜单把坏簇所在的分区隐藏起来,这样就可以避免对这个区域进行读写。如果系统提示“TRACK 0 BAD,DISK
UNUSABLE”,那么说明硬盘的零磁道出现坏道。这需要通过Pctools9.0等磁盘软件,把0扇区0磁道屏蔽起来,最后用1扇区取代它就能修复。

以Pctools9.0为例,运行Pctools9.0中的de.exe文件,接着选主菜单Select中的Drive,进去后在Drive
type项选Physical,按空格选中它,再按Tab键切换到Drives项,选中hard
disk,然后回到主菜单,打开Select菜单,在出现的Partition
Table中,选中硬盘分区表信息。找到C盘,该分区是从硬盘的0柱面开始的,那么,将1分区的Beginning
Cylinder的0改成1,保存后退出。重新启动后再重新分区、格式化即可 二、重新分区再隐藏

用Windows系统自带的Fdisk。如果硬盘存在物理坏道,通过Scandisk和Norton Disk
Doctor我们就可以估计出坏道大致所处位置,然后利用Fdisk分区时为这些坏道分别单独划出逻辑分区,所有分区步骤完成后再把含有坏道的逻辑分区删
除掉,余下的就是没有坏道的好盘了。

方法一:如一块4.3G硬盘在2G处有严重的物理坏道,用Format格式化进行不下去,Scandisk或NDD检测也通不过,但能正常分区。找来一款分区格式化软件Smart Fdisk,用启动盘启动电脑后,进入盘符A:,运行该软件的执行文件SFdisk.EXE;然后删掉(DEL)原有分区,算出坏道在硬盘上的所在位置。如本例中,先建立1990M的基本分区,快速格式化后并激活它,然后再把坏道处分出约50M的逻辑分区,再将所剩的硬盘空间作为一个逻辑区后用快速格式化功能将其快速格式化;最后再将那个约50M的坏道所在的区删除(DEL)掉就是了。然后重启,一个有严重物理坏道的硬盘就很快被修好了,以后磁头再也不会去读那些被删除了的坏道区了。

方法二:用Windows系统自带的Fdisk分区。例如一块1G的硬盘,在格式化到10%时不能顺利通过,这时按Ctrl+Break强行终止,运行 Fdisk建立一个90M的DOS分区为C盘,然后再建立一个20M逻辑盘D,再将余下的800余M建立一个逻辑盘E。退出Fdisk再运行Format E:,如果格到10%时又遇到阻碍,这时用Fdisk再建立一个88M的E盘、10M的F盘,余下的790M作为G盘。继续重复上面的操作,直到完成。然后,运行Fdisk将10M的D、F盘删除,这时余下的就是没有坏道的好盘了。

方法三:同理,用PartitionMagic、DiskManager等磁盘软件也可完成这样的工作。如PartitionMagic分区软件,先用 PartitionMagic4中的“check”命令或Windows中的磁盘扫描程序来扫描磁盘,算出坏簇在硬盘上的位置,然后在 Operations菜单下选择“Advanced/bad Sector Retest”;把坏簇所在硬盘分成多个区后,再把坏簇所在的分区隐藏,以免在Windows中误操作,这个功能是通过Hide Partition菜单项来实现的。这样也能保证有严重坏道的硬盘的正常使用,并免除系统频繁地去读写坏道从而扩展坏道的面积。

系统显示“TRACK 0 BAD,DISK UNUSABLE”,意思为“零磁道损坏,硬盘无法使用”或用磁盘扫描程序扫描其它硬盘时其0扇区出现红色“B”。硬盘0扇区损坏,是大家比较头痛的故障,一般人往往将出现这样故障的硬盘作报废处理。其实合理运用一些磁盘软件,把报废的0扇区屏蔽掉,而用1扇区取而代之就能起到起死回生的效果,这样的软件如Pctools9.0和NU8等。

方法一:我们就先以Pctools9.0为例来作说明。一块2.1G硬盘出现上述故障,用盘启动电脑后,运行Pctools9.0目录下的DE.EXE文件。接着选主菜单Select中的Drive,进去后在Drive type项选Physical,按空格选定,再按Tab键切换到Drives项,选中hard disk,然后OK回车后回到主菜单。打开Select菜单,这时会出现Partition Table,选中进入后出现硬盘分区表信息。该硬盘有两个分区,找到C区,该分区是从硬盘的0柱面开始的,那么,将1分区的Beginning Cylinder的0改成1就可以了,保存后退出。重新启动电脑后按Del键进入COMS设置,运行“IDE AUTO DETECT”,可以看到CYLS由782变成781。保存退出后重新分区格式化该硬盘,使其起死回生。

方法二:诺顿NU8.0也较好用。例如一块1.28G硬盘出现0磁道损坏故障,进入NU8工具包目录,运行其主程序NORTON.EXE,然后可先选“补救盘”RESCUE选项对该硬盘的引导区、分区表等信息进行备份。接着选择“磁盘编辑器DISKEDIT”,成功运行后选“对象OBJECT”,选“分区表”后可见本硬盘的参数如下:面SIDE为0-63,簇CYLINDER为0-255,扇区SECTOR为1-63,其主引导记录和分区表信息就应该在0 面0柱1扇区。我们要做的事就是把其C盘的起始扇区从0面0柱1扇区改为0面1柱1扇区,移动光标手工修改即可。另外需要说的就是,改动数值要根据具体情况而定。最后存盘后退出重启电脑,用Format命令格式化硬盘即可正常使用了。需要特别留意的是,修好后的硬盘一定不要再用DOS下的Fdisk等分区工具对其进行重新分区操作,以免其又改变硬盘的起始柱面。

Powered by ScribeFire.

坏硬盘分区

In hardware, howto on February 1, 2008 at 1:51 pm
一、用软件来解决

1.在天极网Ftp://ftp1.mydown.com/home1/soft34/fbdisk10.zip下载一个大小仅19.8KB的小软件
FBDISK(坏盘分区器)。它可将有坏磁道的硬盘自动重新分区,将坏磁道设为隐藏分区。在DOS下运行FBDISK,屏幕提示Start scan
hard disk?(Y/N),输入Y,开始扫描硬盘,并将坏道标出来,接着提示Write to disk?(Y/N),选Y。坏道就会被隔离。

2.用PartitionMagic对硬盘进行处理。先用PartitionMagic中的“Check”命令来扫描磁盘,大概找出坏簇所在的硬盘分区,
然后在Operations菜单下选择“Advanced/bad Sector Retest”。再通过Hide
Partition菜单把坏簇所在的分区隐藏起来,这样就可以避免对这个区域进行读写。如果系统提示“TRACK 0 BAD,DISK
UNUSABLE”,那么说明硬盘的零磁道出现坏道。这需要通过Pctools9.0等磁盘软件,把0扇区0磁道屏蔽起来,最后用1扇区取代它就能修复。

以Pctools9.0为例,运行Pctools9.0中的de.exe文件,接着选主菜单Select中的Drive,进去后在Drive
type项选Physical,按空格选中它,再按Tab键切换到Drives项,选中hard
disk,然后回到主菜单,打开Select菜单,在出现的Partition
Table中,选中硬盘分区表信息。找到C盘,该分区是从硬盘的0柱面开始的,那么,将1分区的Beginning
Cylinder的0改成1,保存后退出。重新启动后再重新分区、格式化即可 二、重新分区再隐藏

用Windows系统自带的Fdisk。如果硬盘存在物理坏道,通过Scandisk和Norton Disk
Doctor我们就可以估计出坏道大致所处位置,然后利用Fdisk分区时为这些坏道分别单独划出逻辑分区,所有分区步骤完成后再把含有坏道的逻辑分区删
除掉,余下的就是没有坏道的好盘了。

方法一:如一块4.3G硬盘在2G处有严重的物理坏道,用Format格式化进行不下去,Scandisk或NDD检测也通不过,但能正常分区。找来一款分区格式化软件Smart Fdisk,用启动盘启动电脑后,进入盘符A:,运行该软件的执行文件SFdisk.EXE;然后删掉(DEL)原有分区,算出坏道在硬盘上的所在位置。如本例中,先建立1990M的基本分区,快速格式化后并激活它,然后再把坏道处分出约50M的逻辑分区,再将所剩的硬盘空间作为一个逻辑区后用快速格式化功能将其快速格式化;最后再将那个约50M的坏道所在的区删除(DEL)掉就是了。然后重启,一个有严重物理坏道的硬盘就很快被修好了,以后磁头再也不会去读那些被删除了的坏道区了。

方法二:用Windows系统自带的Fdisk分区。例如一块1G的硬盘,在格式化到10%时不能顺利通过,这时按Ctrl+Break强行终止,运行 Fdisk建立一个90M的DOS分区为C盘,然后再建立一个20M逻辑盘D,再将余下的800余M建立一个逻辑盘E。退出Fdisk再运行Format E:,如果格到10%时又遇到阻碍,这时用Fdisk再建立一个88M的E盘、10M的F盘,余下的790M作为G盘。继续重复上面的操作,直到完成。然后,运行Fdisk将10M的D、F盘删除,这时余下的就是没有坏道的好盘了。

方法三:同理,用PartitionMagic、DiskManager等磁盘软件也可完成这样的工作。如PartitionMagic分区软件,先用 PartitionMagic4中的“check”命令或Windows中的磁盘扫描程序来扫描磁盘,算出坏簇在硬盘上的位置,然后在 Operations菜单下选择“Advanced/bad Sector Retest”;把坏簇所在硬盘分成多个区后,再把坏簇所在的分区隐藏,以免在Windows中误操作,这个功能是通过Hide Partition菜单项来实现的。这样也能保证有严重坏道的硬盘的正常使用,并免除系统频繁地去读写坏道从而扩展坏道的面积。

系统显示“TRACK 0 BAD,DISK UNUSABLE”,意思为“零磁道损坏,硬盘无法使用”或用磁盘扫描程序扫描其它硬盘时其0扇区出现红色“B”。硬盘0扇区损坏,是大家比较头痛的故障,一般人往往将出现这样故障的硬盘作报废处理。其实合理运用一些磁盘软件,把报废的0扇区屏蔽掉,而用1扇区取而代之就能起到起死回生的效果,这样的软件如Pctools9.0和NU8等。

方法一:我们就先以Pctools9.0为例来作说明。一块2.1G硬盘出现上述故障,用盘启动电脑后,运行Pctools9.0目录下的DE.EXE文件。接着选主菜单Select中的Drive,进去后在Drive type项选Physical,按空格选定,再按Tab键切换到Drives项,选中hard disk,然后OK回车后回到主菜单。打开Select菜单,这时会出现Partition Table,选中进入后出现硬盘分区表信息。该硬盘有两个分区,找到C区,该分区是从硬盘的0柱面开始的,那么,将1分区的Beginning Cylinder的0改成1就可以了,保存后退出。重新启动电脑后按Del键进入COMS设置,运行“IDE AUTO DETECT”,可以看到CYLS由782变成781。保存退出后重新分区格式化该硬盘,使其起死回生。

方法二:诺顿NU8.0也较好用。例如一块1.28G硬盘出现0磁道损坏故障,进入NU8工具包目录,运行其主程序NORTON.EXE,然后可先选“补救盘”RESCUE选项对该硬盘的引导区、分区表等信息进行备份。接着选择“磁盘编辑器DISKEDIT”,成功运行后选“对象OBJECT”,选“分区表”后可见本硬盘的参数如下:面SIDE为0-63,簇CYLINDER为0-255,扇区SECTOR为1-63,其主引导记录和分区表信息就应该在0 面0柱1扇区。我们要做的事就是把其C盘的起始扇区从0面0柱1扇区改为0面1柱1扇区,移动光标手工修改即可。另外需要说的就是,改动数值要根据具体情况而定。最后存盘后退出重启电脑,用Format命令格式化硬盘即可正常使用了。需要特别留意的是,修好后的硬盘一定不要再用DOS下的Fdisk等分区工具对其进行重新分区操作,以免其又改变硬盘的起始柱面。

Powered by ScribeFire.

keyboard shortcut reset

In howto, linux on January 30, 2008 at 10:20 pm

The following command list all the keyboard shortcuts under this category.
gconftool-2 –recursive-list /desktop/gnome

More options go to: http://www.gnome.org/learn/admin-guide/2.2/ch01s04.html

quote in Java

In howto, java on January 30, 2008 at 9:17 pm
“3″ is not a char literal. It uses double quotes, instead of single quotes. (Double quotes makes it a String which we’ll discuss later).

is not a char literal. There isn’t a character between the two single quotes. You need one character between the double quotes.

‘ab’ is not a char literal. There are two characters in between the single quotes. char literals only have one character in between.

python workspace, a little bit global

In howto, python on January 26, 2008 at 11:43 am

a=100

def first():
b=a+1
c=a+2
return b,c

def second():
d=bb+11
e=cc+12
return d,e

class thirdC:
def fourth(self):
f=dd+101
g=ee+102
return f,g
def fifth():
h=ff+1001
i=gg+1002
(j,k)=second()
return h,i,j,k

if __name__==’__main__’:
(bb,cc)=first()
(dd,ee)=second()
tc=thirdC()
(ff,gg)=tc.fourth()
(hh,ii,jj,kk)=fifth()

java Socket programming

In howto, java on January 25, 2008 at 12:45 pm
DataInputStream和InputStreamReader都可以用一个InputStream类做为其参数,而且目的也是一样的,就是把字节级的读取转换为字符级的读取!

#### Basing on Byte stream
Socket Operations at Client Side
• create a client socket:
Socket (host, port)
s = new Socket (“java.sun.com”, 13)

• get input / output data streams out of the socket:
in = new DataInputStream(s.getInputStream ());
out = new DataOutputStream( s.getOutputStream());
out = new PrintStream( s.getOutputStream());

• read from input / write to output data streams:
String str = in.readLine();
out.println ( “Echo:” + str + “\r”);

• close the socket:
s.close();

Socket Operations at Server Side

A server is always waiting for being connected. It need not initiate a connection to a host. So a server socket need only specify its own port no.
• create a server socket:
ServerSocket (port)
ServerSocket s = new ServerSocket(8189);
• accept an incoming connection:
Socket snew = s.accept ();
• get input / output data streams out of the socket for the incoming client:
in = new DataInputStream(snew.getInputStream());
out = new PrintStream(snew.getOutputStream());
• close the socket for the incoming client:
snew.close();

#### Basing on Character strem
Socket Operations at Client Side
• create a client socket:
Socket echoSocket = new Socket(args[0],9999);
out = new PrintWriter(echoSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
• read from input streams:

System.out.println(“server: ” + in.readLine());
• write to output streams:
String str = in.readLine();
out.println ( “Echo:” + str + “\r”);
• close the socket
echoSocket.close();

Socket Operations at Server Side
• create a client socket:
ServerSocket serviceSocket = new ServerSocket(9999);
r=new InputStreamReader(serviceSocket.getInputStream());
in=new BufferedReader(r);
out = new PrintWriter(serviceSocket.getOutputStream(),true);
• read from input streams:
String line=in.readLine()
System.out.println(“Received from client “+line);
• write to output streams:

String str = in.readLine();
out.println(“Server says: “+str);
• close the socket
serviceSocket.close();

Powered by ScribeFire.

java Socket programming

In howto, java on January 25, 2008 at 12:45 pm
DataInputStream和InputStreamReader都可以用一个InputStream类做为其参数,而且目的也是一样的,就是把字节级的读取转换为字符级的读取!

#### Basing on Byte stream
Socket Operations at Client Side
• create a client socket:
Socket (host, port)
s = new Socket (“java.sun.com”, 13)

• get input / output data streams out of the socket:
in = new DataInputStream(s.getInputStream ());
out = new DataOutputStream( s.getOutputStream());
out = new PrintStream( s.getOutputStream());

• read from input / write to output data streams:
String str = in.readLine();
out.println ( “Echo:” + str + “\r”);

• close the socket:
s.close();

Socket Operations at Server Side

A server is always waiting for being connected. It need not initiate a connection to a host. So a server socket need only specify its own port no.
• create a server socket:
ServerSocket (port)
ServerSocket s = new ServerSocket(8189);
• accept an incoming connection:
Socket snew = s.accept ();
• get input / output data streams out of the socket for the incoming client:
in = new DataInputStream(snew.getInputStream());
out = new PrintStream(snew.getOutputStream());
• close the socket for the incoming client:
snew.close();

#### Basing on Character strem
Socket Operations at Client Side
• create a client socket:
Socket echoSocket = new Socket(args[0],9999);
out = new PrintWriter(echoSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
• read from input streams:

System.out.println(“server: ” + in.readLine());
• write to output streams:
String str = in.readLine();
out.println ( “Echo:” + str + “\r”);
• close the socket
echoSocket.close();

Socket Operations at Server Side
• create a client socket:
ServerSocket serviceSocket = new ServerSocket(9999);
r=new InputStreamReader(serviceSocket.getInputStream());
in=new BufferedReader(r);
out = new PrintWriter(serviceSocket.getOutputStream(),true);
• read from input streams:
String line=in.readLine()
System.out.println(“Received from client “+line);
• write to output streams:

String str = in.readLine();
out.println(“Server says: “+str);
• close the socket
serviceSocket.close();

Powered by ScribeFire.

HOWTO: lambda in Python

In howto, python on January 23, 2008 at 6:24 pm
By popular demand, a few features commonly found in functional programming languages like Lisp have been added to Python. With the lambda keyword, small anonymous functions can be created. Here’s a function that returns the sum of its two arguments: “lambda a, b: a+b”. Lambda forms can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda forms can reference variables from the containing scope:

>>> def make_incrementor(n):
… return lambda x: x + n

>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

lambda很灵活,可以用在任何需要函数的地方:

>>>def f(x):
… return x*2

>>> f(2)
4

定义一个函数f(x),f(x)=x*2. 用lambda来表达就是:

>>> f=lambda x: x*2
>>> f(2)
4

这个函数没有函数名,lambda的结果被赋值给变量f调用。

############################################
对于Tkinter,
可以直接用lambda直接设置一些简单callback:
b = Button(master, text=”Delete”,command = lambda listbox=listbox: listbox.delete(ANCHOR))
在这种情况下,需要设定返回值(listbox=),然后才是lambda的参数(listbox).

这种简写方式等效于:(如下code是在一个class内的代码)

self.b = Button(master, text=”Delete”,command = self.toremove)
##self.b = Button(master, text=”Delete”,command = lambda llb=lb: lb.delete(ANCHOR))
def toremove(self):
self.listbox.delete(ANCHOR)

Powered by ScribeFire.

HOWTO: listbox in Python Tkinter

In howto, python on January 23, 2008 at 6:24 pm

alist=[' x ',' xin ','zhengxin',' shan ',' shanshan ','shanshan cheng ']
##aset=set(alist)
##b=set()
##
##for aitem in aset:
## if aitem.find(‘xi’)!=-1:
## print aitem,’:item will be removed’
## b.add(aitem)
##
##c=aset-b
##print aset
##print c

from Tkinter import *
class MyDialog:
def __init__(self,master):
MyDialog.removed=list()
Label(text=”one”).pack()
self.s = Frame()
self.s.pack()

self.listbox = Listbox(self.s,selectmode=EXTENDED)
self.listbox.pack()

for item in alist:
self.listbox.insert(END, item)

Label(text=”two”).pack()

self.b = Button(master, text=”Delete”,command = self.toremove)
## self.b = Button(master, text=”Delete”,command = lambda lb=lb: lb.delete(ANCHOR))
self.b.pack()

def toremove(self):
# Select what to remove and save them to the Class Variable MyDialog.removed
self.items = self.listbox.curselection()
for i in self.items:
MyDialog.removed.append(self.listbox.get(i))
print self.listbox.get(i)

# To sort the sequence,then reverse, then delete.
self.iitems=list()
for i in range(len(self.items)):
self.iitems.append(int(self.items[i]))
self.iitems.sort()
self.iitems.reverse()
for j in self.iitems:
self.listbox.delete(j)
## def toremove(self):
## self.listbox.delete(ANCHOR)

if __name__==’__main__’:
root = Tk()
d = MyDialog(root)
root.mainloop()

Create class for GUI , Python

In howto, python on January 22, 2008 at 9:38 pm

from Tkinter import *

class MyDialog:
def __init__(self, top):
Label(top, text=”Value”).pack()

self.e = Entry(top)
self.e.pack(padx=5)

b = Button(top, text=”OK”, command=self.ok)
b.pack(pady=5)

def ok(self):
print “value is”, self.e.get()

root = Tk()
d = MyDialog(root)
root.mainloop()

Multiline Formulae in LaTeX and lyx

In howto, latex on January 22, 2008 at 6:39 pm

Cited from: http://www.maths.tcd.ie/~dwilkins/LaTeXPrimer/Multiline.html

Consider the problem of typesetting the formula

[GIF Image]

It is necessary to ensure that the = signs are aligned with one another. In LaTeX, such a formula is typeset using the eqnarray* environment. The above example was obtained by typing the lines

\begin{eqnarray*}\cos 2\theta & = & \cos^2 \theta - \sin^2 \theta \\            & = & 2 \cos^2 \theta - 1.\end{eqnarray*}

Note the use of the special character & as an alignment tab. When the formula is typeset, the part of the second line of the formula beginning with an occurrence of & will be placed immediately beneath that part of the first line of the formula which begins with the corresponding occurrence of &. Also \\ is used to separate the lines of the formula.

Although we have placed corresponding occurrences of & beneath one another in the above example, it is not necessary to do this in the input file. It was done in the above example merely to improve the appearance (and readability) of the input file.

The more complicated example

[GIF Image]

was obtained by typing

If $h \leq \frac{1}{2} |\zeta - z|$ then\[ |\zeta - z - h| \geq \frac{1}{2} |\zeta - z|\]and hence\begin{eqnarray*}\left| \frac{1}{\zeta - z - h} - \frac{1}{\zeta - z} \right|& = & \left|\frac{(\zeta - z) - (\zeta - z - h)}{(\zeta - z - h)(\zeta - z)}\right| \\  & = &\left| \frac{h}{(\zeta - z - h)(\zeta - z)} \right| \\ & \leq & \frac{2 |h|}{|\zeta - z|^2}.\end{eqnarray*}

The asterisk in eqnarray* is put there to suppress the automatic equation numbering produced by LaTeX. If you wish for an automatically numbered multiline formula, you should use \begin{eqnarray} and \end{eqnarray}.

#############################################
For Lyx, in the menu of Insert > Math > Eqnarray Environment, here it's easy to input multiple-line equation.

Lyx: equation numbering ALT+M N

In howto, latex on January 22, 2008 at 2:09 pm

LATEX is at its best when handling mathematical equations. Using LyX, you can get those perfect
equations with relatively little effort. There are two ways of entering equations. The first is to
use the menus. The “math” submenu in the “insert” menu contains everything you need. The
only problem is that it is clumsy, and only suitable for very beginning users. Far better is to
use the keyboard. The Alt-m key sequence gives you pretty much everything you need to create
equations. Let us try to create the following equation:


1. First enter the “Descriptive Math Mode” by pressing Alt-m d which starts an equation on
a separate line.
2. The terms on the left side involve fractions. A fraction is entered by typing Alt-m f (“f”
for fraction). To enter the ¶ symbol, type Alt-m p (“p” for partial). So type
Alt-m d Alt-m f Alt-m p A Alt-m p z
The takes you to the denominator field, while the leaves the fraction
and allows you to enter the next term.
3. The second term involves a subscript. This is done by typing “_”. So the second term is
entered as:
+ v_G Alt-m f Alt-m p A Alt-m p t
5
The “v_G” entry creates vG.
4. The third term involves superscripts. This is done by typing “^”. So the third term is
entered as follows:
+ iD Alt-m f Alt-m p^2 A Alt-m p t^2
Notice the “Alt-m p^2” and the “t^2” entries. These create the second derivitives.
5. The term on the right involves a Greek letter and vertical bars. These are entered as follows:
= Alt-m g g |A|^2 A
Here the “Alt-m g” sequence selects the Greek keyboard, where “abcde. . . ” become
“abcde. . . ”. The vertical bar is just directly typed in as seen above.
6. Finally, we want to give the equation a number. By default, LyX does not number equations.
If you want to add a number to an equation, just put the cursor into the equation
and type Alt-m n. The equation number is automatically generated, and is guaranteed to be
in proper sequence, with proper respect paid to style. If you want to remove an equation
number, just type Alt-m Shift-n.
However, the only real reason to number an equation such as Eq. (1) is to refer to it in the
text. In that case, we can’t just add a number, we have to give that number a meaningful
label. This is done by placing the cursor in the equation, and typing Alt-i l, which opens
up a dialog box where you can give the name of the label, say “eq:maineq” (by default,
LyX will put “eq:” as part of an equation label to keep it from being confused with a
section label or a figure label or any other label). Once you have done that, you can refer
to that equation elsewhere by typing
Eq. Alt-i r and selecting “eq:maineq”

That is pretty much it. There is much more you can do, like creating matrices, integral signs etc.
But the essence of the math mode in LyX is what we just did. But look at the result (type Alt-x
p) and see the quality of the typesetting that we have painlessly obtained. The Alt-m keyboard is
summarized below for quick reference:

############################
Normally, equation with label will be numbered automatically.

Lyx: equation numbering ALT+M N

In howto, latex on January 22, 2008 at 2:09 pm

LATEX is at its best when handling mathematical equations. Using LyX, you can get those perfect
equations with relatively little effort. There are two ways of entering equations. The first is to
use the menus. The “math” submenu in the “insert” menu contains everything you need. The
only problem is that it is clumsy, and only suitable for very beginning users. Far better is to
use the keyboard. The Alt-m key sequence gives you pretty much everything you need to create
equations. Let us try to create the following equation:


1. First enter the “Descriptive Math Mode” by pressing Alt-m d which starts an equation on
a separate line.
2. The terms on the left side involve fractions. A fraction is entered by typing Alt-m f (“f”
for fraction). To enter the ¶ symbol, type Alt-m p (“p” for partial). So type
Alt-m d Alt-m f Alt-m p A Alt-m p z
The takes you to the denominator field, while the leaves the fraction
and allows you to enter the next term.
3. The second term involves a subscript. This is done by typing “_”. So the second term is
entered as:
+ v_G Alt-m f Alt-m p A Alt-m p t
5
The “v_G” entry creates vG.
4. The third term involves superscripts. This is done by typing “^”. So the third term is
entered as follows:
+ iD Alt-m f Alt-m p^2 A Alt-m p t^2
Notice the “Alt-m p^2” and the “t^2” entries. These create the second derivitives.
5. The term on the right involves a Greek letter and vertical bars. These are entered as follows:
= Alt-m g g |A|^2 A
Here the “Alt-m g” sequence selects the Greek keyboard, where “abcde. . . ” become
“abcde. . . ”. The vertical bar is just directly typed in as seen above.
6. Finally, we want to give the equation a number. By default, LyX does not number equations.
If you want to add a number to an equation, just put the cursor into the equation
and type Alt-m n. The equation number is automatically generated, and is guaranteed to be
in proper sequence, with proper respect paid to style. If you want to remove an equation
number, just type Alt-m Shift-n.
However, the only real reason to number an equation such as Eq. (1) is to refer to it in the
text. In that case, we can’t just add a number, we have to give that number a meaningful
label. This is done by placing the cursor in the equation, and typing Alt-i l, which opens
up a dialog box where you can give the name of the label, say “eq:maineq” (by default,
LyX will put “eq:” as part of an equation label to keep it from being confused with a
section label or a figure label or any other label). Once you have done that, you can refer
to that equation elsewhere by typing
Eq. Alt-i r and selecting “eq:maineq”

That is pretty much it. There is much more you can do, like creating matrices, integral signs etc.
But the essence of the math mode in LyX is what we just did. But look at the result (type Alt-x
p) and see the quality of the typesetting that we have painlessly obtained. The Alt-m keyboard is
summarized below for quick reference:

############################
Normally, equation with label will be numbered automatically.

Python Tkinter-Checkbutton

In howto, python on January 22, 2008 at 12:40 pm

Cited from: http://effbot.org/tkinterbook/checkbutton.htm

To use a Checkbutton, you must create a Tkinter variable. To inspect the button state, query the variable.

from Tkinter import *

master = Tk()

var = IntVar()

c = Checkbutton(master, text="Expand", variable=var)c.pack()

mainloop()

By default, the variable is set to 1 if the button is selected, and 0 otherwise. You can change these values using the onvalue and offvalue options. The variable doesn’t have to be an integer variable:

    var = StringVar()   c = Checkbutton(       master, text="Color image", variable=var,       onvalue="RGB", offvalue="L"       )

If you need to keep track of both the variable and the widget, you can simplify your code somewhat by attaching the variable to the widget reference object.

    v = IntVar()   c = Checkbutton(master, text="Don't show this again", variable=v)   c.var = v

If your Tkinter code is already placed in a class (as it should be), it is probably cleaner to store the variable in an attribute, and use a bound method as callback:

    def __init__(self, master):       self.var = IntVar()       c = Checkbutton(           master, text="Enable Tab",           variable=self.var,           command=self.cb)       c.pack()

   def cb(self, event):       print "variable is", self.var.get()

Example:

from Tkinter import *def cb1():   print 'use c.var.get() to check the checkbutton value'

master=Tk()v = IntVar()c = Checkbutton(master, text="Color Image", variable=v, command=cb1)c.var=vc.pack()master.mainloop()

simple python gui

In howto, python on January 19, 2008 at 3:25 pm

from Tkinter import *
root = Tk()

w = Label(root, text=”Hello, world!”)
w.pack()

root.mainloop() # if runs in IDLE, comment this line, otherwise errors occur.

python arguments

In howto, python on January 18, 2008 at 1:04 pm

What if you want to supply arguments to the Python script? The sys module contains a variable called argv. It is an array that contains the name of the Python file and any command line arguments that followed.

For example, let’s define a file called show_args.py;

import sys
print sys.argv

Now when we evaluate show_args.py with Python, we’ll simply see the arguments we entered on the command line, along with the filename of the script:

% python show_args.py 1 2 3 4 5
['show_args.py', '1', '2', '3', '4', '5']
%

Notice that sys.argv is an array, so you can refer to individual commands using the [] array element syntax. You can also use any array function on sys.argv or on a part of it (using the [:] syntax).

Here’s file show_args_2.py that extracts elements from the sys.argv array:

import sys, string

print ‘The arguments of %s are “%s”‘ % \
(sys.argv[0], string.join(sys.argv[1:]))

(The “\” character lets me continue the print command to the next line by nullifying the “newline” character that would otherwise create a new line.) We’ll run this script with the same command-line arguments we used for show_args.py:

% python show_args_2.py 1 2 3 4 5
The arguments of show_args_2.py are “1 2 3 4 5″
%

The sys.argv array consists of strings, so you will need to convert number arguments to numbers using the conversion functions int or float. For example, let’s make our pi multiplying script take an argument. We’ll call it pi_mult.py:

import math, sys

def times_pi(value):
return math.pi * value

value = float(sys.argv[1])

print ‘%g times pi is %g’ % (value, times_pi(value))

Now when we run it with a command-line argument, that argument is changed into a float before it is multiplied by math.pi:

% python pi_mult.py 2
2 times pi is 6.28319
%

But what if we forget to enter an argument on the command line? We’ll get an error message (since there is no second element to the sys.argv array) and Python will stop evaluating the script file:

% python pi_mult.py
Traceback (most recent call last):
File “pi_mult.py”, line 6, in ?
value = float(sys.argv[1])
IndexError: list index out of range
%

By convention, Unix commands will provide a “usage” message if the arguments are wrong. The usage message lists descriptions of the arguments (enclosed in “” characters) so you know what kind of arguments the command requires. We can add a check for the right number of arguments to our command, and print out the usage message if the argument count is incorrect.

We’ll make a new version, called pi_mult_2.py, in which we add the argument check and the usage message:

import math, sys

if len(sys.argv) != 2:
print ‘Usage: pi_mult_2.py ‘
sys.exit(1)

def times_pi(value):
return math.pi * value

value = float(sys.argv[1])

print ‘%g times pi is %g’ % (value, times_pi(value))

Now when we try to run pi_mult_2.py without arguments, the number of command line arguments is wrong; it should be 2: one for the script filename and one for the number to be multipled by pi. The usage message will be printed instead of causing a Python error:

% python pi_mult_2.py
Usage: pi_mult_2.py
%

python read files

In howto, python on January 17, 2008 at 1:06 pm
Doing it the usual way

The standard idiom consists of a an ‘endless’ while loop, in which we repeatedly call the file’s readline method. Here’s an example:

# File: readline-example-1.py

file = open(“sample.txt”)

while 1:
line = file.readline()
if not line:
break
pass # do something

This snippet reads the file line by line. If readline reaches the end of the file, it returns an empty string. Otherwise, it returns the line of text, including the trailing newline character.

On my test machine, using a 10 megabyte sample text file, this script reads about 32,000 lines per second.
Using the fileinput module

If you think the while loop is ugly, you can hide the readline call in a wrapper class. The standard fileinput module contains an input class which does exactly that.

# File: readline-example-2.py

import fileinput

for line in fileinput.input(“sample.txt”):
pass

However, adding more layers of Python code doesn’t exactly help. For the same test setup, performance drops to 13,000 lines per second. That’s nearly two and half times slower!
Speeding up line reading

To speed things up, we obviously need to make sure we spend as little time on in Python code (running under the interpreter) as possible.

One way to do this is to tell the file object to read larger chunks of data. For example, if you have enough memory, you can slurp the entire file into memory, using the readlines method. Or you could even use the read method to read the entire file into a single memory block, and then use string.split to chop it up into individual lines.

However, if you’re processing really large files, it would be nice if you could limit the chunk size to something reasonable. For example, if you read a few thousand lines at a time, you probably won’t use up more than 100 kilobytes or so.

The following script uses a nested loop. The outer loop uses readlines to read about 100,000 bytes of text, and the inner loop processes those lines using a simple for-in loop:

# File: readline-example-3.py

file = open(“sample.txt”)

while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something

Can this really be faster? You bet. With the same test data, we can now process 96,900 lines of text per second!

Or to put it another way, this solution is three times as fast as the standard solution, and over seven times faster than the fileinput version.

In Python 2.2 and later, you can loop over the file object itself. This works pretty much like readlines(N) under the covers, but looks much better:

# File: readline-example-5.py

file = open(“sample.txt”)

for line in file:
pass # do something

In Python 2.1, you have to use the xreadlines iterator factory instead:

# File: readline-example-4.py

file = open(“sample.txt”)

for line in file.xreadlines():
pass # do something

Copyright © 2000 Fredrik Lundh

Powered by ScribeFire.

google search tricks

In google, howto on January 16, 2008 at 3:19 pm
1.thekeywords site:thewebsite
Things can be found just on the specific web site.

2.intitle:index of filename
If you want to find some mpeg files, then use “intitle:index of mpeg”, google will return some index of mpeg files web address, some of them are just like ftp file lists.

Powered by ScribeFire.

Python reads configuration file

In howto, python on January 14, 2008 at 1:15 pm

The ConfigParser module in the standard library already does this:

import ConfigParser

cfg = ConfigParser.ConfigParser()
cfg.readfp(open(‘myconfig.ini’))
print cfg.get(’system’, ‘database’)

—-

The configuration file consists of sections, led by a “[section]” header and followed by “name: value” entries, with continuations in the style of RFC 822; “name=value” is also accepted. Note that leading whitespace is removed from values. The optional values can contain format strings which refer to other values in the same section, or values in a special DEFAULT section. Additional defaults can be provided on initialization and retrieval. Lines beginning with “#” or “;” are ignored and may be used to provide comments.

For example:

[My Section]
foodir: %(dir)s/whatever
dir=frob

would resolve the “%(dir)s” to the value of “dir” (“frob” in this case). All reference expansions are done on demand.

Default values can be specified by passing them into the ConfigParser constructor as a dictionary. Additional defaults may be passed into the get() method which will override all others.

—————————

Python 本身没有数组这个说法, 有的就是list和tuple, list就具有其他语言中的数组特性.
至于list和tuple的区别,在于list可以在运行时修改内容和大小,tuple在首次创建和赋值后, 不可以再次修改内部的内容
不过python 有提供一个array模块,用于提供基本数字,字符类型的数组.用于容纳字符号,整型,浮点等基本类型.

import array
#建立一个整数数组,初始内容是1,2,3,4,5
array.array(‘l’, [1, 2, 3, 4, 5])

这种模块主要用于二进制上的缓冲区,流的操作.

del in python

In howto, python on January 14, 2008 at 1:15 pm

del in python workspace

del(XX) or del XX

Python reads configuration file

In howto, python on January 14, 2008 at 1:15 pm

The ConfigParser module in the standard library already does this:

import ConfigParser

cfg = ConfigParser.ConfigParser()
cfg.readfp(open(‘myconfig.ini’))
print cfg.get(’system’, ‘database’)

—-

The configuration file consists of sections, led by a “[section]” header and followed by “name: value” entries, with continuations in the style of RFC 822; “name=value” is also accepted. Note that leading whitespace is removed from values. The optional values can contain format strings which refer to other values in the same section, or values in a special DEFAULT section. Additional defaults can be provided on initialization and retrieval. Lines beginning with “#” or “;” are ignored and may be used to provide comments.

For example:

[My Section]
foodir: %(dir)s/whatever
dir=frob

would resolve the “%(dir)s” to the value of “dir” (“frob” in this case). All reference expansions are done on demand.

Default values can be specified by passing them into the ConfigParser constructor as a dictionary. Additional defaults may be passed into the get() method which will override all others.

—————————

Python 本身没有数组这个说法, 有的就是list和tuple, list就具有其他语言中的数组特性.
至于list和tuple的区别,在于list可以在运行时修改内容和大小,tuple在首次创建和赋值后, 不可以再次修改内部的内容
不过python 有提供一个array模块,用于提供基本数字,字符类型的数组.用于容纳字符号,整型,浮点等基本类型.

import array
#建立一个整数数组,初始内容是1,2,3,4,5
array.array(‘l’, [1, 2, 3, 4, 5])

这种模块主要用于二进制上的缓冲区,流的操作.

Python中Array的常用操作数组基本操作

In howto, python on January 14, 2008 at 1:14 pm
1. 定义数组

>>> seq = [ “a” , “b” , 1 ]

[ “a” , “b” , 1 ]

2. 创建数组

>>> a = “what are you doing?”.split()

[’what’, ‘are’, ‘you’, ‘doing?’]

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

b = [ x for x in a if x >3 ]

[ 4, 6, 8]

———————————————————–

1. 数组操作

x代表数组中的元素,i代表位置

a) append(x) 把元素x添加到数组的尾部

b) insert(i,x) 把元素x 插入到位置i

c) remove(x) 删除第一个元素x

d) pop(i) 删除第i个元素,并返回这个元素。若调用pop()则删除最后一个元素

e) index(x) 返回数组中第一个值为x的位置。如果没有匹配的元素会抛出一个错误

f) count(x) 返回x在数组中出现的次数

g) sort() 对数组中的元素进行排序

h) reverse() 对数组中的元素用倒序排序

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

>>> del a[0]

[4, 6, 8]

>>> a = [ 1 , 2 ] + a

[1, 2, 4, 6, 8]

>>> a += [None]*2

[1, 2, 4, 6, 8, None, None]

>>> a.remove(1)

[2, 4, 6, 8, None, None]

>>> a.pop()

[2, 4, 6, 8, None,]

>>> a.append(100)

[2, 4, 6, 8, None, 100]

>>> a.insert(0,8)

[8, 2, 4, 6, 8, None, 100]

>>> a.count(8)

2

>>> a.index(2)

1

2. 遍历数组

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

>>> for x in a:

… print x

>>> for i, x in enumerate(a):

… print x

>>> b = [ x+100 for x in a]

>>> for i,j in zip(a,b):

… print i,j

jython searchs python path (but numpy not works)

In howto, python on January 14, 2008 at 1:13 pm

sys.path.append(‘path to search’)

This directory(\Python25\Lib\site-packages) exists so that 3rd party packages can be installed here. Read the source for site.py for more details.

####

java -Dpython.path=

array in python

In howto, python on January 14, 2008 at 1:13 pm

Two types of array:

1. the array comes with Python.
import array
a=array.array(‘f’,[1,2,3])
aa=a*2 # got array(‘f’,[1.0,2.0,3.0,1.0,2.0,3.0])
print a #not suitable for numerical calculation,http://docs.python.org/lib/module-array.html

2.Numpy (third party modules, need to download from http://numpy.scipy.org
from numpy import *
b=
array([1,2,3])
bb=b*2 # got array([2, 4, 6])

P.S.: the two types can exist simultaneously, but when they are calculated together, the ‘array.array’ will be converted to ‘numpy.array’ automatically.
>>> import numpy
>>> a=numpy.array([1,2,3])
>>> import array
>>> b=array.array(‘f’,[0.1,0.1,0.1])
>>> print a
[1 2 3]
>>> print b
array(‘f’, [0.10000000149011612, 0.10000000149011612, 0.10000000149011612])
>>> c=a+b
>>> print c
[ 1.1 2.1 3.1]

>>> a
array([1, 2, 3])
>>> b
array(‘f’, [0.10000000149011612, 0.10000000149011612, 0.10000000149011612])
>>> c
array([ 1.1, 2.1, 3.1])
>>>

plot in python

In howto, python on January 14, 2008 at 1:12 pm

Here are some examples of ‘matplotlib’, from http://matplotlib.sourceforge.net/tutorial.html

Here is about the simplest script you can use to create a figure with matplotlib

A simple plot

from pylab import *plot([1,2,3,4])show()       

If you are new to python, the first question you are probably asking yourself about this plot is, “Why does the xaxis range from 0-3 and the yaxis from 1-4.” The answer is that if you provide a single list or array to the plot command, matplotlib assumes it a vector of y-values, and automatically generates the x-values for you. Since python ranges start with 0, the default x vector has the same length as your y vector but starts with 0. Hence the x vector is [0,1,2,3]. Of course, if you don’t want the default behavior, you can supply the x data explicitly, as in plot(x,y) where x and y are equal length vectors.

plot is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command

plot([1,2,3,4], [1,4,9,16])

For every x, y pair of arguments, there is a optional third argument which is the format string that indicates the color and line type of the plot. The letters and symbols of the format string are from matlab, and you concatenate a color string with a line style string. The default format string is ‘b-’, which is a solid blue line (don’t ask me, talk to The Mathworks). For example, to plot the above with red circles, you would issue

Using format strings

from pylab import *plot([1,2,3,4], [1,4,9,16], 'ro')axis([0, 6, 0, 20])savefig('secondfig.png')show()

See the plot documentation for a complete list of line styles and format strings. The axis command in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the view port of the axes.

If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example below illustrates a plotting several lines with different format styles in one command using arrays.

Multiple lines with one plot command

from pylab import *t = arange(0.0, 5.2, 0.2)

# red dashes, blue squares and green trianglesplot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')show()

plot in python

In howto, python on January 14, 2008 at 1:12 pm

Here are some examples of ‘matplotlib’, from http://matplotlib.sourceforge.net/tutorial.html

Here is about the simplest script you can use to create a figure with matplotlib

A simple plot

from pylab import *plot([1,2,3,4])show()       

If you are new to python, the first question you are probably asking yourself about this plot is, “Why does the xaxis range from 0-3 and the yaxis from 1-4.” The answer is that if you provide a single list or array to the plot command, matplotlib assumes it a vector of y-values, and automatically generates the x-values for you. Since python ranges start with 0, the default x vector has the same length as your y vector but starts with 0. Hence the x vector is [0,1,2,3]. Of course, if you don’t want the default behavior, you can supply the x data explicitly, as in plot(x,y) where x and y are equal length vectors.

plot is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command

plot([1,2,3,4], [1,4,9,16])

For every x, y pair of arguments, there is a optional third argument which is the format string that indicates the color and line type of the plot. The letters and symbols of the format string are from matlab, and you concatenate a color string with a line style string. The default format string is ‘b-’, which is a solid blue line (don’t ask me, talk to The Mathworks). For example, to plot the above with red circles, you would issue

Using format strings

from pylab import *plot([1,2,3,4], [1,4,9,16], 'ro')axis([0, 6, 0, 20])savefig('secondfig.png')show()

See the plot documentation for a complete list of line styles and format strings. The axis command in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the view port of the axes.

If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example below illustrates a plotting several lines with different format styles in one command using arrays.

Multiple lines with one plot command

from pylab import *t = arange(0.0, 5.2, 0.2)

# red dashes, blue squares and green trianglesplot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')show()

python plot using specific xticks

In howto, python on January 14, 2008 at 1:10 pm

from pylab import *
plot([1,2,3,4])
xlabel(‘x axis’)
xticks( arange(5), (‘Tom’, ‘Dick’, ‘Harry’, ‘Sally’) )
show()

scientific usages using numpy,scipy,matplotlib,ipython

In howto, python on January 14, 2008 at 1:09 pm

Plotting 2-D data (from http://linuxgazette.net/114/andreasen.html)

Example 1: Plotting x,y data

The first example illustrates plotting a 2-D dataset. The data to be plotted is included in the file tgdata.dat and represents weight loss (in wt. %) as a function of time. The plotting routine is in the file tgdata.py and the python code is listed below. Line numbers have been added for readability.

     1  from scipy import *   2   3  data=io.array_import.read_array('tgdata.dat')   4  plotfile='tgdata.png'   5   6  gplt.plot(data[:,0],data[:,1],'title "Weight vs. time" with points')   7  gplt.xtitle('Time [h]')   8  gplt.ytitle('Hydrogen release [wt. %]')   9  gplt.grid("off")  10  gplt.output(plotfile,'png medium transparent picsize 600 400')

To run the code, download the tgdata.py.txt file, rename it to tgdata.py, and run it with python tgdata.py. Besides Python, you also need SciPy and gnuplot installed. Gnuplot version 4.0 was used throughout this article. The output of the program is a plot to screen as shown below. The plot is also saved to disk as tgdata.png per line 4 above.

In line 1, everything from the SciPy module is imported. In order to make use of the various functions of a module, the module needs to be imported by adding an import module-name line to the the python script. In this case it might have been sufficient to import only the gplt package and the io.array_import package. In line 3 the io.array_import package is used to import the data file tgdata.dat into the variable called data as an array with the independent variable stored in column 0 (note that array indices start with 0 as in C unlike Fortran/Octave/Matlab where it starts at 1) and the dependent variable in column 1. In line 4 a variable containing the file name (a string) to which the plot should be stored. In line 6-10 the gplt package is used as an interface to drive gnuplot. Line 6 tells gnuplot to use column 0 as x-values and column 1 as y-values. The notation data[:,0] means: use/print all rows in column 0. On the other hand data[0,:] refers to all columns in the first row.

The gnuplot png option picsize can be a little tricky. The example shown above works when Gnuplot is built with libpng + zlib. If you have Gnuplot built with libgd the required syntax becomes size and the specified width and height should be comma separated.

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

The single import statement (from http://www.scipy.org/PyLab)

What most users want is for a single import statement to get a consistent set of packages which fulfil most of their needs. This should consist of:

from pylab import *

That gets them NumPy, SciPy, and Matplotlib. A rough equivalent would be:

Toggle line numbers
   1 from pylab import *   2 from numpy import *   3 from scipy import *

But there are so many names!

Not really. from scipy import * brings in about 20 subpackages (i.e. signal such that you still need to do signal.ifft, but not scipy.signal.ifft) and only 15 new symbols.

tkinter conflicts with IDLE

In howto, python on January 14, 2008 at 1:05 pm

The code you are told to write will invoke a Tkinter outer loop with root.mainloop(), and yet IDLE itself has already got an outer loop going. And creating two outer loops can keep you from closing Python (read further for solutions).

1.
To summarize, the bottom line is literally this: When using a root.mainloop() as your program’s last command, be ready to “comment it out” (put a # number/pound sign at that line’s beginning) when running from IDLE, and to undo the commenting when booting it outside of IDLE, such as from Windows Explorer.

root.mainloop() #ready to boot directly

# root.mainloop() #ready to run under IDLE

2.
A better solution: In examining newer Tkinter programming examples linked to these pages, including the revised tkex1.py above, you will find a usingIDLE Boolean variable that is set instead of commenting out the root.mainloop() command. This is cleaner and also handier, as it gets used in deciding other factors in how to destroy the top window upon closing, including whether or not the WM_DELETE_WINDOW protocol is employed.
Or:
>>> import sys
>>> for eachPath in sys.path:
if eachPath.find(“idlelib”):
usingIDLE = 1
print ‘find it’

>>> if usingIDLE:
# root.mainloop() # this means don’t run the root.mainloop() for tkinter application.

Just to be clear, understand that this issue is in regard to Ctrl-F5/Running a Tkinter script from IDLE. If you boot a script from the OS or Python command line, or from Windows Explorer, then most of the time it doesn’t seem to matter whether IDLE is also running.

This overall conflict situation appears to be also true with other Tkinter-based environments, such as the IDE that comes with Mac Python.

3.
Another solution: Don’t use root.mainloop() at all, but instead use root.wait_frame(yourToplevelFrame). The first two example scripts on the Tkinter 3D page use this approach, as explained here.

Symbols computing in Python

In howto, python on January 14, 2008 at 1:04 pm

Symbols computing in Python, ( from http://code.google.com/p/sympy)

In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables explicitly:

>>> from sympy import *
>>> x = Symbol(‘x’)
>>> y = Symbol(‘y’)

Then you can play with them:

>>> x+y+x-y
2*x

>>> (x+y)**2
(x+y)**2

>>> ((x+y)**2).expand()
2*x*y+x**2+y**2

>>> c=x**2-3*x+2 # 因式分解
>>> factor(c)
(1 – x)*(2 – x)

Python Tkinter runs without DOS box

In howto, python on January 14, 2008 at 1:03 pm

Name the python file with the extension .pyw, while not py.

Windows users: if you click a .py Python program’s filename in a Windows file explorer to start it (or launch it with os.system), a DOS console box automatically pops up to serve as the program’s standard stream. If your program makes windows of its own, you can avoid this console pop-up window by naming your program’s source-code file with a .pyw extension, not .py. The .pyw extension simply means a .py source file without a DOS pop-up on Windows.

One caveat: in the Python 1.5.2 release, .pyw files can only be run, not imported — the .pyw is not recognized as a module name. If you want a program to both be run without a DOS console pop-up and be importable elsewhere, you need both .py and .pyw files; the .pyw may simply serve as top-level script logic that imports and calls the core logic in the .py. See Section 9.4 in Chapter 9, for an example.

Also note that because printed output goes to this DOS pop-up when a program is clicked, scripts that simply print text and exit will generate an odd “flash” — the DOS console box pops up, output is printed into it, and the pop-up goes immediately away (not the most user-friendly of features!). To keep the DOS pop-up box around so you can read printed output, simply add a raw_input( ) call at the bottom of your script to pause for an Enter key press before exiting.

Python and Matlab call system or executable programs

In howto, python on January 14, 2008 at 1:01 pm

1.Python
command: os.system(‘notepad’)

2. Matlab
command:
winopen(”);
system(”);
unix(”);

Evaluate Python speed (datetime->timedelta)

In howto, python on January 14, 2008 at 1:01 pm

We can evaluate the following script with python and jython to work out which is faster.

import datetime

t1= datetime.datetime.now()

j=0
k=100000
for i in range(1,k):
j=j+i

print # to print a new line

t2= datetime.datetime.now()

tstr=[(t2-t1).seconds,(t2-t1).microseconds] # the attributes of timedelta class: senconds and microseconds, from http://docs.python.org/lib/datetime-timedelta.html#l2h-602
print ‘Accumulated from 1-’,k,’: ‘,j
print tstr

sort within Python

In howto, python on January 14, 2008 at 1:00 pm

1.
a=[15,13,17,11]
b=list(a)
b.sort()
c=list(b)
for i in range(len(b)):
c[i]=a.index(b[i])

print c

-> [3, 1, 0, 2]

2.

a=[15,13,17,11]c=list( [ a[i],i ] for i in range (len(a)) )c.sort()c-> [[11, 3], [13, 1], [15, 0], [17, 2]]

sort within Python

In howto, python on January 14, 2008 at 1:00 pm

1.
a=[15,13,17,11]
b=list(a)
b.sort()
c=list(b)
for i in range(len(b)):
c[i]=a.index(b[i])

print c

-> [3, 1, 0, 2]

2.

a=[15,13,17,11]c=list( [ a[i],i ] for i in range (len(a)) )c.sort()c-> [[11, 3], [13, 1], [15, 0], [17, 2]]

floating point format in Python

In howto, python on January 14, 2008 at 12:59 pm

a=[0.001,0.003,0.002]
a.sort()
print a
-> [0.001, 0.002, 0.0030000000000000001]
import fpformat
b=fpformat.fix(a[2],6)
print b
-> 0.003000
b=fpformat.sci(a[2],2)
print b
-> 3.00e-003

Troubleshooting Sudo

In howto, linux on December 8, 2007 at 1:24 am

I happen to much prefer Ubuntu and Mac OS X’s sudo model to the root/user one that’s typical of most Linux distributions. You can read all about why Ubuntu uses sudo and all the pros and cons of that model at help.ubuntu.com/community/RootSudo.

The one thing I don’t like about sudo is how fragile it is. If you don’t know what you’re doing (especially at the command-line), sometimes sudo can get broken. It doesn’t happen very often, but it does happen. That’s what this page is for.

If your sudo is “broken,” meaning that you can’t use the sudo command to temporarily gain administrative privileges, there are two files you should be aware of:

/etc/sudoers and /etc/group

The /etc/sudoers file should look the same for every Ubuntu user who hasn’t fiddled with it:

# /etc/sudoers

#

# This file MUST be edited with the ‘visudo’ command as root.

#

# See the man page for details on how to write a sudoers file.

#

# Host alias specification

# User alias specification

# Cmnd alias specification

# Defaults

Defaults !lecture,tty_tickets,!fqdn

# User privilege specification

root ALL=(ALL) ALL

# Members of the admin group may gain root privileges

%admin ALL=(ALL) ALL

It basically says anyone who is root can do anything, and anyone in the administrative group (people who can sudo) can do anything (with a password).

Now, the /etc/group file will look different for every Ubuntu
installation. It specifies which groups each user belongs to. An
example of how it might look is here:

root:x:0:

daemon:x:1:

bin:x:2:

sys:x:3:

adm:x:4:firstuser

tty:x:5:

disk:x:6:

lp:x:7:cupsys

mail:x:8:

news:x:9:

uucp:x:10:

man:x:12:

proxy:x:13:

kmem:x:15:

dialout:x:20:firstuser,cupsys

fax:x:21:

voice:x:22:

cdrom:x:24:firstuser,haldaemon

floppy:x:25:firstuser,haldaemon

tape:x:26:

sudo:x:27:

audio:x:29:firstuser

dip:x:30:firstuser

www-data:x:33:

backup:x:34:

operator:x:37:

list:x:38:

irc:x:39:

src:x:40:

gnats:x:41:

shadow:x:42:

utmp:x:43:

video:x:44:firstuser

sasl:x:45:

plugdev:x:46:firstuser,haldaemon

staff:x:50:

games:x:60:

users:x:100:

nogroup:x:65534:

dhcp:x:101:

syslog:x:102:

klog:x:103:

firstuser :x :1000:

lpadmin:x:104:firstuser

scanner:x:105:firstuser,cupsys

admin:x:106:firstuser

crontab:x:107:

ssh:x:108:

messagebus:x:109:

haldaemon:x:110:

slocate:x:111:

For troubleshooting purposes, the most important line in the /etc/group file is the one in bold, which specifies who is in the admin group, and hence who has sudo privileges. Substitute your actual username for firstuser, of course.

Now, this begs the question, “How can I edit the /etc/group file if I don’t have sudo permissions?”

The answer is something called recovery mode.

Free Image Hosting at www.ImageShack.us Free Image Hosting at www.ImageShack.us

You know when you boot up, you get several options for how you want to
boot up? There’s usually a kernel, recovery mode, and memtest at the
very least.

After you boot into recovery mode, you should be logged in as
root. Or, if you set a root password in your installation, you’ll be
prompted for your root password. Either way–password or not–you’ll
end up logged in as root.


Once
you’re there, before you make any changes, it’s a good idea to make
backup copies of your two corrupt files. Sure, they’re incorrect, but
they’re better than nothing, especially if you accidentally delete the
contents of the original files. To back them up, type

cp /etc/group /etc/group.old

cp /etc/sudoers /etc/sudoers.old

Then, to edit the files, use these commands:

sudo visudo

This command edits the /etc/sudoers file.

nano /etc/group

This command edits the /etc/group file.

To save in nano, you press Control-X (save), Y (confirm), and Enter (exit).

If you don’t want to bother editing the /etc/group file, you can also issue this command:

adduser username admin

That one command will add user username to the admin group so you can sudo

If you are trying to fix the error where it says sudo is mode _____, should be 0440, then you’ll want to type

chmod 0440 /etc/sudoers

When you’re done, reboot, and you should be able to sudo again.

Powered by ScribeFire.

Troubleshooting Sudo

In howto, linux on December 8, 2007 at 1:24 am

I happen to much prefer Ubuntu and Mac OS X’s sudo model to the root/user one that’s typical of most Linux distributions. You can read all about why Ubuntu uses sudo and all the pros and cons of that model at help.ubuntu.com/community/RootSudo.

The one thing I don’t like about sudo is how fragile it is. If you don’t know what you’re doing (especially at the command-line), sometimes sudo can get broken. It doesn’t happen very often, but it does happen. That’s what this page is for.

If your sudo is “broken,” meaning that you can’t use the sudo command to temporarily gain administrative privileges, there are two files you should be aware of:

/etc/sudoers and /etc/group

The /etc/sudoers file should look the same for every Ubuntu user who hasn’t fiddled with it:

# /etc/sudoers

#

# This file MUST be edited with the ‘visudo’ command as root.

#

# See the man page for details on how to write a sudoers file.

#

# Host alias specification

# User alias specification

# Cmnd alias specification

# Defaults

Defaults !lecture,tty_tickets,!fqdn

# User privilege specification

root ALL=(ALL) ALL

# Members of the admin group may gain root privileges

%admin ALL=(ALL) ALL

It basically says anyone who is root can do anything, and anyone in the administrative group (people who can sudo) can do anything (with a password).

Now, the /etc/group file will look different for every Ubuntu
installation. It specifies which groups each user belongs to. An
example of how it might look is here:

root:x:0:

daemon:x:1:

bin:x:2:

sys:x:3:

adm:x:4:firstuser

tty:x:5:

disk:x:6:

lp:x:7:cupsys

mail:x:8:

news:x:9:

uucp:x:10:

man:x:12:

proxy:x:13:

kmem:x:15:

dialout:x:20:firstuser,cupsys

fax:x:21:

voice:x:22:

cdrom:x:24:firstuser,haldaemon

floppy:x:25:firstuser,haldaemon

tape:x:26:

sudo:x:27:

audio:x:29:firstuser

dip:x:30:firstuser

www-data:x:33:

backup:x:34:

operator:x:37:

list:x:38:

irc:x:39:

src:x:40:

gnats:x:41:

shadow:x:42:

utmp:x:43:

video:x:44:firstuser

sasl:x:45:

plugdev:x:46:firstuser,haldaemon

staff:x:50:

games:x:60:

users:x:100:

nogroup:x:65534:

dhcp:x:101:

syslog:x:102:

klog:x:103:

firstuser :x :1000:

lpadmin:x:104:firstuser

scanner:x:105:firstuser,cupsys

admin:x:106:firstuser

crontab:x:107:

ssh:x:108:

messagebus:x:109:

haldaemon:x:110:

slocate:x:111:

For troubleshooting purposes, the most important line in the /etc/group file is the one in bold, which specifies who is in the admin group, and hence who has sudo privileges. Substitute your actual username for firstuser, of course.

Now, this begs the question, “How can I edit the /etc/group file if I don’t have sudo permissions?”

The answer is something called recovery mode.

Free Image Hosting at www.ImageShack.us Free Image Hosting at www.ImageShack.us

You know when you boot up, you get several options for how you want to
boot up? There’s usually a kernel, recovery mode, and memtest at the
very least.

After you boot into recovery mode, you should be logged in as
root. Or, if you set a root password in your installation, you’ll be
prompted for your root password. Either way–password or not–you’ll
end up logged in as root.


Once
you’re there, before you make any changes, it’s a good idea to make
backup copies of your two corrupt files. Sure, they’re incorrect, but
they’re better than nothing, especially if you accidentally delete the
contents of the original files. To back them up, type

cp /etc/group /etc/group.old

cp /etc/sudoers /etc/sudoers.old

Then, to edit the files, use these commands:

sudo visudo

This command edits the /etc/sudoers file.

nano /etc/group

This command edits the /etc/group file.

To save in nano, you press Control-X (save), Y (confirm), and Enter (exit).

If you don’t want to bother editing the /etc/group file, you can also issue this command:

adduser username admin

That one command will add user username to the admin group so you can sudo

If you are trying to fix the error where it says sudo is mode _____, should be 0440, then you’ll want to type

chmod 0440 /etc/sudoers

When you’re done, reboot, and you should be able to sudo again.

Powered by ScribeFire.

two ways to make a user sudo

In howto, linux on December 8, 2007 at 12:32 am

$sudo adduser laser admin
sudo adduser laser sudo, here ’sudo’ can not make the user run sudo ability.

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

if group admin doesn’t exist, you should edit /etc/sudoers

login with root, if no root, run “passwd root” to create one.

$vi /etc/sudoers

cp the last line of “root ALL……”, paste it at the next line and change the root to your name. Done.

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

If you’ve used Linux for any amount of time, you might be used to
running programs as root directly whenever you need to install
packages, modify your system’s configuration, and so on. Ubuntu employs
a different model, however. The Ubuntu installer doesn’t set up a root
user — a root account still exists, but it’s set with a random
password. Users are meant to do administration tasks using sudo and
gksudo.

You probably already know how to use sudo — just run sudo commandname .
But what about running GUI apps that you want to run as root (or
another user)? Simple — use gksudo instead of sudo. For instance, if
you’d like to run Ethereal as root, just pop open a run dialog box (Alt-F2) and use gksudo ethereal.

By the way, if you really must do work as root, you can use sudo su -,
which will log you in as root. If you really, really want to have a
root password that you know, so that you can log in as root directly
(i.e., without using sudo), then run passwd when logged
in as root, and set the password to whatever you want. I’d recommend
using the pwgen package to create a secure password not only for root
but for all your user accounts.

Powered by ScribeFire.

Top/free的使用及参数详解

In Blogged, howto, linux on December 5, 2007 at 11:52 pm

1.作用

top命令用来显示执行中的程序进程,使用权限是所有用户。

2.格式

top [-] [d delay] [q] [c] [S] [s] [i] [n]

3.主要参数

d:指定更新的间隔,以秒计算。

q:没有任何延迟的更新。如果使用者有超级用户,则top命令将会以最高的优先序执行。

c:显示进程完整的路径与名称。

S:累积模式,会将己完成或消失的子行程的CPU时间累积起来。

s:安全模式。

i:不显示任何闲置(Idle)或无用(Zombie)的行程。

n:显示更新的次数,完成后将会退出top。

4.说明

top命令是Linux系统管理的一个主要命令,通过它可以获得许多信息。这里我们结合图1来说明它给出的信息。

top命令的显示 (图略)

第一行表示的项目依次为当前时间、系统运行时间、当前系统登录用户数目、1/5/10分钟系统平均负载(一般来说,这个负载值应该不太可能超过 1 才对,除非您的系统很忙碌。 如果持续高于 5 的话,那么…..仔细的看看到底是那个程序在影响整体系统吧!)。

第二行显示的是所有启动的进程、目前运行、挂起 (Sleeping)的和无用(Zombie)的进程。(比较需要注意的是最后的 zombie 那个数值,如果不是 0 ,嘿嘿!好好看看到底是那个 process 变成疆尸了吧?!)(stop模式:与sleep进程应区别,sleep会主动放弃cpu,而stop是被动放弃cpu ,例单步跟踪,stop(暂停)的进程是无法自己回到运行状态的)

第三行显示的是目前CPU的使用情况,包括us用户空间占用CPU百分比、sy 内核空间占用CPU百分比、ni 用户进程空间内改变过优先级的进程占用CPU百分比(中断处理占用)、id 空闲CPU百分比、wa 等待输入输出的CPU时间百分比、hi,si,st 三者的意思目录还不清楚 :)

第四行显示物理内存的使用情况,包括总的可以使用的内存、已用内存、空闲内存、缓冲区占用的内存。

第五行显示交换分区使用情况,包括总的交换分区、使用的、空闲的和用于高速缓存的大小。

第六行显示的项目最多,下面列出了详细解释。

PID(Process ID):进程标示号 ( 每个 process 的 ID )

USER:进程所有者的用户名 ( 该 process 所属的使用者 )

PR:进程的优先级别 ( Priority 的简写,程序的优先执行顺序,越小越早被执行 )

NI:进程的优先级别数值 ( Nice 的简写,与 Priority 有关,也是越小越早被执行 )

VIRT:进程占用的虚拟内存值。

RES:进程占用的物理内存值。

SHR:进程使用的共享内存值。

S:进程的状态,其中S表示休眠,R表示正在运行,Z表示僵死状态,N表示该进程优先值是负数。

%CPU:该进程占用的CPU使用率。

%MEM:该进程占用的物理内存和总内存的百分比。

TIME+:该进程启动后占用的总的CPU时间 ( CPU 使用时间的累加 )

Command:进程启动的启动命令名称,如果这一行显示不下,进程会有一个完整的命令行。

top命令使用过程中,还可以使用一些交互的命令来完成其它参数的功能。这些命令是通过快捷键启动的。

<空格>:立刻刷新。

P:根据CPU使用大小进行排序。

T:根据时间、累计时间排序。

q:退出top命令。

m:切换显示内存信息。

t:切换显示进程和CPU状态信息。

c:切换显示命令名称和完整命令行。

M:根据使用内存大小进行排序。

W:将当前设置写入~/.toprc文件中。这是写top配置文件的推荐方法。

可以看到,top命令是一个功能十分强大的监控系统的工具,对于系统管理员而言尤其重要。但是,它的缺点是会消耗很多系统资源。

5.应用实例

使用top命令可以监视指定用户,缺省情况是监视所有用户的进程。如果想查看指定用户的情况,在终端中按“U”键,然后输入用户名,系统就会切换为指定用户的进程运行界面,见图2所示。

a.作用

free命令用来显示内存的使用情况,使用权限是所有用户。

b.格式

free [-b|-k|-m] [-o] [-s delay] [-t] [-V]

c.主要参数

-b -k -m:分别以字节(KB、MB)为单位显示内存使用情况。

-s delay:显示每隔多少秒数来显示一次内存使用情况。

-t:显示内存总和列。

-o:不显示缓冲区调节列。

d.应用实例

free命令是用来查看内存使用情况的主要命令。和top命令相比,它的优点是使用简单,并且只占用很少的系统资源。通过-S参数可以使用free命令不间断地监视有多少内存在使用,这样可以把它当作一个方便实时监控器。

#free -b -s5

使用这个命令后终端会连续不断地报告内存使用情况(以字节为单位),每5秒更新一次。

Top/free的使用及参数详解

In Blogged, howto, linux on December 5, 2007 at 11:52 pm

1.作用

top命令用来显示执行中的程序进程,使用权限是所有用户。

2.格式

top [-] [d delay] [q] [c] [S] [s] [i] [n]

3.主要参数

d:指定更新的间隔,以秒计算。

q:没有任何延迟的更新。如果使用者有超级用户,则top命令将会以最高的优先序执行。

c:显示进程完整的路径与名称。

S:累积模式,会将己完成或消失的子行程的CPU时间累积起来。

s:安全模式。

i:不显示任何闲置(Idle)或无用(Zombie)的行程。

n:显示更新的次数,完成后将会退出top。

4.说明

top命令是Linux系统管理的一个主要命令,通过它可以获得许多信息。这里我们结合图1来说明它给出的信息。

top命令的显示 (图略)

第一行表示的项目依次为当前时间、系统运行时间、当前系统登录用户数目、1/5/10分钟系统平均负载(一般来说,这个负载值应该不太可能超过 1 才对,除非您的系统很忙碌。 如果持续高于 5 的话,那么…..仔细的看看到底是那个程序在影响整体系统吧!)。

第二行显示的是所有启动的进程、目前运行、挂起 (Sleeping)的和无用(Zombie)的进程。(比较需要注意的是最后的 zombie 那个数值,如果不是 0 ,嘿嘿!好好看看到底是那个 process 变成疆尸了吧?!)(stop模式:与sleep进程应区别,sleep会主动放弃cpu,而stop是被动放弃cpu ,例单步跟踪,stop(暂停)的进程是无法自己回到运行状态的)

第三行显示的是目前CPU的使用情况,包括us用户空间占用CPU百分比、sy 内核空间占用CPU百分比、ni 用户进程空间内改变过优先级的进程占用CPU百分比(中断处理占用)、id 空闲CPU百分比、wa 等待输入输出的CPU时间百分比、hi,si,st 三者的意思目录还不清楚 :)

第四行显示物理内存的使用情况,包括总的可以使用的内存、已用内存、空闲内存、缓冲区占用的内存。

第五行显示交换分区使用情况,包括总的交换分区、使用的、空闲的和用于高速缓存的大小。

第六行显示的项目最多,下面列出了详细解释。

PID(Process ID):进程标示号 ( 每个 process 的 ID )

USER:进程所有者的用户名 ( 该 process 所属的使用者 )

PR:进程的优先级别 ( Priority 的简写,程序的优先执行顺序,越小越早被执行 )

NI:进程的优先级别数值 ( Nice 的简写,与 Priority 有关,也是越小越早被执行 )

VIRT:进程占用的虚拟内存值。

RES:进程占用的物理内存值。

SHR:进程使用的共享内存值。

S:进程的状态,其中S表示休眠,R表示正在运行,Z表示僵死状态,N表示该进程优先值是负数。

%CPU:该进程占用的CPU使用率。

%MEM:该进程占用的物理内存和总内存的百分比。

TIME+:该进程启动后占用的总的CPU时间 ( CPU 使用时间的累加 )

Command:进程启动的启动命令名称,如果这一行显示不下,进程会有一个完整的命令行。

top命令使用过程中,还可以使用一些交互的命令来完成其它参数的功能。这些命令是通过快捷键启动的。

<空格>:立刻刷新。

P:根据CPU使用大小进行排序。

T:根据时间、累计时间排序。

q:退出top命令。

m:切换显示内存信息。

t:切换显示进程和CPU状态信息。

c:切换显示命令名称和完整命令行。

M:根据使用内存大小进行排序。

W:将当前设置写入~/.toprc文件中。这是写top配置文件的推荐方法。

可以看到,top命令是一个功能十分强大的监控系统的工具,对于系统管理员而言尤其重要。但是,它的缺点是会消耗很多系统资源。

5.应用实例

使用top命令可以监视指定用户,缺省情况是监视所有用户的进程。如果想查看指定用户的情况,在终端中按“U”键,然后输入用户名,系统就会切换为指定用户的进程运行界面,见图2所示。

a.作用

free命令用来显示内存的使用情况,使用权限是所有用户。

b.格式

free [-b|-k|-m] [-o] [-s delay] [-t] [-V]

c.主要参数

-b -k -m:分别以字节(KB、MB)为单位显示内存使用情况。

-s delay:显示每隔多少秒数来显示一次内存使用情况。

-t:显示内存总和列。

-o:不显示缓冲区调节列。

d.应用实例

free命令是用来查看内存使用情况的主要命令。和top命令相比,它的优点是使用简单,并且只占用很少的系统资源。通过-S参数可以使用free命令不间断地监视有多少内存在使用,这样可以把它当作一个方便实时监控器。

#free -b -s5

使用这个命令后终端会连续不断地报告内存使用情况(以字节为单位),每5秒更新一次。

解读Linux操作系统内核源码的好方法

In Blogged, howto, linux on December 5, 2007 at 11:50 pm

针对好多Linux 爱好者对内核很有兴趣却无从下口,本文旨在介绍一种解读linux内核源码的入门方法,而不是解说linux复杂的内核机制;

一.核心源程序的文件组织:

1.Linux核心源程序通常都安装在/usr/src/linux下,而且它有一个非常简单的编号约定:任何偶数的核心(例如2.0.30)都是一个稳定地发行的核心,而任何奇数的核心(例如2.1.42)都是一个开发中的核心。

本文基于稳定的2.2.5源代码,第二部分的实现平台为 Redhat Linux 6.0。

2.核心源程序的文件按树形结构进行组织,在源程序树的最上层你会看到这样一些目录:

●Arch :arch子目录包括了所有和体系结构相关的核心代码。它的每一个子目录都代表一种支持的体系结构,例如i386就是关于intel

cpu及与之相兼容体系结构的子目录。PC机一般都基于此目录;

●Include: include子目录包括编译核心所需要的大部分头文件。与平台无关的头文件在 include/linux子目录下,与 intel

cpu相关的头文件在include/asm-i386子目录下,而include/scsi目录则是有关scsi设备的头文件目录;

●Init: 这个目录包含核心的初始化代码(注:不是系统的引导代码),包含两个文件main.c和Version.c,这是研究核心如何工作的一个非常好的起点。

●Mm :这个目录包括所有独立于 cpu

体系结构的内存管理代码,如页式存储管理内存的分配和释放等;而和体系结构相关的内存管理代码则位于arch/*/mm/,例如arch/i386/mm/Fault.c

●Kernel:主要的核心代码,此目录下的文件实现了大多数linux系统的内核函数,其中最重要的文件当属sched.c;同样,和体系结构相关的代码在arch/*/kernel中;

●Drivers: 放置系统所有的设备驱动程序;每种驱动程序又各占用一个子目录:如,/block

下为块设备驱动程序,比如ide(ide.c)。如果你希望查看所有可能包含文件系 统的设备是如何初始化的,你可以看drivers/block/genhd.c中的device_setup()。它不仅初始化硬盘,也初始化网络,因为 安装nfs文件系统的时候需要网络其他:

如, Lib放置核心的库代码; Net,核心与网络相关的代码; Ipc,这个目录包含核心的进程间通讯的代码; Fs

,所有的文件系统代码和各种类型的文件操作代码,它的每一个子目录支持一个文件系统,例如fat和ext2;

Scripts, 此目录包含用于配置核心的脚本文件等。

一般,在每个目录下,都有一个 .depend 文件和一个 Makefile

文件,这两个文件都是编译时使用的辅助文件,仔细阅读这两个文件对弄清各个文件这间的联系和依托关系很有帮助;而且,在有的目录下还有Readme

文件,它是对该目录下的文件的一些说明,同样有利于我们对内核源码的理解;

二.解读实战:为你的内核增加一个系统调用

虽然,Linux 的内核源码用树形结构组织得非常合理、科学,把功能相关联的文件都放在同一个子目录下,这样使得程序更具可读性。然而,Linux

的内核源码实在是太大而且非常复杂,即便采用了很合理的文件组织方法,在不同目录下的文件之间还是有很多的关联,分析核心的一部分代码通常会要查看其它的几个相关的文件,而且可能这些文件还不在同一个子目录下。

体系的庞大复杂和文件之间关联的错综复杂,可能就是很多人对其望而生畏的主要原因。 当然,这种令人生畏的劳动所带来的回报也是非常令人着迷的:你不仅可以从中学到很多的计算机的底层的知识(如下面将讲到的系统的引导),体会到整个操作系 统体系结构的精妙和在解决某个具体细节问题时,算法的巧妙;而且更重要的是:在源码的分析过程中,你就会被一点一点地、潜移默化地专业化;甚至,只要分析 十分之一的代码后,你就会深刻地体会到,什么样的代码才是一个专业的程序员写的,什么样的代码是一个业余爱好者写的。

为了使读者能更好的体会到这一特点,下面举了一个具体的内核分析实例,希望能通过这个实例,使读者对Linux的内核的组织有些具体的认识,从中读者也可以学到一些对内核的分析方法。

以下即为分析实例:

A、操作平台:

硬件:cpu intel Pentium II ;

软件:Redhat Linux 6.0; 内核版本2.2.5

B、相关内核源代码分析:

1.系统的引导和初始化:Linux 系统的引导有好几种方式:常见的有 Lilo,

Loadin引导和Linux的自举引导(bootsect-loader),而后者所对应源程序为arch/i386/boot/bootsect.S,它为实模式的汇编程序,限于篇幅在此不做分析;无论是哪种引导方式,最后都要跳转到

arch/i386/Kernel/setup.S, setup.S主要是进行时模式下的初始化,为系统进入保护模式做准备;此后,系统执行

arch/i386/kernel/head.S (对经压缩后存放的内核要先执行 arch/i386/boot/compressed/head.S);

head.S 中定义的一段汇编程序setup_idt ,它负责建立一张256项的 idt 表(Interrupt Descriptor

Table),此表保存着所有自陷和中断的入口地址;其中包括系统调用总控程序 system_call

的入口地址;当然,除此之外,head.S还要做一些其他的初始化工作;

2.系统初始化后运行的第一个内核程序asmlinkage void __init start_kernel(void) 定义在

/usr/src/linux/init/main.c中,它通过调用usr/src/linux/arch/i386/kernel/traps.c 中的一个函数

void __init trap_init(void) 把各自陷和中断服务程序的入口地址设置到 idt

表中,其中系统调用总控程序system_cal就是中断服务程序之一;void __init trap_init(void) 函数则通过调用一个宏

set_system_gate(SYSCALL_VECTOR,&system_call); 把系统调用总控程序的入口挂在中断0×80上;

其中SYSCALL_VECTOR是定义在 /usr/src/linux/arch/i386/kernel/irq.h中的一个常量0×80; 而

system_call

即为中断总控程序的入口地址;中断总控程序用汇编语言定义在/usr/src/linux/arch/i386/kernel/entry.S中;

3.中断总控程序主要负责保存处理机执行系统调用前的状态,检验当前调用是否合法, 并根据系统调用向量,使处理机跳转到保存在 sys_call_table

表中的相应系统服务例程的入口; 从系统服务例程返回后恢复处理机状态退回用户程序;

而系统调用向量则定义在/usr/src/linux/include/asm-386/unistd.h 中;sys_call_table

表定义在/usr/src/linux/arch/i386/kernel/entry.S 中; 同时在

/usr/src/linux/include/asm-386/unistd.h 中也定义了系统调用的用户编程接口;

4.由此可见 , linux 的系统调用也象 dos 系统的 int 21h 中断服务, 它把0×80 中断作为总的入口, 然后转到保存在

sys_call_table 表中的各种中断服务例程的入口地址 , 形成各种不同的中断服务;

由以上源代码分析可知, 要增加一个系统调用就必须在 sys_call_table 表中增加一项 ,

并在其中保存好自己的系统服务例程的入口地址,然后重新编译内核,当然,系统服务例程是必不可少的。

由此可知在此版linux内核源程序中,与系统调用相关的源程序文件就包括以下这些:

arch/i386/boot/bootsect.S

arch/i386/Kernel/setup.S

arch/i386/boot/compressed/head.S

arch/i386/kernel/head.S

init/main.c

arch/i386/kernel/traps.c

arch/i386/kernel/entry.S

arch/i386/kernel/irq.h

include/asm-386/unistd.h

当然,这只是涉及到的几个主要文件。而事实上,增加系统调用真正要修改文件只有include/asm-386/unistd.h和arch/i386/kernel/entry.S两个。

C、对内核源码的修改:

1.在kernel/sys.c中增加系统服务例程如下:

asmlinkage int sys_addtotal(int numdata)

{

int i=0,enddata=0;

while(i<=numdata)

enddata+=i++;

return enddata;

}

该函数有一个 int 型入口参数 numdata , 并返回从 0 到 numdata 的累加值;

当然也可以把系统服务例程放在一个自己定义的文件或其他文件中,只是要在相应文件中作必要的说明;

2.把 asmlinkage int sys_addtotal( int) 的入口地址加到sys_call_table表中:

arch/i386/kernel/entry.S 中的最后几行源代码修改前为:

… …

.long SYMBOL_NAME(sys_sendfile)

.long SYMBOL_NAME(sys_ni_syscall) /* streams1 */

.long SYMBOL_NAME(sys_ni_syscall) /* streams2 */

.long SYMBOL_NAME(sys_vfork) /* 190 */

.rept NR_syscalls-190

.long SYMBOL_NAME(sys_ni_syscall)

.endr

修改后为: … …

.long SYMBOL_NAME(sys_sendfile)

.long SYMBOL_NAME(sys_ni_syscall) /* streams1 */

.long SYMBOL_NAME(sys_ni_syscall) /* streams2 */

.long SYMBOL_NAME(sys_vfork) /* 190 */

/* add by I */

.long SYMBOL_NAME(sys_addtotal)

.rept NR_syscalls-191

.long SYMBOL_NAME(sys_ni_syscall)

.endr

3. 把增加的 sys_call_table 表项所对应的向量,在include/asm-386/unistd.h

中进行必要申明,以供用户进程和其他系统进程查询或调用:

增加后的部分 /usr/src/linux/include/asm-386/unistd.h 文件如下:

… …

#define __NR_sendfile 187

#define __NR_getpmsg 188

#define __NR_putpmsg 189

#define __NR_vfork 190

/* add by I */

#define __NR_addtotal 191

4.测试程序(test.c)如下:

#include

#include

_syscall1(int,addtotal,int, num)

main()

{

int i,j;

do

printf(“Please input a number\n”);

while(scanf(“%d”,&i)==EOF);

if((j=addtotal(i))==-1)

printf(“Error occurred in syscall-addtotal();\n”);

printf(“Total from 0 to %d is %d \n”,i,j);

}

对修改后的新的内核进行编译,并引导它作为新的操作系统,运行几个程序后可以发现一切正常;在新的系统下对测试程序进行编译(*注:由于原内核并未提供此系统调用,所以只有在编译后的新内核下,此测试程序才能可能被编译通过),运行情况如下:

$gcc -o test test.c

$./test

Please input a number

36

Total from 0 to 36 is 666

可见,修改成功;

而且,对相关源码的进一步分析可知,在此版本的内核中,从/usr/src/linux/arch/i386/kernel/entry.S

文件中对 sys_call_table 表的设置可以看出,有好几个系统调用的服务例程都是定义在/usr/src/linux/kernel/sys.c

中的同一个函数:

asmlinkage int sys_ni_syscall(void)

{

return -ENOSYS;

}

例如第188项和第189项就是如此:

… …

.long SYMBOL_NAME(sys_sendfile)

.long SYMBOL_NAME(sys_ni_syscall) /* streams1 */

.long SYMBOL_NAME(sys_ni_syscall) /* streams2 */

.long SYMBOL_NAME(sys_vfork) /* 190 */

… …

而这两项在文件 /usr/src/linux/include/asm-386/unistd.h 中却申明如下:

… …

#define __NR_sendfile 187

#define __NR_getpmsg 188 /* some people actually want streams */

#define __NR_putpmsg 189 /* some people actually want streams */

#define __NR_vfork 190

由此可见,在此版本的内核源代码中,由于asmlinkage int sys_ni_syscall(void) 函数并不进行任何操作,所以包括 getpmsg,

putpmsg 在内的好几个系统调用都是不进行任何操作的,即有待扩充的空调用;

但它们却仍然占用着sys_call_table表项,估计这是设计者们为了方便扩充系统调用而安排的;

所以只需增加相应服务例程(如增加服务例程getmsg或putpmsg),就可以达到增加系统调用的作用。

解读Linux操作系统内核源码的好方法

In Blogged, howto, linux on December 5, 2007 at 11:50 pm

针对好多Linux 爱好者对内核很有兴趣却无从下口,本文旨在介绍一种解读linux内核源码的入门方法,而不是解说linux复杂的内核机制;

一.核心源程序的文件组织:

1.Linux核心源程序通常都安装在/usr/src/linux下,而且它有一个非常简单的编号约定:任何偶数的核心(例如2.0.30)都是一个稳定地发行的核心,而任何奇数的核心(例如2.1.42)都是一个开发中的核心。

本文基于稳定的2.2.5源代码,第二部分的实现平台为 Redhat Linux 6.0。

2.核心源程序的文件按树形结构进行组织,在源程序树的最上层你会看到这样一些目录:

●Arch :arch子目录包括了所有和体系结构相关的核心代码。它的每一个子目录都代表一种支持的体系结构,例如i386就是关于intel

cpu及与之相兼容体系结构的子目录。PC机一般都基于此目录;

●Include: include子目录包括编译核心所需要的大部分头文件。与平台无关的头文件在 include/linux子目录下,与 intel

cpu相关的头文件在include/asm-i386子目录下,而include/scsi目录则是有关scsi设备的头文件目录;

●Init: 这个目录包含核心的初始化代码(注:不是系统的引导代码),包含两个文件main.c和Version.c,这是研究核心如何工作的一个非常好的起点。

●Mm :这个目录包括所有独立于 cpu

体系结构的内存管理代码,如页式存储管理内存的分配和释放等;而和体系结构相关的内存管理代码则位于arch/*/mm/,例如arch/i386/mm/Fault.c

●Kernel:主要的核心代码,此目录下的文件实现了大多数linux系统的内核函数,其中最重要的文件当属sched.c;同样,和体系结构相关的代码在arch/*/kernel中;

●Drivers: 放置系统所有的设备驱动程序;每种驱动程序又各占用一个子目录:如,/block

下为块设备驱动程序,比如ide(ide.c)。如果你希望查看所有可能包含文件系 统的设备是如何初始化的,你可以看drivers/block/genhd.c中的device_setup()。它不仅初始化硬盘,也初始化网络,因为 安装nfs文件系统的时候需要网络其他:

如, Lib放置核心的库代码; Net,核心与网络相关的代码; Ipc,这个目录包含核心的进程间通讯的代码; Fs

,所有的文件系统代码和各种类型的文件操作代码,它的每一个子目录支持一个文件系统,例如fat和ext2;

Scripts, 此目录包含用于配置核心的脚本文件等。

一般,在每个目录下,都有一个 .depend 文件和一个 Makefile

文件,这两个文件都是编译时使用的辅助文件,仔细阅读这两个文件对弄清各个文件这间的联系和依托关系很有帮助;而且,在有的目录下还有Readme

文件,它是对该目录下的文件的一些说明,同样有利于我们对内核源码的理解;

二.解读实战:为你的内核增加一个系统调用

虽然,Linux 的内核源码用树形结构组织得非常合理、科学,把功能相关联的文件都放在同一个子目录下,这样使得程序更具可读性。然而,Linux

的内核源码实在是太大而且非常复杂,即便采用了很合理的文件组织方法,在不同目录下的文件之间还是有很多的关联,分析核心的一部分代码通常会要查看其它的几个相关的文件,而且可能这些文件还不在同一个子目录下。

体系的庞大复杂和文件之间关联的错综复杂,可能就是很多人对其望而生畏的主要原因。 当然,这种令人生畏的劳动所带来的回报也是非常令人着迷的:你不仅可以从中学到很多的计算机的底层的知识(如下面将讲到的系统的引导),体会到整个操作系 统体系结构的精妙和在解决某个具体细节问题时,算法的巧妙;而且更重要的是:在源码的分析过程中,你就会被一点一点地、潜移默化地专业化;甚至,只要分析 十分之一的代码后,你就会深刻地体会到,什么样的代码才是一个专业的程序员写的,什么样的代码是一个业余爱好者写的。

为了使读者能更好的体会到这一特点,下面举了一个具体的内核分析实例,希望能通过这个实例,使读者对Linux的内核的组织有些具体的认识,从中读者也可以学到一些对内核的分析方法。

以下即为分析实例:

A、操作平台:

硬件:cpu intel Pentium II ;

软件:Redhat Linux 6.0; 内核版本2.2.5

B、相关内核源代码分析:

1.系统的引导和初始化:Linux 系统的引导有好几种方式:常见的有 Lilo,

Loadin引导和Linux的自举引导(bootsect-loader),而后者所对应源程序为arch/i386/boot/bootsect.S,它为实模式的汇编程序,限于篇幅在此不做分析;无论是哪种引导方式,最后都要跳转到

arch/i386/Kernel/setup.S, setup.S主要是进行时模式下的初始化,为系统进入保护模式做准备;此后,系统执行

arch/i386/kernel/head.S (对经压缩后存放的内核要先执行 arch/i386/boot/compressed/head.S);

head.S 中定义的一段汇编程序setup_idt ,它负责建立一张256项的 idt 表(Interrupt Descriptor

Table),此表保存着所有自陷和中断的入口地址;其中包括系统调用总控程序 system_call

的入口地址;当然,除此之外,head.S还要做一些其他的初始化工作;

2.系统初始化后运行的第一个内核程序asmlinkage void __init start_kernel(void) 定义在

/usr/src/linux/init/main.c中,它通过调用usr/src/linux/arch/i386/kernel/traps.c 中的一个函数

void __init trap_init(void) 把各自陷和中断服务程序的入口地址设置到 idt

表中,其中系统调用总控程序system_cal就是中断服务程序之一;void __init trap_init(void) 函数则通过调用一个宏

set_system_gate(SYSCALL_VECTOR,&system_call); 把系统调用总控程序的入口挂在中断0×80上;

其中SYSCALL_VECTOR是定义在 /usr/src/linux/arch/i386/kernel/irq.h中的一个常量0×80; 而

system_call

即为中断总控程序的入口地址;中断总控程序用汇编语言定义在/usr/src/linux/arch/i386/kernel/entry.S中;

3.中断总控程序主要负责保存处理机执行系统调用前的状态,检验当前调用是否合法, 并根据系统调用向量,使处理机跳转到保存在 sys_call_table

表中的相应系统服务例程的入口; 从系统服务例程返回后恢复处理机状态退回用户程序;

而系统调用向量则定义在/usr/src/linux/include/asm-386/unistd.h 中;sys_call_table

表定义在/usr/src/linux/arch/i386/kernel/entry.S 中; 同时在

/usr/src/linux/include/asm-386/unistd.h 中也定义了系统调用的用户编程接口;

4.由此可见 , linux 的系统调用也象 dos 系统的 int 21h 中断服务, 它把0×80 中断作为总的入口, 然后转到保存在

sys_call_table 表中的各种中断服务例程的入口地址 , 形成各种不同的中断服务;

由以上源代码分析可知, 要增加一个系统调用就必须在 sys_call_table 表中增加一项 ,

并在其中保存好自己的系统服务例程的入口地址,然后重新编译内核,当然,系统服务例程是必不可少的。

由此可知在此版linux内核源程序中,与系统调用相关的源程序文件就包括以下这些:

arch/i386/boot/bootsect.S

arch/i386/Kernel/setup.S

arch/i386/boot/compressed/head.S

arch/i386/kernel/head.S

init/main.c

arch/i386/kernel/traps.c

arch/i386/kernel/entry.S

arch/i386/kernel/irq.h

include/asm-386/unistd.h

当然,这只是涉及到的几个主要文件。而事实上,增加系统调用真正要修改文件只有include/asm-386/unistd.h和arch/i386/kernel/entry.S两个。

C、对内核源码的修改:

1.在kernel/sys.c中增加系统服务例程如下:

asmlinkage int sys_addtotal(int numdata)

{

int i=0,enddata=0;

while(i<=numdata)

enddata+=i++;

return enddata;

}

该函数有一个 int 型入口参数 numdata , 并返回从 0 到 numdata 的累加值;

当然也可以把系统服务例程放在一个自己定义的文件或其他文件中,只是要在相应文件中作必要的说明;

2.把 asmlinkage int sys_addtotal( int) 的入口地址加到sys_call_table表中:

arch/i386/kernel/entry.S 中的最后几行源代码修改前为:

… …

.long SYMBOL_NAME(sys_sendfile)

.long SYMBOL_NAME(sys_ni_syscall) /* streams1 */

.long SYMBOL_NAME(sys_ni_syscall) /* streams2 */

.long SYMBOL_NAME(sys_vfork) /* 190 */

.rept NR_syscalls-190

.long SYMBOL_NAME(sys_ni_syscall)

.endr

修改后为: … …

.long SYMBOL_NAME(sys_sendfile)

.long SYMBOL_NAME(sys_ni_syscall) /* streams1 */

.long SYMBOL_NAME(sys_ni_syscall) /* streams2 */

.long SYMBOL_NAME(sys_vfork) /* 190 */

/* add by I */

.long SYMBOL_NAME(sys_addtotal)

.rept NR_syscalls-191

.long SYMBOL_NAME(sys_ni_syscall)

.endr

3. 把增加的 sys_call_table 表项所对应的向量,在include/asm-386/unistd.h

中进行必要申明,以供用户进程和其他系统进程查询或调用:

增加后的部分 /usr/src/linux/include/asm-386/unistd.h 文件如下:

… …

#define __NR_sendfile 187

#define __NR_getpmsg 188

#define __NR_putpmsg 189

#define __NR_vfork 190

/* add by I */

#define __NR_addtotal 191

4.测试程序(test.c)如下:

#include

#include

_syscall1(int,addtotal,int, num)

main()

{

int i,j;

do

printf(“Please input a number\n”);

while(scanf(“%d”,&i)==EOF);

if((j=addtotal(i))==-1)

printf(“Error occurred in syscall-addtotal();\n”);

printf(“Total from 0 to %d is %d \n”,i,j);

}

对修改后的新的内核进行编译,并引导它作为新的操作系统,运行几个程序后可以发现一切正常;在新的系统下对测试程序进行编译(*注:由于原内核并未提供此系统调用,所以只有在编译后的新内核下,此测试程序才能可能被编译通过),运行情况如下:

$gcc -o test test.c

$./test

Please input a number

36

Total from 0 to 36 is 666

可见,修改成功;

而且,对相关源码的进一步分析可知,在此版本的内核中,从/usr/src/linux/arch/i386/kernel/entry.S

文件中对 sys_call_table 表的设置可以看出,有好几个系统调用的服务例程都是定义在/usr/src/linux/kernel/sys.c

中的同一个函数:

asmlinkage int sys_ni_syscall(void)

{

return -ENOSYS;

}

例如第188项和第189项就是如此:

… …

.long SYMBOL_NAME(sys_sendfile)

.long SYMBOL_NAME(sys_ni_syscall) /* streams1 */

.long SYMBOL_NAME(sys_ni_syscall) /* streams2 */

.long SYMBOL_NAME(sys_vfork) /* 190 */

… …

而这两项在文件 /usr/src/linux/include/asm-386/unistd.h 中却申明如下:

… …

#define __NR_sendfile 187

#define __NR_getpmsg 188 /* some people actually want streams */

#define __NR_putpmsg 189 /* some people actually want streams */

#define __NR_vfork 190

由此可见,在此版本的内核源代码中,由于asmlinkage int sys_ni_syscall(void) 函数并不进行任何操作,所以包括 getpmsg,

putpmsg 在内的好几个系统调用都是不进行任何操作的,即有待扩充的空调用;

但它们却仍然占用着sys_call_table表项,估计这是设计者们为了方便扩充系统调用而安排的;

所以只需增加相应服务例程(如增加服务例程getmsg或putpmsg),就可以达到增加系统调用的作用。

Comand Line Process Bar for Java

In howto, java, python on December 4, 2007 at 10:43 pm

As we all know python can print without change line. Now the following codes shows how to do it in Java.

###############################################
“”"sc.py
This is a simple class to demonstrate the use of jythonc.
“”"

import java.lang.String

class sc(java.lang.Object):
def __init__(self):
“”"public sc() # constructor is not forced to add’@sig’
“”"

def tprint(self,c=’hello’):
“”"@sig public void tprint(String c)
“”"
print c,

if __name__ == ‘__main__’:
sc1 = sc()
sc1.tprint(‘zhengxin’)

################################################
// Simpleclasstest.java

import java.lang.*;

public class Simpleclasstest {
public static void main(String[] args) {
sc sc1 = new sc();
for (int i = 1;i<100; i++)
{ try { Thread.sleep(200); } catch (InterruptedException e) {};
sc1.tprint(“–”);
}
System.out.println(‘\n’);
}
}
#########################################
What to do now:
$jythonc sc.py # to generate java class.
$javac -cp /usr/share/jython/jython.jar:./jpywork Simpleclasstest.java # using Simpleclasstest.java to call the jython generated class.
$java -cp /usr/share/jython/jython.jar:.:./jpywork Simpleclasstest # run it.
=========================================================
Here is the way to achieve it in pure Java. and this java Class can be called by matlab to show process bar.
#########################################
//tryoutput.java
public class tryoutput {
String s;
public void setStr(String s)
{ this.s = s; }
public void tPrint()
{ try { Thread.sleep(200); } catch (InterruptedException e) {};
System.out.print(this.s);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
tryoutput op = new tryoutput();
op.setStr(“=”);
for ( int i=0; i<100; i++) {
op.tPrint();
} } }
#####################################

Comments:
Here for both java and python, the loop can be put in the tprint methods. Same effect.

python: import and Class and dir()

In howto, python on December 4, 2007 at 9:38 pm

Python:
No matter what the current directory is, Python must import the things it need.
———————————————————
Java:
If the class or jar is in the CLASSPATH, import will cause errors like: “import abc; something is expected”

############################
Import for Python:

  • What is imported is just the module name. If in the module a class is defined, to get a instance of the class, you must
    >>>import abc # here abc is the module file name
    >>>instance=abc.Cons() # here Cons is the class constructor; for jython, abc=Cons, it will looks like >>>instance=abc.abc()
  • >>>dir(instance)
    [] # this is just what you got when you want to check what methods is available for the object. If you want to achieve it, you should run:
    >>>dir(abc.Cons) # in Jython it should be: >>>dir(abc.abc)

C header definition and declaration

In C/C++, howto on December 3, 2007 at 1:33 am

Structuring header files

  > In the past, I've been told that for every .c file, you should > have a corresponding .h file which will contain all the necessary > definitions, prototypes, etc... for the functions in the file. > Is this the case, or should we just use one global header file > that contains all the prototypes, externs, defines, etc...

The rules are not carved in stone, and should be followed with a grain ofsalt in all specific cases, but here's the usual story:

a) It's always a good idea to play safe against possible multiple inclusions  of the same .h file. This can happen if you #include "foo.h" ,"bar.h", and  bar.h has an "#include "foo.h" line itself.  The canonical way to prevent multiple inclusions is to wrap each header  with an #ifndef CONSTANT directive, and #define that constant in the file  (immediately after). Example:

          /* This is myheader.h */          #ifndef _MYHEADER_          #define _MYHEADER_

          /* All the rest of the header here */

          #endif /* _MYHEADER_ */          /* End of myheader.h */

   The preprocessor will access the "rest of the header" only the first time   the header is included. The second time the _MYHEADER_ constant will be   already defined, causing #ifndef to be false, and the "rest" to be skipped   up to the #endif /* _MYHEADER_ */ line, that is up to the end.

b) .c files should contain relatively small sets of tightly related  functions. Their declarations go in a .h file with the same name, to  be included by all the other .c files that use those functions.

c) Type definitions (typedef, struct) must go in .h files, as soon as they are  used by more than one .c file. Defined type names should visually suggest  that they are not base types (like int or float). An often used convention  is to write their names using caps:       typedef int* Foo;       typedef float GlobeTrotter[3];       typedef struct _BarfBeer {          int a,b;          struct _BarfBeer* next; /* For a linked list */       } BarfBeer;

d) Preprocessor directives defining constants and macros go in .h files as  soon as the constants and macros are used by more than one function (it  annoys me to have to fish through a .c file for the definition of a macro,  and I'd much rather see it in a short .h). Constants used by just one  function are #define-d right before it in the .c file, and #undef-ined  immediately after. Defined constant names should be ALL_IN_CAPS

e) Global variables are declared with the "extern" storage qualifier in .h  files, which are included by all the .c files that need those  globals. There must be only ONE definition for each global variable (i.e. a  declaration without "extern"), and it MUST be in a .c file. If you put it  in a header, you get a multiple definition error as soon as that header is  included by more than one .c file. It doesn't hurt, and greatly helps  code readability, to redeclare at the beginning of a function all extern  variables used by that funciton (of course using the "extern" storage  qualifier).

f) If at all possible, do not include header files in header files, and let  only the .c guys do all the #include-ing.  A non ``flat'', hyerarchical inclusion structure is more suited to C++.

P.S. A "storage qualifier" is a keyword specifying the type of storage needed    for a certain variable. Example of C storage qualifiers are: static,

   extern, register, volatile.

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

Extern Variables and Functions

Because a global variable may be defined in one file and referred to in other files, some means of telling the compiler that the variable is defined elsewhere may be needed. Otherwise, the compiler may object to the variable as undefined. This is facilitated by an extern declaration. For example, the declaration

extern int size; // variable declaration

informs the compiler that size is actually defined somewhere (may be later in this file or in another file). This is called a variable declaration (not definition) because it does not lead to any storage being allocated for size.

It is a poor programming practice to include an initializer for an extern variable, since this causes it to become a variable definition and have storage allocated for it:

extern int size = 10; // no longer a declaration!

If there is another definition for size elsewhere in the program, it will eventually clash with this one.

Function prototypes may also be declared as extern, but this has no effect when a prototype appears at the global scope. It is more useful for declaring function prototypes inside a function. For example:

double Tangent (double angle)

{

extern double sin(double); // defined elsewhere

extern double cos(double); // defined elsewhere

return sin(angle) / cos(angle);

}

The best place for extern declarations is usually in header files so that they can be easily included and shared by source files.



jython call 3rd party java class file

In howto, java, python on December 2, 2007 at 3:14 am

——————————
Accessible Class
——————————
Every functions (including constructor) and the class declaration must start with public.

——————————
Jython call class Notes
——————————
For instance, if you want to initialize an object form your class, you should run
>>>gc = GetConf();
the ‘()’ is needed! Just remember, python loves (), the basic function dir() must followed ().

——————————
About Path
——————————
1. in terminal, go to the folder where the class file is. then run jython,and import the name of the calss. Now you can get a instance of that.

2. at runtime, you could do:

>>> import sys>>> sys.path.append('/path/to/module')

A few rules about CLASSPATH and python.path:

  • sys.path in the registry file — Add here to enable importing from Java classes (.java), Java class libraries (.jar), and Jython/Python (.py).
  • CLASSPATH — Add here to enable importing from Java classes (.java) and Java class libraries (.jar), but not Jython/Python (.py).

Matlab call java "class"

In howto, java, matlab on December 1, 2007 at 4:06 pm

1. Every methods should be public, especially the constructor. Otherwise the class can not be called.
Programming only within java, not so strict. Even you don’t need put any identifier in front classes and functions.

2. Matlab and Sun Java are not compatible completely, though 99% do, especially when Sun Java or Matlab update, issues always come out. But I found Matlab call the java classes generated by gcc-java(gcj) works much better.
When Matlab updates, it almost work on or for latest java jdk. Matlab 2007a can not call the java class generated by jdk 1.6.03, while Matlab 2007b can.

3. Remember the javaclasspath variable in Matlab. To use javaaddpath(pwd) for you Matlab functions. If new class file is added, run clear;clc; again to initialize the new class.

3.2. About compiling
Put the class file in the static javaclasspath (which is set in /toolbox/local/classpath.txt), in this way it will much faster than javaaddpath(pwd). But you much also put the class file in the classpath of MCR, /toolbox/local/classpath.txt, in this file, there still saying “$matlabroot” things, but here $matlabroot is mean . Just put the class in the mcr classpath folder, no need to be same with .

4.Can not get the attributes from the returned object directly, you need to compose a getXXXX(){return XXXXXX} method by yourself.

5. mcc -m XX.m -a YY.txt
If the XX.m doesn’t call java class (including Matlab embeded java functions, here try to use import less, which always cause error when the m-file is compiled), the YY.txt added by mcc without format changed will be able to be accessed, it is stored in XX_mcr/XX/. If not, the YY.txt can not be accessed. You must copy the YY.txt manually to the XX.exe folder.
Just be careful the added files when you mcc Matlab programs using java.

The attached code is to read config file abc.txt.
##################################
// GetConf.java
// GetConf.java
import java.util.*;
import java.io.*;

public class GetConf {
//the public is not necessary for Matlab, but for jython, this is essential.

String para;
Properties conf;

public GetConf() throws IOException{
conf = new Properties();
para = new String();
File file_name = new File(“abc.txt”);

FileInputStream conf_input;

try {
conf_input = new FileInputStream(file_name);
conf.load(conf_input);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}

public String getOnePara(String pnm){
para = conf.getProperty(pnm);
para = para.trim();
return para;
}

public static void main(String[] args) throws IOException{
String pa = (new GetConf()).getOnePara(“a”);
System.out.println(pa);
}

}
##################################
Here is the config file abc.txt
————————————————-
# a comment
! a comment

a = a string
b = a string with escape sequences \t \\ \” \’ \ (space) \u0123
c = a string with a continuation line \
continuation line
d.e = another string
————————————————

Headers in latex

In howto, latex on November 29, 2007 at 8:41 pm
The GNU Revision Control System is generally considered a tool for software development, but it is also useful for tracking revisions of text documents. This article explains how to include and format RCS keywords in LaTeX documents, and how to track document revisions using these keywords.

Most discussions of the GNU Revision Control System occur in the context of tracking source code revisions. But RCS can track revisions of any type of file, text or binary, provided that the diff utilities which generate RCS change files can handle binary data.

RCS seems ready-made for working with LaTeX input files. The pre-defined keyword identifiers built in to RCS are easy to format and print. They provide ready information that can include the document’s author, its revision, filename, and, revision log entry. RCS also provides facilities for user-defined identifiers.

RCS is commonly included with the development software of Linux distributions. The latest source code version of RCS is available from ftp://prep.ai.mit.edu/pub/gnu and its mirror sites.

The ident(1) manual page has a list of the standard RCS keywords that are generated when documents are checked out by RCS. They include:

* $Author: lg $: The login name of the person who checked in the revision.
* $Date: 2002/10/09 22:24:18 $: The date and time the document was checked in.
* $RCSfile: latex.html,v $ The basename and extension of the RCS file.
* $Id: latex.html,v 1.2 2002/10/09 22:24:18 lg Exp $: String containing the name of the RCS file, the revision number, date and time, author, state, and locker if any.
* $Revision: 1.2 $: The document’s revision number.
* $Log: latex.html,v $
* Revision 1.2 2002/10/09 22:24:18 lg
* Remove all lg_toc##.html; change hyperlinks to index.html
*
* Revision 1.1.1.1 2002/08/14 22:27:03 dan
* Preliminary.
*
* Revision 1.1.1.1 1997/09/14 15:01:51 schwarz
* Imported files
* The log message entered when the document was checked in.

These keywords are included verbatim in documents. They are expanded when the document is checked out with co(1).

One consideration that needs to be taken into account is that the keywords’ dollar signs are interpreted by LaTeX (and TeX) as starting and ending math-mode typesetting. LaTeX and TeX will not generate an error when it encounters the dollar signs. However, because LaTeX and TeX typeset equations differently than normal text, the results can be unpredictable.

For example, including the $Id: latex.html,v 1.2 2002/10/09 22:24:18 lg Exp $ string at the top of the odd pages the commands

\pagestyle{myheadings}
\markright{$Id: latex.html,v 1.2 2002/10/09 22:24:18 lg Exp $}

results in the expanded RCS $Id: latex.html,v 1.2 2002/10/09 22:24:18 lg Exp $ string to be printed at the top of the pages, but some of the keywords run together because of the way TeX formats the string. An alternative is to use the keywords of the individual identifiers, and separating them with the appropriate command. Here, the TeX command \hfil inserts the necessary space when the keyword strings are typeset in the running head.

\pagestyle{myheadings}
\markright{$Date: 2002/10/09 22:24:18 $\hfil$RCSfile: latex.html,v $\hfil$Revision: 1.2 $}

The string given to the \markright command will be typeset with the date in the upper left of the page, the filename centered, and the revision number at the top right.

The \markright command is all that’s needed for printing on one side of a sheet. For printing on both sides of the page, use the \markboth command.

\pagestyle{myheadings}
\markboth{$Date: 2002/10/09 22:24:18 $\hfil$RCSfile: latex.html,v $\hfil$Revision: 1.2 $}{\thepage}

The first argument to \markboth prints the RCS information at the tops of the left-hand pages and the page number at the top of the right-hand pages. The identifier \thepage is a standard LaTeX variable which prints the page number.

The RCS log message can be placed anywhere in a document that the $Log: latex.html,v $ Revision 1.2 2002/10/09 22:24:18 lg Remove all lg_toc##.html; change hyperlinks to index.html Revision 1.1.1.1 2002/08/14 22:27:03 dan Preliminary. Revision 1.1.1.1 1997/09/14 15:01:51 schwarz Imported files keyword can be inserted. For example, to place a (short!) log message in the margin at the beginning of a document, put the command \marginpar{$Log: latex.html,v $ \marginpar{Revision 1.2 2002/10/09 22:24:18 lg \marginpar{Remove all lg_toc##.html; change hyperlinks to index.html \marginpar{ \marginpar{Revision 1.1.1.1 2002/08/14 22:27:03 dan \marginpar{Preliminary. \marginpar{ \marginpar{Revision 1.1.1.1 1997/09/14 15:01:51 schwarz \marginpar{Imported files \marginpar{} immediately after the \begin{document} command, or after the \maketile command if the document has a title page and you’d rather have the RCS log text annotating the body text of the document.

The RCS information can be included in the documents footer by using the fancyhdr package, which is available from any TeX archive site.

If you want to include the $Date: 2002/10/09 22:24:18 $ and $Revision: 1.2 $ keywords at the bottom of a page, you could include

\usepackage{fancyhdr}
\fancypagestyle{rcsfooters}{%
\fancyhf{}
\fancyhead[C]{thepage}
\fancyfoot[L]{$Date: 2002/10/09 22:24:18 $}
\fancyfoot[R]{$Revision: 1.2 $}

in the document preamble; that is, before the \begin{document} command. At the point you want the RCS data to be typeset, insert the commands

\thispagestyle{rcsfooters}
\pagestyle{rcsfooters}

ident(1) also searches files for RCS keywords. Typing the command ident term-paper.tex for example, will print a list of the keywords and their values to standard output. It’s a simple matter of typing ident *tex | grep “fred” – to search for the documents which were last checked out by user fred.

For further information, consult the manual pages of the various programs in the RCS package, and the rcsintro(1) manual page for an introduction to the RCS system.

Powered by ScribeFire.

Symbolic Operations in Matlab

In howto, matlab on November 28, 2007 at 8:48 pm

Background Note:

Up to this point we have done purely numerical operations in Matlab. This is the traditional approach for solving problems on the computer, and much of the current computational work done in industry follows this approach. However, a relatively new capability (last 5-10 years or so) that is gaining popularity involves the use of symbolic operations directly on the computer. Computer programs that use these symbolic techniques are often referred to as computer algebra systems, and they are becoming quite powerful. In particular, Matlab’s Symbolic Math Toolbox offers this general capability within the Matlab environment by providing an interface to the Maple code (Maple is a commercial software package that emphasizes symbolic manipulations or computer algebra techniques). This set of labs will introduce some of the basic symbolic capability in Matlab, eventually leading up to the analytical solution of Ordinary Differential Equations directly on the computer. Many of the exercises given here are derived from the Matlab’s User’s Guide and you are encouraged to refer to that manual for further examples and guidance.

Define Some Symbolic Variables:

First define a bunch of symbolic variables: syms a1 b1 c1 a2 b2 c2 d2 A B C1 C2 x y t

Now let’s form some symbolic functions:

Mathematical Function
Matlab Syntax for Function

f1 = a1 + b1*x + c1*x^2

f2 = a2 + b2*x + c2*x^2 + d2*x^3

g = exp(A*t)*(C1*cos(B*t)+C2*sin(B*t))

u = 2*x*y^2 + sin(x+y)

Differentiation of Symbolic Functions:

Differentiate each of the above functions using Matlab’s diff command. For example, try diff(f1). What happened? Is the result correct? Do the same thing for the other functions. What happens when you type diff(u)? How do you get Matlab to take the partial derivative with respect to the variable y? Type help sym/diff to see the various options associated with taking symbolic derivatives.

We can also take higher order derivatives. For example diff(f1,2) takes the second derivative of f1(x). Try this for all the functions!

Can you show that the mixed partial derivatives of u(x,y) are equal? Take du/dx and du/dy as above and save the results as string variables. For example, try typing

dudx = diff(u,x); dudy = diff(u,y);.

Now take the first derivative of these symbolic variables, as follows:

uyx = diff(dudx,y); uxy = diff(dudy,x);

Are these latter two variables the same? They should be. Pretty neat stuff, don’t you think!!!

Integration of Symbolic Functions:

Using Matlab’s int function, perform the following integrals using f1(x):

Mathematical Operation
Matlab Syntax for Operation

I1 = int(f1)

I2 = int(f1, 0, 5)

Do these make sense? Check out the subs command. Now let a1 = 1, b1 = -2, and c1 = 1, and substitute these numerical constants into the symbolic expressions for I1 and I2, as follows:.

I1 = subs(I1,{a1 b1 c1},{1 -2 1}), I2 = subs(I2,{a1 b1 c1},{1 -2 1})

What are the values for the integrals I1 and I2? Why is I1 a function of x and I2 is simply a scalar number? Note also that the curly brackets in Matlab refer to cell arrays. The sequence given by the set, {a1 b1 c1},{1 -2 1}, replaces the numerical variables into the symbolic variables in sequence. The cell array simply let’s us make all three substitutions in one call to the subs command.

Try integrating and substituting values for the constants in the other functions. Note that with u(x,y), you can only integrate with respect to one variable at a time. For example,

Mathematical Operation
Matlab Syntax for Operation

Iu = int(int(u,x,0,pi),y,0,2*pi)

Pretty impressive!!! Could you do this integral by hand this fast? I certainly can’t…

Plotting Symbolic Functions:

Certainly we can also plot symbolic relationships. Since we have already defined the constants for use with f1(x), let’s use this function to do some simple plots. In particular, let’s plot f1(x), df1/dx, and over the range . We can do this as follows:

F1 = subs(f1,{a1 b1 c1},{1 -2 1}); D1 = diff(F1); I1 = int(F1);
Nx = 51; xp = linspace(0,5,Nx);
F1p = double(subs(F1,x,xp));
D1p = double(subs(D1,x,xp));
I1p = double(subs(I1,x,xp));
plot(xp,F1p,’r-‘,xp,D1p,’g–’,xp,I1p,’b-.’),grid
title(‘Evaluating and Plotting Symbolic Functions’)
xlabel(‘X Values’),ylabel(‘Various Function Values’)
legend(‘Function’,’First Derivative’,’Integral’)

Solving Algebraic Equations:

We can also solve algebraic equations with Matlab. For example, what if we wanted to know the value of x where f1(x) = 3? With the above constants this problem becomes: find x such that

In Matlab, we can use the solve command: solve(x^2-2*x-2) or solve(F1 – 3).

We can also solve systems of algebraic equations. For example, the analytical solution to the following 2×2 system:

is given by:

S = solve(3*x + 2*y – 3,-2*x + y + 7); % this solves a simple set of 2×2 equations

S.x, S.y % this prints x and y to the screen

Solving Ordinary Differential Equations:

The real goal of the above discussion and examples with symbolic variables is to give enough background so that we can solve ODEs analytically on the computer. This will be pretty powerful capability if we can actually do this with a set of relatively simple commands. As a test, let’s give Matlab’s dsolve command a workout for a few different types of ODEs that we have treated thus far in the semester (be sure to type help dsolve to get a good idea of the various forms that can be used).

a. Solve the first order IVP:

dsolve(‘Dy + y/x = (2/x)*exp(2*x)’,’x’) % this gives the general solution

dsolve(‘Dy + y/x = (2/x)*exp(2*x)’,’y(1) = 0’,’x’) % this gives the unique solution

b. Solve the second order IVP:

Sh = dsolve(‘D2y – 4*y = 0′,’x'), pretty(simple(Sh)) % homogeneous soln
Sg = dsolve(‘D2y – 4*y = 4*x^2′,’x'), pretty(simple(Sg)) % general soln
Su = dsolve(‘D2y – 4*y = 4*x^2′,’y(0) = -1/2′,’Dy(0) = 4′,’x') % unique soln
pretty(simple(Su))

c. Solve the second order IVP:

Q1 = dsolve(‘D2y + 6*Dy +13*y = 10*sin(5*t)’, ’y(0) = 0’,’Dy(0) = 0’,’t’)
pretty(simple(Q1))

d. Re-solve the problem in Part c as a system of two 1st order ODEs, where z1 = y and z2 = dy/dt:

Q2 = dsolve(‘Dz1 =z2’,’Dz2 = -13*z1 -6*z2 + 10*sin(5*t)’, ’z1(0) = 0’,’z2(0) = 0’,’t’)
pretty(simple(Q2.z1)), pretty(simple(Q2.z2))

Final Note:

There is a lot of good stuff here. In particular, there are several examples that should make your life much easier in this course and in several of your other technical classes. You should do your best to understand the basic capability that is illustrated here — it represents some pretty powerful mathematical analysis capability. You should also note that some of the examples from earlier in the semester (the Two Salty Tanks problem for example) give other illustrations of the use of computer algebra to solve a coupled set of first order differential equations for a real problem of interest. Also, a final Matlab demo will be given at the end of the semester illustrating how to take Laplace transforms and inverse Laplace transforms analytically using Matlab’s symbolic processing capability.

########
from: http://www.tmt.ugal.ro/crios/Support/ANPT/Curs/deqn/labs/mlabex_symbolic/mlabex_symbolic.html

unittest模块

In howto, python on November 28, 2007 at 11:42 am
unittest模块是用python编写的,其功能与junit一样,都是为了方便单元测试用的测试框架。
unittest模块是从python
2.1引入标准库的。它包含几个类:TestCase,TestSuite,TestResult,TextTestRunner等等。要建立自动测试,
必须创建unittest.TestCase的子类。然后定义一连串的test测试函数。使用assertXXX来下断言。测试成功就ok,测试错误就
Error,测试失败就Fail,共3种状态。比如:

import uniittest

import ysfile #自定义的模块

class TestZDYSFile(unittest.TestCase):

def setUp(self):

self.zd=ysfile.ZDYSFile(‘ysh1b1.09′)

def testGetYear(self):

self.assertEqual(self.zd.getYear(),2005)

def testGetLoca_bz(self):

self.assertEqual(self.zd.getLoca_bz(),4)

class TestPDYSZipFile(unittest.TestCase):

def setUp(self):

self.pd=ysfile.PDYSZipFile(‘pdysj09.zip’)

def testGetCdate(self):

self.assertEqual(self.pd.getCdate(),’20050117′)

if __name__ == ‘__main__’:

#unittest.main()

suite = unittest.TestSuite()

suite.addTest(unittest.makeSuite(TestZDYSFile))

suite.addTest(unittest.makeSuite(TestPDYSZipFile))

unittest.TextTestRunner(verbosity=2).run(suite)

unittest.main()是用来调用所有的测试实例,unittest.TestSuite()是用来组合相关的测
试实例的,用addTest方法添加测试实例。setUp和tearDown方法是用来建立必要的测试环境,例如变量,文件等。tearDown进行一些
扫尾工作。

Powered by ScribeFire.

unittest模块

In howto, python on November 28, 2007 at 11:42 am
unittest模块是用python编写的,其功能与junit一样,都是为了方便单元测试用的测试框架。
unittest模块是从python
2.1引入标准库的。它包含几个类:TestCase,TestSuite,TestResult,TextTestRunner等等。要建立自动测试,
必须创建unittest.TestCase的子类。然后定义一连串的test测试函数。使用assertXXX来下断言。测试成功就ok,测试错误就
Error,测试失败就Fail,共3种状态。比如:

import uniittest

import ysfile #自定义的模块

class TestZDYSFile(unittest.TestCase):

def setUp(self):

self.zd=ysfile.ZDYSFile(‘ysh1b1.09′)

def testGetYear(self):

self.assertEqual(self.zd.getYear(),2005)

def testGetLoca_bz(self):

self.assertEqual(self.zd.getLoca_bz(),4)

class TestPDYSZipFile(unittest.TestCase):

def setUp(self):

self.pd=ysfile.PDYSZipFile(‘pdysj09.zip’)

def testGetCdate(self):

self.assertEqual(self.pd.getCdate(),’20050117′)

if __name__ == ‘__main__’:

#unittest.main()

suite = unittest.TestSuite()

suite.addTest(unittest.makeSuite(TestZDYSFile))

suite.addTest(unittest.makeSuite(TestPDYSZipFile))

unittest.TextTestRunner(verbosity=2).run(suite)

unittest.main()是用来调用所有的测试实例,unittest.TestSuite()是用来组合相关的测
试实例的,用addTest方法添加测试实例。setUp和tearDown方法是用来建立必要的测试环境,例如变量,文件等。tearDown进行一些
扫尾工作。

Powered by ScribeFire.

unittest模块

In howto, python on November 28, 2007 at 11:42 am
unittest模块是用python编写的,其功能与junit一样,都是为了方便单元测试用的测试框架。
unittest模块是从python
2.1引入标准库的。它包含几个类:TestCase,TestSuite,TestResult,TextTestRunner等等。要建立自动测试,
必须创建unittest.TestCase的子类。然后定义一连串的test测试函数。使用assertXXX来下断言。测试成功就ok,测试错误就
Error,测试失败就Fail,共3种状态。比如:

import uniittest

import ysfile #自定义的模块

class TestZDYSFile(unittest.TestCase):

def setUp(self):

self.zd=ysfile.ZDYSFile(‘ysh1b1.09′)

def testGetYear(self):

self.assertEqual(self.zd.getYear(),2005)

def testGetLoca_bz(self):

self.assertEqual(self.zd.getLoca_bz(),4)

class TestPDYSZipFile(unittest.TestCase):

def setUp(self):

self.pd=ysfile.PDYSZipFile(‘pdysj09.zip’)

def testGetCdate(self):

self.assertEqual(self.pd.getCdate(),’20050117′)

if __name__ == ‘__main__’:

#unittest.main()

suite = unittest.TestSuite()

suite.addTest(unittest.makeSuite(TestZDYSFile))

suite.addTest(unittest.makeSuite(TestPDYSZipFile))

unittest.TextTestRunner(verbosity=2).run(suite)

unittest.main()是用来调用所有的测试实例,unittest.TestSuite()是用来组合相关的测
试实例的,用addTest方法添加测试实例。setUp和tearDown方法是用来建立必要的测试环境,例如变量,文件等。tearDown进行一些
扫尾工作。

Powered by ScribeFire.

Compiling Python(Jython) and for Java

In howto on November 28, 2007 at 12:19 am

Another view: Jython is the extension language for Java.

Use jythonc. What is jythonc and what is its status?

jythonc transforms Python source code into Java source code then invokes a Java compiler to turn it into .class files. This allows Python to be integrated into Java in several places that regular Jython currently doesn’t support. It also processes special annotations in docstrings on methods in Python code to determine the static type information to expose when turning a dynmically typed Python method into a statically typed Java method.

jythonc is unmaintained and will not be present in Jython-2.3. While jythonc handles all of the language features present in Jython 2.2, it doesn’t support 2.3 features such as generators. As such, it is not recommended that new Jython projects make use of jythonc. It is only included in Jython-2.2 to support older users of jythonc and to allow access to a few features that are only provided by jythonc at the moment:

  1. Running in a JVM with a classloader that will not load dynamically created classes
  2. Declaring Java method signatures in Python code
  3. Loading Python classes dynamically from Java with Class.forName

While all of these features are planned for Jython-2.3, they are currently only available from jythonc. Most uses of the second feature, adding method declarations to docstrings, can be handled by declaring a Java interface to implement with a Python class. Each method in the Python implementation takes the types of the Java method it implements. Exposing the Python class as an instance of that type to Java code can be done as explained in Accessing Jython from Java Without Using jythonc and its followup, Simple and Efficient Jython Object Factories.

(See http://www.jython.org/Project/jythonc.html)

You can extend Java classes.

You can add (J)Python protocols to Java classes.

You will need to describe the signature of methods in order to make them callable from Java (in addition to Jython).

What jythonc does — jythonc translates .py files into .java source code files, then compiles these to .class files.

With jythonc, you can also:

  • Compile Jython (.py) to Java class files (.class).

  • Compile Jython to Java source, then stop without compiling to .class files.

  • Use a Java compiler different from the default: javac. See the help from jythonc:

    --compiler path-C path    Use a different compiler than `standard' javac.  If this is set to    `NONE' then compile ends with .java.  Alternatively, you can set the    property python.jpythonc.compiler in the registry.

    This option can also be set in your Jython registry file.

Java compatible classes – In order to implement a Java compatible class (that is, one that acts like a native Java class and can be called from Java), your Jython code must follow these rules:

  • Inherit from a Java class or interface.
  • Include only one class per module.
  • Give the Jython class and the source file that contains it the same name.
  • Place all code inside that Jython class.
  • Include method signature hints (called sig-strings) — Add a @sig line in the doc-string for each method.

How to use jythonc:

  • Type jythonc --help for help.

  • Compile your Jython code with:

    jythonc mymodule.py
  • To get help for jythonc, type:

    $ jythonc --help

Some notes:

  • When your run jythonc, by default, the .java files are placed in a sub-directory ./jpywork. You can override this with the --workdir command line option. From jythonc --help:

    --workdir directory-w directory    Specify working directory for compiler (default is ./jpywork)
  • When you run this resulting code from Java, the directory ./jpywork and the Jython jar file must be on your classpath.

Example — The following Jython code extends a Java class. Compile it with jythonc:

# Foo.py

import java

class Foo(java.util.Date):    def __init__(self):        self.count = 0    def bar(self, incr=1):        """@sig void bar(int incr)"""        self.count += incr        return self.count    def toString(self):        cnt = self.bar()        return "Foo[" + java.util.Date.toString(self) + " " + `cnt` + "]"

Example, continued — Here is Java code to test the above. Compile it with javac and run it:

// FooTest.java

import Foo;

public class FooTest {     public static void main(String[] args) {         Foo foo = new Foo();         System.out.println(foo);         foo.bar();         foo.bar(43);         System.out.println(foo);     }}

Notes:

  • Compile and run:

    $ javac FooTest.java$ java FooTest
  • You will need jpywork on your classpath. So, you can compile and run it as follows:

    $ ../../Jython-2.2a/jythonc Foo.py$ javac -classpath ../../Jython-2.2a/jython.jar:./jpywork FooTest.java$ java -classpath ../../Jython-2.2a/jython.jar:./jpywork FooTest

In order to implement a Java compatible class (that is, one that acts like a native Java class and can be called from Java), your Jython code must follow these rules:

  • Inherit from a Java class or interface.
  • Include method signature hints (called sig-strings).
  • Give the Jython class and the source file it is in the same name.

Here is another simple example:

"""simpleclass.py

This is a simple class to demonstrate the use of jythonc."""

import java.lang.Object

class simpleclass(java.lang.Object):    def __init__(self, name='The Horse With No Name'):        """public simpleclass(String name)        """        self.name = name        self.size = -1    def set_name(self, name):        """@sig public void set_name(String name)        """        self.name = name    def set_size(self, size):        """@sig public void set_size(int size)        """        self.size = size    def show(self):        """@sig public String show()        """        return 'name: %s  size: %s' % (self.name, self.size, )

And, a Java test harness for this simple example:

// simpleclasstest.java

import simpleclass;

public class simpleclasstest {    public static void main(String[] args) {    String s1;    simpleclass sc = new simpleclass();    s1 = sc.show();    System.out.println("1. " + s1);    sc.set_name("dave");    sc.set_size(4321);    s1 = sc.show();    System.out.println("2. " + s1);    }}

Notes:

  • In order to produce a Java compatible class, our Jython class must inherit from a Java class. In this case, we use java.lang.Object, because we do not need to inherit any behavior.
  • The methods set_name, set_size, and show each have sig-strings.

Put jpywork on your CLASSPATH, then use the following to compile and test the above:

$ jythonc simpleclass.py$ javac simpleclasstest.java$ java simpleclasstest1. name: The Horse With No Name  size: -12. name: dave  size: 4321

In the following example, we create a stand-alone Jar file, that is, one that can be executed as a script on a machine where Jython is not installed. Here is the Jython script:

# test_jythonc.py

import sys

def test(words):    msgs = ['hi', 'bye']    for word in words:        msgs.append(word)    for msg in msgs:        print msg

def main():    args = sys.argv[1:]    test(args)

if __name__ == '__main__':    main()

Compile and build a Jar file with the following:

$ jythonc --all --jar mytest.jar test_jythonc.py

Run it as follows:

$ java -jar mytest.jar hello goodbyehibyehellogoodbye

Notes:

  • Note that our Jython script contains no class. jythonc will create a public class and a public static main function for us.
  • The --jar flag tells jythonc that we want the results placed in a Jar file (as opposed to placing it in the work directory ./jpywork).
  • The --all flag tells jythonc to include all Jython support in the Jar file, making it stand-alone. This enables us to run it on a system where Java is installed but Jython is not.

16.1   Calling Jython Code from Jython

From Jython, you can run Jython and Python code. When you do so, you may run Java code that is in a super-class or is used by the Jython code.

But, notice that, from Jython, you cannot call Python code that has been extended with C.

16.2   Calling Jython Code from Java

Must compile Jython/Python to Java with jythonc.

Must pay attention to method signatures. Define method signature in Jython in a doc string with @sig. Then look at the generated .java file.

Other things to be aware of:

  • Must set classpath to include jpywork.
  • Must write a Java compatible class. See above.

16.3   Another example — Jython-2.2a/Demo/javaclasses

What this example shows:

  • How to write a class that can be compiled (with jythonc) and then called from Java.
  • How to write method signatures for Jython methods.
  • How to compile the the Jython code and the Java code.

For example, I compiled and ran the example in Jython-2.2a/Demo/javaclasses with the following:

$ rm -rf jpywork/$ ../../jythonc --package pygraph Graph.py$ javac -classpath .:../../jython.jar pygraph/PythonGraph.java$ java -classpath .:../../jython.jar:jpywork pygraph.PythonGraph

For more information, see Jython-2.2a/Demo/javaclasses/readme.txt.

From:http://www.rexx.com/~dkuhlman/jython_course_01.html#another-example-jython-2-2a-demo-javaclasses

Blogged with Flock

Python的"字节码" pyc文件

In howto, python on November 27, 2007 at 4:18 pm
pyc是python的二进制编译文件
pyc文件比py文件拥有更快的装载速度,但是执行速度没有区别。
但是对于程序员来说,转换为pyc文件最大的好处是可以隐藏源代码。

命令为

python -c “import compileall; compileall.compile_dir(‘py文件存放目录的路径’)”

该命令可以为一个目录下的py文件生成pyc文件(包含子目录)

在windows平台上的路径书写方式为(‘D:/7ying/test’)

Powered by ScribeFire.

Python的"字节码" pyc文件

In howto, python on November 27, 2007 at 4:18 pm
pyc是python的二进制编译文件
pyc文件比py文件拥有更快的装载速度,但是执行速度没有区别。
但是对于程序员来说,转换为pyc文件最大的好处是可以隐藏源代码。

命令为

python -c “import compileall; compileall.compile_dir(‘py文件存放目录的路径’)”

该命令可以为一个目录下的py文件生成pyc文件(包含子目录)

在windows平台上的路径书写方式为(‘D:/7ying/test’)

Powered by ScribeFire.

如何“编译”Python程序

In howto, python on November 27, 2007 at 1:04 pm

如何编译Python程序(或者如何由Python生成可执行文件)是一个非常常见的问题,总是有人问,列出来,google搜索的时候就可以看到了。如果还有人说”找不到相关资料”,唯一的解释就是这个人太懒了,根本没有去找。

如果转载,请注明作者是牡蛎,出自http://blender.blogchina.com/523381.html。

0. Python(及其它高级的脚本语言)不存在把指令编译到本地代码的工具,但是总是可以发布可执行文件。

 
py2exe http://py2exe.sf.net
只支持windows平台,应该是大家听到最多的一个名字了,用户不少,所以有问题的话在它的mail list里面很容易找到答案。文档中提到了”无法找到某某code”、使用opengl等模块的问题

 
PyPackage http://codereactor.net/projects/pypack/index.html
我觉得py2exe等等工具还是罗嗦得像唐僧,需要在配置文件中写上需要的数据文件。作者完全无视这样一个事实:我需要发布可执行文件的时候,程序已经完工了,所有的数据文件就在主程序所在目录下,所以多数情况下,根本不用到别的地方搜索。现在终于有人站了出来,PyPackage实际上并不是一个程序打包的工具,而只是简化py2exe的操作,甚至可以自动调用InnoSetup 5制作安装文件——不过这个软件并不智能,会打包很多不需要的文件

 
Installer http://www.mcmillan-inc.com/installer_dnld.html
可以产生windows、linux平台的可执行文件,现在作者主页连不上去了,但是搜索一下可以在其它地方下载
自带一个小程序写配置文件,如果程序较复杂,还是需要手工修改这个配置文件。支持从py15以来的所有Python版本
2005年9月,冰冻牡蛎更新:Giovanni Bajo获得Gordon McMillan’s Installer的授权、版权改变为GPL,并在http://pyinstaller.hpcf.upr.edu/继续开发PYinstaller。2006年9月更新:这里可以看到Gordon McMillan’s的原始网站的镜像

 
Python自带的freeze.py(不过windows版本不带这个,你可以自己下载Python的源程序再找)。这个是我最不推荐的一种方法(为什么?自己看),不过如果你的Python程序要发布到其它工具不支持的平台上,可以考虑这个方法

 
新出来的Pyco http://www.pythonapocrypha.com/projects/pyco/
还没用过

 
Squeeze http://starship.python.net/crew/fredrik/ipa/squeeze.htm
还没用过,只支持Python 1.4

 
cx_Freeze http://starship.python.net/crew/atuining/cx_Freeze/
winodws、linux平台。简单的程序甚至都不需要写配置文件

 
Stand alone Python for Windows http://arctrix.com/nas/python/standalone.html
如果你不介意源程序太过”暴露”的话,用这个吧
会不会觉得Updated: Sun, 09 Apr 2000 18:39:54 -0600 扎眼?如果你看一看它的VC源代码,就不会这么想了——其实这是普遍适用于win系统的方法,无论是98、2000或者xp。也许也可以用到linux上——我不懂linux,如果真的可以这么做,还请告诉我。

 
py2app http://undefined.org/python/
支持linux平台的工具可能也支持mac os,或者直接使用这个py2app。具体就不知道了,只吃过苹果,还没玩过苹果呢

 
Movable Python http://www.voidspace.org.uk/python/movpy/
这个其实是使用py2exe制作的、可以放在U盘上的绿色Python。有使用py2app制作苹果版movpy和用cx_Freeze制作Linux版movpy的计划。懒到都不愿意学习py2exe、py2app或者cx_Freeze的人可以看看。

 
Shed Skin – A Python-to-C++ Compiler: 试验项目,windows上,连他的例子我都没有编译成功 :(

 
Psyco: 给Python程序加速的东西,看不出对发布Python程序的直接好处,并且作者以后将致力于PyPy。

 
PyPy: 项目目标是纯Python实现的Python、速度比CPython快,将来可以帮助实现编译Python。

 
pyc: Python compiler in Python,一个用纯Python写的Python的bytecode编译器,可以优化输出的pyc文件。和PyPy一样,现在还看不出对发布Python程序的直接好处。只有py24的bytecode。pyc是pyvm这个新的python虚拟机的一部分。

 
Jungle: 使用GNU工具(as、ld和winres)把Python程序编译到windows的exe可执行文件。该可执行文件只使用基于python24的的pythonic.dll。猜测它支持的模块仅限于内部模块以及jungle.jgl列出的模块。只有可执行文件下载,而这个可执行文件也是用Jungle自己编译的。目前版本号都到1.10了,经常看0.xx的版本号,这个数字好大啊,娃哈哈。

 

另类的方法,对Python语言特性都还不是100%支持,众多的CPython模块也不可以使用,还有,我也没有试过:
for .NET的Python编译器(如Visual Python、IronPython),不过我可不喜欢为了一个芝麻大的软件安装.NET framework
用jython,然后用jbuilder、jsmooth、NativeJ之类的包裹一下,或者用gcj编译成本地代码

 

2006年11月26日,近来有些人问,如何保护python开发的商业软件/闭源软件。

我的观点是,纯Python程序,又不想用C语言(其实C语言程序也可以破解,所以最好的方法就是不发布任何程序,嘿嘿),可以试试pyobfuscate混淆源代码,增加可能被反编译获得的源代码的阅读难度。不过pyobfuscate也好久没有更新了,娃哈哈。而实际上,没必要考虑别人会获得源代码的问题。 考虑(尤其是在自己的程序还没有写出来的时候)别人会反编译自己的Python程序,有点杞人忧天。

在*nix下的话,似乎可以(我不用*nix,并不确定)使用Python自带的freeze.py,把源程序的字节码转换成C程序,然后使用GCC编译,这样应该看不到字节码了。在windows下,不知道怎么使用freeze.py,总报错——谁知道的话告诉我吧。但是如果想实现跨平台,使用freeze.py的方法似乎不可取。

首先我相信,目前没有软件可以很好反编译Python 2.4及之后的版本生成的字节码,所以采用新版本Python“编译”到可执行文件,是安全的。

其次,据我所知,目前最成熟的反编译软件只有decompyle。而不是象某些人为了夸大问题的重要性,而口吐莲花所说的“现在有很多Python的反编译软件”。而我不相信有人愿意花钱买这个“唯一的且很多的”反编译软件,理由有二
看看decompyle页面更新日期,是2004年。我猜测作者把这个软件商业化之后并不成功,并没有太多人需要反编译自己或者他人的Python程序。导致作者没有足够的收入或者兴趣继续完善了
有人愿意花钱去反编译一个还不存在地软件,或者一个不出名的程序?

次成熟的反编译软件是decompiler.py。但是它比商业软件decompyle差远了。我没有去做试验,是他自己的主页承认说有很多局限的。

最后,真诚请教那些有“很多”Python反编译程序的高手,两个问题:
subsystem.htm
这是将数独游戏和消除游戏结合起来的益智游戏,未注册的话,只能累积玩60分钟。这是Python+pygame制作的软件,使用py2exe发布,可否麻烦高手——别怕,我不要它的源程序——看看它的注册部分,整个注册机/注册码出来?
wingide
这个有名的Python商业ide,我不确定它是不是使用py2exe制作的,而且它的规模比较大。我对它的源代码有点兴趣,有人说看不到它的源代码,但是我觉得\bin\2.4\src.zip里面的一堆pyo,是如假包换的源代码的字节码,如果真是如此,麻烦高手在空余时间,反编译一份喽。

解决Linux系统播放器MP3标签乱码的问题

In howto, linux on November 23, 2007 at 12:36 am

在amarok 或者 banshee 等播放器中 导入的mp3 很多都是乱码。看起来很别扭,今天找到了解决的方法 找到了一款java编写的小程序。

  使用方法

  下载ID3iconv 0.2.1 Binary

  cd到 mp3文件夹 这个很关键 不cd进去 是不行的 会出错。
  执行命令 sudo java -jar ~/id3iconv-0.2.1.jar -e gbk -removev1 *.mp3

  如果 程序出错 很有可能是java环境的错误,可以配置一下环境。

  方法

  安装JAVA环境。

  sudo apt-get install sun-java6-jre

  安装JDK。

  sudo apt-get install sun-java6-jdk

  设置当前默认的java解释器。

  sudo update-alternatives –config java

  输入有包含”sun”的行的前面的数字。

Powered by ScribeFire.

解决Linux系统播放器MP3标签乱码的问题

In howto, linux on November 23, 2007 at 12:36 am

在amarok 或者 banshee 等播放器中 导入的mp3 很多都是乱码。看起来很别扭,今天找到了解决的方法 找到了一款java编写的小程序。

  使用方法

  下载ID3iconv 0.2.1 Binary

  cd到 mp3文件夹 这个很关键 不cd进去 是不行的 会出错。
  执行命令 sudo java -jar ~/id3iconv-0.2.1.jar -e gbk -removev1 *.mp3

  如果 程序出错 很有可能是java环境的错误,可以配置一下环境。

  方法

  安装JAVA环境。

  sudo apt-get install sun-java6-jre

  安装JDK。

  sudo apt-get install sun-java6-jdk

  设置当前默认的java解释器。

  sudo update-alternatives –config java

  输入有包含”sun”的行的前面的数字。

Powered by ScribeFire.

中国访问blogspot的方法

In google, howto on November 22, 2007 at 1:32 pm

Crossonline below is my Blog ID, just change it to yours, it will work. Anything wrong, please comment to let me know, thanks.

  • pkblogs.com/crossonline
  • inblogs.net/crossonline
  • 更改C:\WINDOWS\system32\drivers\etc\hosts,添加 72.14.219.190 crossonline.blogspot.com
  • 最近部分地区的电信好像是又把blogspot.com给封了,至少在极速客那里很多人反应,河北网通这里还是好好的,可以正常访问。不过看到极速客提供的比较费神费力的修改Hosts的方法,我很乐意分享一下我是怎样访问被封杀的blogspot的。首先打开Notepad(或者其他的编辑器),写入如下内容:
    function FindProxyForURL(url,host){if(dnsDomainIs(host, ".blogspot.com")){    return "PROXY 72.14.219.190:80";}}

    另 存为proxy.pac到C盘的根目录下,以Firefox为例,打开Firefox,依次点击Tools->Options-> Advanced->Network->Settings…->选中Automatic proxy configuration URL,在下面填写:

    file:///C:/proxy.pac

    ,再点Reload,再点Ok,一路 Ok下去,就可以了。这个方法的巧妙之处(其实一点都不巧妙啦)就在于不用像极速客介绍的那样修改一堆有的没的的Hosts,只要一个“.”就保证了所有 blogspot的子域名可以没有限制的访问(内含GFW关键字的除外),嗯,Enjoy。

    P.S. Linux用户应该不需要Linux版本了吧,照葫芦画瓢对与Linux用户来说应该是再简单不过了,XD

    下面有朋友提到WordPress.com可不可以通过这种方式访问,回答是:当然可以!只需要把proxy.pac用记事本打开,修改为

    function FindProxyForURL(url,host){if(dnsDomainIs(host, ".blogspot.com")){    return "PROXY 72.14.219.190:80";}if(dnsDomainIs(host, ".wordpress.com")){    return "PROXY 72.232.101.41:80";}}

    然 后保存,重启浏览器就可以了。这个原理是利用了该域名的多服务器的特征,每个服务器对应一个IP,GFW只是封杀了其中的一个IP地址,默认的那个,其他 的还是好好的,所以可以用这种方法进行访问,但也取决于网站本身,比如vox.com之前还支持,后来其IP地址为“204.9.178.110”的服务 器修改了设置,所以上方法就不能用了。以此类推,同志们还可以去Hack一下Technorati等等其他好的网站的其他服务器的IP地址,这样照着修改 一下就能畅通无阻的访问了。此致,敬礼。

######################################
flickr的访问:
使用firefox和其插件access flickr.

Creating .deb-Packages With Checkinstall

In howto, linux on November 22, 2007 at 12:20 pm

Version 1.0

Author: Falko Timme <ft [at] falkotimme [dot] com>
Last edited 02/04/2005

Checkinstall is a nice tool to create simple .deb-packages that you can use in your local network (e.g. if you have to install the same piece of software on multiple computers running Debian). It lets you compile and install software from the sources like before, but with the difference that you end up with a simple Debian package which also means that you can easily uninstall the software you just compiled by running dpkg -r!

I will demonstrate the use of checkinstall by compiling and installing the anti-virus software ClamAV on a Debian system.

This howto is meant as a practical guide; it does not cover the theoretical backgrounds. They are treated in a lot of other documents in the web.

This document comes without warranty of any kind!

 

1 Install Checkinstall

It is as easy as 1-2-3:

apt-get install checkinstall

If your system tells you that it does not know a package called checkinstall then add the following line to /etc/apt/sources.list:

deb http://www.backports.org/debian/ woody checkinstall

and run

apt-get update

Then try again to install checkinstall.

 

2 Install ClamAV

We need the ClamAV sources . We will install the software from the /tmp directory.

cd /tmp
wget http://mesh.dl.sourceforge.net/sourceforge/clamav/clamav-0.81.tar.gz
apt-get install libgmp3 libgmp3-dev
groupadd clamav
useradd -g clamav -s /bin/false -c “Clam AntiVirus” clamav
tar xvfz clamav-0.81.tar.gz
cd clamav-0.81/
./configure –sysconfdir=/etc

(Please note: ./configure –help gives a list of all configuration options available.)

make

Now comes the main difference: instead of make install we run

checkinstall -D make install

Answer the question “The package documentation directory ./doc-pak does not exist.
Should I create a default set of package docs? [y]:”
with y.

Then enter a description for your package (e.g. ClamAV 0.81). A summary of the configuration options for your .deb-package will come up:

You can change them here or just hit enter to continue. Now ClamAV will be installed plus a Debian package will be created which you can find in the installation directory /tmp/clamav-0.81 as the final checkinstall summary states:

Now you can copy clamav-0.81_0.81-1_i386.deb to other Debian computers and run

dpkg -i /path/to/clamav-0.81_0.81-1_i386.deb

to install it. If you want to remove it, just run

dpkg -r clamav-0.81

This even works on the computer you compiled ClamAV on! This is a nice way to install software from the sources and remove it if you are unsatisfied with the result.

Blogged with Flock

Creating .deb-Packages With Checkinstall

In howto, linux on November 22, 2007 at 12:20 pm

Version 1.0

Author: Falko Timme <ft [at] falkotimme [dot] com>
Last edited 02/04/2005

Checkinstall is a nice tool to create simple .deb-packages that you can use in your local network (e.g. if you have to install the same piece of software on multiple computers running Debian). It lets you compile and install software from the sources like before, but with the difference that you end up with a simple Debian package which also means that you can easily uninstall the software you just compiled by running dpkg -r!

I will demonstrate the use of checkinstall by compiling and installing the anti-virus software ClamAV on a Debian system.

This howto is meant as a practical guide; it does not cover the theoretical backgrounds. They are treated in a lot of other documents in the web.

This document comes without warranty of any kind!

 

1 Install Checkinstall

It is as easy as 1-2-3:

apt-get install checkinstall

If your system tells you that it does not know a package called checkinstall then add the following line to /etc/apt/sources.list:

deb http://www.backports.org/debian/ woody checkinstall

and run

apt-get update

Then try again to install checkinstall.

 

2 Install ClamAV

We need the ClamAV sources . We will install the software from the /tmp directory.

cd /tmp
wget http://mesh.dl.sourceforge.net/sourceforge/clamav/clamav-0.81.tar.gz
apt-get install libgmp3 libgmp3-dev
groupadd clamav
useradd -g clamav -s /bin/false -c “Clam AntiVirus” clamav
tar xvfz clamav-0.81.tar.gz
cd clamav-0.81/
./configure –sysconfdir=/etc

(Please note: ./configure –help gives a list of all configuration options available.)

make

Now comes the main difference: instead of make install we run

checkinstall -D make install

Answer the question “The package documentation directory ./doc-pak does not exist.
Should I create a default set of package docs? [y]:”
with y.

Then enter a description for your package (e.g. ClamAV 0.81). A summary of the configuration options for your .deb-package will come up:

You can change them here or just hit enter to continue. Now ClamAV will be installed plus a Debian package will be created which you can find in the installation directory /tmp/clamav-0.81 as the final checkinstall summary states:

Now you can copy clamav-0.81_0.81-1_i386.deb to other Debian computers and run

dpkg -i /path/to/clamav-0.81_0.81-1_i386.deb

to install it. If you want to remove it, just run

dpkg -r clamav-0.81

This even works on the computer you compiled ClamAV on! This is a nice way to install software from the sources and remove it if you are unsatisfied with the result.

Blogged with Flock

Wine Review: DirectX 9.0c on Linux with Wine

In Windows, howto, linux on November 22, 2007 at 12:03 pm

Microsoft DirectX is a collection of application programming interfaces for handling tasks related to multimedia, especially game programming and video, on Microsoft platforms. Originally, the names of these APIs all began with Direct, such as Direct3D, DirectDraw, DirectMusic, DirectPlay, DirectSound, and so forth. DirectX, then, was the generic term for all of these Direct-something APIs, and that term became the name of the collection. Over the intervening years, some of these APIs have been deprecated and replaced, so that this naming convention is no longer absolute. In fact, the X has caught on to the point that it has replaced Direct as the common part in the names of new DirectX technologies, including XAct, XInput, and so forth.

Direct3D (the 3D graphics API within DirectX) is widely used in the development of computer games for Microsoft Windows, Microsoft Xbox, and Microsoft Xbox 360. Direct3D is also used by other software applications for visualization and graphics tasks, most notably among the engineering sector for CAD/CAM, because of its ability to quickly render high-quality 3D graphics using DirectX-compatible graphics hardware. As Direct3D is the most widely recognized API in DirectX, it is not uncommon to see the name DirectX used in place of Direct3D.

Wine configuration

This is with a clean configuration directory and running in a 1024×768 virtual desktop.

$ winecfg

Once the .wine directory is built the configuration tool will start and you can set a virtual desktop in the graphics tab if you wish. This is a good time to also set your Audio driver in the Audio tab.

next up is to install a native mscoree.dll and streamci.dll into /system32 from a windows install and set then to native Windows.

Go to ~/.wine/drive_c/windows/system32 and rename d3d8, d3d9, ddraw, dsound, dsound.vxd, quartz dlls to *.bak

You will need to set a large number of dlls to native for the install to work properly. Here is the full list of dlls that need to be set.

“d3d8″=”native”
“d3d9″=”native”
“d3dim”=”native”
“d3drm”=”native”
“d3dx8″=”native”
“d3dxof”=”native”
“dciman32″=”native”
“ddrawex”=”native”
“devenum”=”native”
“dinput”=”native”
“dinput8″=”native”
“dmband”=”native”
“dmcompos”=”native”
“dmime”=”native”
“dmloader”=”native”
“dmscript”=”native”
“dmstyle”=”native”
“dmsynth”=”native”
“dmusic”=”native”
“dplay”=”native”
“dplayx”=”native”
“dpnaddr”=”native”
“dpnet”=”native”
“dpnhpast”=”native”
“dswave”=”native”
“dxdiagn”=”native”
“mscoree”=”native”
“quartz”=”native”
“streamci”=”native”

Installing Directx

Download DirectX 9.0c November release from here.

The directx_nov2007_redist.exe executable will extract the installer files to a directory of your choice.

tom@tuxonfire ~ $ wine directx_nov2007_redist.exe
fixme:advapi:DecryptFileA "z:\\home\\tom\\directx-9\\" 00000000
fixme:midi:OSS_MidiInit Synthesizer supports MIDI in. Not yet supported.
tom@tuxonfire ~ $

Now cd to the directory where you choose to extract the DirectX installer and run DXSETUP.EXE.

tom@tuxonfire ~ $ cd /home/tom/directx-9
tom@tuxonfire ~/directx-9 $ wine DXSETUP.EXE
fixme:midi:OSS_MidiInit Synthesizer supports MIDI in. Not yet supported.

Run winecfg again and set d3d8, d3d9, ddrawex, dinut, dinput8 to builtin wine.

Now lets run dxdiag.exe

tom@tuxonfire ~/directx-9 $ cd /home/tom/.wine/drive_c/windows/system32
tom@tuxonfire ~/.wine/drive_c/windows/system32 $ wine dxdiag.exe
fixme:ole:CoInitializeSecurity ((nil),-1,(nil),(nil),1,3,(nil),0,(nil)) - stub!

We can now test ddraw, ddraw 3D, D3D8, and D3D9

Direct Sound test:

Now we need to install gm.dls to test Direct Music, this driver file goes into ~/.wine/drive_c/windows/system32/drivers

Direct Play test:

You will notice in system32 d3dx9_24.dll up to d3dx9_36.dll is now installed, this really helps when you run into a game that needs these additional DirectX dlls.

Now you have the option to run most DirectX dlls in native or builtin mode, for example if you have a game that’s crashing on the builtin Wine quartz.dll you can test the game with the native Windows dll to see if this will improve the situation.

Keep in mind d3d8, d3d9, ddraw will only work as builtin, and in most cases you should try to use builtin dsound and dinput. I have had limited success with (dsound and dinput) in native Windows mode btw… The reason why these dlls have to be used in builtin mode is there need for direct access to your hardware. direct music and direct play can be used in native windows mode in most circumstances.

Feel free to comment about this post at the wine-forum.

Blogged with Flock

关于Linux操作系统下C语言编程的注意事项

In C/C++, howto, linux on November 21, 2007 at 12:28 am

关于Linux操作系统下C语言编程的注意事项 — IT技术 – 赛迪网

一、工具的使用

  
1、学会使用vim/emacs,vim/emacs是linux下最常用的源码编辑具,不光要学会用它们编辑源码,还要学会用它们进行查找、定位、替换等。新手的话推荐使用vim,这也是我目前使用的文本编辑器。

  
2、学会makefile文件的编写规则,并结合使用工具aclocal、autoconf和automake生成makefile文件。

  
3、掌握gcc和gdb的基本用法。掌握gcc的用法对于构建一个软件包很有益处,当软件包包含的文件比较多的时候,你还能用gcc把它手动编译出来,你就会对软件包中各个文件间的依赖关系有一个清晰的了解。

  
4、掌握svn/cvs的基本用法。这是linux,也是开源社区最常用的版本管理系统。可以去试着参加sourceforge上的一些开源项目。

  

二、linux/unix系统调用与标准C库

  系统调用应用软件与操作系统的接口,其重要性自然不用说,一定要掌握。推荐学习资料为steven先生的UNIX环境高级编程(简称APUE)。

  

三、库的学习

  无论是在哪个平台做软件开发,对于库的学习都很重要,linux下的开发库很多,我主要介绍一下我常常用到的一些库。

  
1、glib库

  glib 库是gtk+和gnome的基础库,并具是跨平台的,在linux、unix和windows下都可以用。glib库对于linux平台开发的影响就像 MFC对windows平台开发的影响一样,很多开源项目都大量的使用了glib库,包括gimp、gnome、gaim、evolution和 linux下的集群软件heartbeat。因为glib库自带有基本的数据结构实现,所以在学习glib库的时候可以顺便学习一下基本的数据结构(包括链表、树、队列和hash表)。

  
2、libxml库

  libxml是linux平台下解析XML文件的一个基础库,现在很多实用软件都用XML格式的配置文件,所以也有必要学习一下。

  
3、readline库

  readline 库是bash shell用的库,如果要开发命令行程序,那么使用readline库可以减少很多工作量,比如bash里的命令行自动补全,在readline里就已经有实现,当然你也可以用自己的实现替代库的行为。readline库有很多网站介绍的,只要google一下readline就可以找到一堆了。

  
4、curses库

  curses 库以前是vi程序的一部分,后来从vi里提取出来成为一个独立的库。curses库对于编写终端相关的程序特别有用,比如要在终端某一行某一列定位输出,改变终端字体的颜色和终端模式。linux下的curses库用的是GNU实现的ncurses(new curses的意思)。  
5、gtk+和KDE库

  这两个库是开发GUI应用程序的基础库,现在linux下的大部份GUI程序都是基于这两个库开发的,对于它们 的学习也是很有必要的。

  

四、网络的学习

  网络这个东西太宽了,推荐学习资料steven先生的UNIX网络编程(简称UNP)和TCP/IP协议详解,更进一步的话可以学习使用libnet编写网络程序

Powered by ScribeFire.

关于Linux操作系统下C语言编程的注意事项

In C/C++, howto, linux on November 21, 2007 at 12:28 am

关于Linux操作系统下C语言编程的注意事项 — IT技术 – 赛迪网

一、工具的使用

  
1、学会使用vim/emacs,vim/emacs是linux下最常用的源码编辑具,不光要学会用它们编辑源码,还要学会用它们进行查找、定位、替换等。新手的话推荐使用vim,这也是我目前使用的文本编辑器。

  
2、学会makefile文件的编写规则,并结合使用工具aclocal、autoconf和automake生成makefile文件。

  
3、掌握gcc和gdb的基本用法。掌握gcc的用法对于构建一个软件包很有益处,当软件包包含的文件比较多的时候,你还能用gcc把它手动编译出来,你就会对软件包中各个文件间的依赖关系有一个清晰的了解。

  
4、掌握svn/cvs的基本用法。这是linux,也是开源社区最常用的版本管理系统。可以去试着参加sourceforge上的一些开源项目。

  

二、linux/unix系统调用与标准C库

  系统调用应用软件与操作系统的接口,其重要性自然不用说,一定要掌握。推荐学习资料为steven先生的UNIX环境高级编程(简称APUE)。

  

三、库的学习

  无论是在哪个平台做软件开发,对于库的学习都很重要,linux下的开发库很多,我主要介绍一下我常常用到的一些库。

  
1、glib库

  glib 库是gtk+和gnome的基础库,并具是跨平台的,在linux、unix和windows下都可以用。glib库对于linux平台开发的影响就像 MFC对windows平台开发的影响一样,很多开源项目都大量的使用了glib库,包括gimp、gnome、gaim、evolution和 linux下的集群软件heartbeat。因为glib库自带有基本的数据结构实现,所以在学习glib库的时候可以顺便学习一下基本的数据结构(包括链表、树、队列和hash表)。

  
2、libxml库

  libxml是linux平台下解析XML文件的一个基础库,现在很多实用软件都用XML格式的配置文件,所以也有必要学习一下。

  
3、readline库

  readline 库是bash shell用的库,如果要开发命令行程序,那么使用readline库可以减少很多工作量,比如bash里的命令行自动补全,在readline里就已经有实现,当然你也可以用自己的实现替代库的行为。readline库有很多网站介绍的,只要google一下readline就可以找到一堆了。

  
4、curses库

  curses 库以前是vi程序的一部分,后来从vi里提取出来成为一个独立的库。curses库对于编写终端相关的程序特别有用,比如要在终端某一行某一列定位输出,改变终端字体的颜色和终端模式。linux下的curses库用的是GNU实现的ncurses(new curses的意思)。  
5、gtk+和KDE库

  这两个库是开发GUI应用程序的基础库,现在linux下的大部份GUI程序都是基于这两个库开发的,对于它们 的学习也是很有必要的。

  

四、网络的学习

  网络这个东西太宽了,推荐学习资料steven先生的UNIX网络编程(简称UNP)和TCP/IP协议详解,更进一步的话可以学习使用libnet编写网络程序

Powered by ScribeFire.

Windows Network Trafic Management (to be contiuned and commented)

In Windows, howto on November 19, 2007 at 11:18 pm

In windows to show the network trafic:
netsh interface ipv4 show subinterfaces

Blogged with Flock

用移动硬盘代替DVD光盘安装Vista

In Windows, howto on November 18, 2007 at 5:21 pm

没有DVD刻录机的朋友,又想安装单系统的Vista,就可以将安装文件放在移动硬盘上,,从移动硬盘启动计算机来安装Vista了!这样安装的效果和从光盘引导安装是一样的。

  1.在XP下将一个空间足够的移动硬盘分区激活(在计算机治理的”磁盘治理”中,右键单击需要的分区,选择”将磁盘分区标为活动的”);

  2.用DaemonToolsT将光盘中所有文件复制到移动硬盘;

  3.在XP的命令提示符状态下运行 X:\boot\bootsect /nt60 x: (X即移动硬盘分区盘符)这一步是让移动硬盘成为可引导分区

  4.重启电脑,在CMOS设置里将第一引导设置为USB引导;

  5.用移动硬盘顺利引导,开始安装Vista。这个过程与光盘安装是一样的,可以格式化您的C盘,安装为单系统。

Blogged with Flock

ati graphical driver 8.42 fglrx for Ubuntu linux

In Blogged, howto, linux on November 17, 2007 at 5:43 pm

If anything wrong, run this command to recover your graphics configuration:
sudo dpkg-reconfigure xserver-xorg
####################################################
Hello everyone, I have a little guide I cooked up, which is basically a modified version of Forlongs guide. I had some trouble getting this all to work, so I decided I would try to help others who may have had some of the problems I was encountering, like a white screen, low graphics, exct. This guide was intended for a fresh install of Gutsy on a 32 bit system, and will work, Ill post the pix to verify my properly working installation. I gotta say that Ive had great success using this driver, glxgears = 5000fps, compiz fusion = 300+fps, nice and smooth 3d & 2d, some video playback trouble, but I found temporarily disabling compiz fusion fixed that problem. So anyways, I hope this helps some of you out.

1. Remove the old driver (if present)

Go to System → Administration → Restricted Drivers Manager and choose disable.

Or remove it yourself:

sudo apt-get remove xorg-driver-fglrx

2. Blacklist old fglrx module:

sudo gedit /etc/default/linux-restricted-modules-common

And insert fglrx – it should look like this then:

DISABLED_MODULES=”fglrx”

3. Reboot now.

4. Download the driver installer to your home folder

http://www2.ati.com/drivers/linux/at…x86.x86_64.run

5. Install necessary packages (to make Debian packages out of the driver, you will need you gutsy installation disc for this.)

sudo apt-get install module-assistant build-essential fakeroot dh-make debhelper debconf libstdc++5 linux-headers-generic

6. Create .deb packages

bash ./ati-driver-installer-8.42.3-x86.x86_64.run –buildpkg Ubuntu/gutsy

7. Install .deb packages

sudo dpkg -i fglrx-kernel-source_8.42.3-1_i386.deb xorg-driver-fglrx_8.42.3-1_i386.deb

8. Compile kernel module

sudo m-a prepare,update

sudo m-a build,install fglrx-kernel

sudo depmod

9. Time for the initial configuration of fglrx.

sudo aticonfig –initial –force

sudo aticonfig –overlay-type=Xv

10. Configure the driver (If needed, which it wont be on a fresh install)

sudo gedit /etc/X11/xorg.conf

Make sure “fglrx” is set for the Driver in the Section “Device”.

And if present, remove:

Section “Extensions”

Option “Composite” “0″ # or “Disable”

EndSection

As well as

Section “ServerFlags”

Option “AIGLX” “off”

EndSection

11. Now you need to modify your Whitelist for Compiz Fusion

sudo gedit /etc/xdg/compiz/compiz-manager

Once that opens up add this under the last line:

WHITELIST=”nvidia intel ati radeon i810 fglrx”

12. CONGRATZ!! You should be gold now, lol, as a recomended option though I would go into Synaptic Package Manager and install:
“compizconfig-settings-manager”
which will give you all the compiz fusion options we all thirst for!!!








Howto Setup SMB Server using NTFS partitions on Ubuntu

In howto, linux, server on November 15, 2007 at 12:24 pm

In GNOME, there is no configure tools like “kdenetwork-filesharing” in KDE, which will automatically add an option ‘msdfs proxy = no’, this made your folders can not be accessed properly within your workgroup. Maybe this is a bug or a carelessness, but just like KDE, too many bugs, it’s ok, I am used to it. Each time I install Linux distro with KDE, I must install some Gnome programs to make the programs installation job done without keep facing KDE’s crash.
Actually in Gnome such a tool is not necessary, Gnome is simple and seamlessly works together with (almost) all the service. SYSTEM-ADMINISTRATION-SHARED FOLDERS is the right place to configure you samba server simply. Although too few stuff there, but these are the essential part. If you prefer expert mode, why not use vi to modify /etc/samba/smb.conf, gui tools is just for beginners and lazy peoples like me.

Why I select Ubuntu. At beginning, I tried Opensuse, the default setting doesn’t show Chinese characters properly, and the essential problem is that the default setting for mount NTFS partitions is not writeable. So I gave it up. Forgiving me don’t want to spend time on to learn how to change fonts and mount options. I prefer more human being friendly default setting, like Ubuntu.

  1. To share files (here what I want to shared is the folders from NTFS partitions)
    For security reason, I prefer add some password for my server, the samba default setting doesn’t allow guest access as well.
    In this case, you should use ’sudo smbpasswd -a user’ to add user and password. Here the user added must exist in the server system users database, otherwise, error message of “Failed to modify password entry for user” will come out.

    • Folders from NTFS partitions are shared

      1. the partition is automatically mounted from /etc/fstabs
      Although when you shared folders from nautilus, there are some error messages telling you access denied stuff, but it doesn’t matter, the Windows will access it properly. But Linux client can not do this.
      Because the access permission is just for the root, while not you. Linux box do the permission check more than the Windows boxes.
      2. the partition is mounted by you after boot from MY COMPUTER
      In this case, there will not any error messages when you share the folders from Nautilus. And Windows, Linux clients can access it very well. Because this time the access permission is for the current user,you. But this is not suitable for files-sharing server.

      The solution is 1). For Windows clients it works well. For Linux clients this job can be done by ‘mount -t smbfs -o username=yourusername,password=youruserpassword //server/dir /mnt/folder’. Here smbfs is need to be installed.

    • Whole NTFS partition is shared
      Just share it. It works well for Windows and Linux clients. But the flexibility is limited, you can not specify folders to share.

  2. Printer Server

    In Gnome, the samba configure tool is still not necessary. Normally the printers in the SYSTEM-ADMINISTRATION-PRINTING will be added to smb server, except bugs exist.
    my HP LaserJet 2200 with usb cable can be founded by Ubuntu automatically and works locally. But from the client machines, the printer is invisible. While the HP Deskjet 1220C can work well both local and client machines.
    The reason is the Gnome auto founded driver is not so correct, although it’s ok for local. Here I use ‘kcontrol’ to add the printer, in kcontrol this is one driver select option “usb port”, with this option everything works well.

    Maybe this is a bug for Gnome system-config-printer, where is no option for the usb port, just list some printers the ubuntu founded, and some specific port. Just no usb port, but just the auto founded usb printer is not correct.

Hide Removable Drive Icons from Your Ubuntu Desktop

In howto, linux on November 13, 2007 at 8:28 pm

I prefer a clean desktop with no icons cluttering it up, but by default Ubuntu adds icons to the desktop for every single removable drive that you attach to your system.

Having recently transitioned to using Ubuntu full-time at home (instead of just part-time), this was one of the first things I wanted to disable. Sadly there’s no option in the default configuration screens, so we’ll have to use the “registry editor” for Ubuntu, called gconf-editor.

Just type in gconf-editor into the Alt+F2 run dialog to open the app.

Now browse down to the following key:

apps \ nautilus \ desktop

You should see a key in the right-hand pane called volumes_visible. Remove the checkbox from it, and the icons will instantly disappear from the desktop. Remember that you can always access the drives from the “Computer” icon, or easily in the file browser.

I’m much happier now with my beautiful desktop.

SMB:Configuring your computer as a server

In howto, linux, server on November 11, 2007 at 4:09 pm

A fairly comprehensive graphical Samba configuration tool is available for KDE, by installing the “kdenetwork-filesharing” package. Once install, you can find it by launching the KDE Control Center. (Alt-F2 and then type kcontrol). Browse to Internet & Network > Samba. It is fairly easy to use.

A less friendly but also graphical tool is Swat, a web-based interface.

The following tips show how to do some basic things without installing additional software, using the command line. It is not difficult, just be careful with typos.

First open a terminal: Applications > System Tools > Terminal and open the file smb.conf

sudo nano -w /etc/samba/smb.conf

How to Save: To save in nano use “ctrl/o” than “ctrl/x”.

Tip: Replacing nano with gedit gives you a nice graphical editor.

The file *smb.conf* is divided in several sections:

Global SettingsDebugging/AccountingAuthenticationPrintingFile sharingMiscShare Definitions

Let’s start with Global Settings. Here you will see several lines, which you can also see in the graphical networktool like workgroup and wins server. If you changed everything to your liking already then you can skip this section, if not change to what you need. If you do not know what items mean, leave them be and read the [WWW] relevant part in the real Samba-howto instead of randomly changing them. It will save you trouble-shooting later.

The important part for us is File sharing. We need to change:

[homes]comment = Home Directoriesbrowseable = no

# By default, the home directories are exported read-only. Change next# parameter to 'yes' if you want to be able to write to them. writable = no

This describes your /home folder. Usually you want to share this folder in a home-environment, because these are the files you want to share. To do so, make the following changes:

[homes]comment = Home Directoriesbrowseable = yes

# By default, the home directories are exported read-only. Change next# parameter to 'yes' if you want to be able to write to them. writable = yes

This finishes sharing your /home folder. The last thing we need to do is fixing a user.

Add users who can access your shares with the ’smbpasswd’ command.

sudo  smbpasswd -a username

New SMB password:Retype new SMB password:Added user username.

NOTE: the username used here should be a real user setup on your PC/Server. Reload Samba for every change to users/passwords or ’smb.conf’

sudo /etc/init.d/samba reload

That’s the basis of Samba file-sharing. Please leave your comments about what else is needed here.

Back to top

Complicating things a little

We started with the base of Samba file-sharing. The above-mentioned items should be enough to get you started. Next we will add details that you might or might not need.

Back to top

If you have more the one networkcard

If you have more the one networkcard (or interface) then you have to define where you want Samba to run. In smb.conf under the [global] section, add:

"interfaces = 127.0.0.1, 192.168.0.31/24""bind interfaces only = yes"

The first address (127.0.0.1), is a loopback network connection (it’s your own machine). The second address (192.168.0.31), is the address of the card you want Samba to run on, the second number (24) is the subnet default for a CLASS-C network. It may vary depending on your network.

With “bind interfaces only” you limit which interfaces on a machine will serve SMB requests.

You can limit which IP address can connect to your Samba server adding these lines:

"hosts allow = 127.0.0.1, 192.168.0.31, 192.168.0.32""hosts deny = 0.0.0.0/0"

The loopback address must be present in the first line. The second line deny access from all IP address not in the first line.

Back to top

Sharing CUPS Printers

If You would like to share Your printers make the following changes to Samba:

If not already done create the Samba-user You want the share to be used by.

In smb.conf uncomment and change the lines ending up with the following configuration:

########## Printing ##########

# If you want to automatically load your printer list rather# than setting them up individually then you'll need this  load printers = yes

# [...] // Some BSD printing stuff, do not edit if You do not need to

# CUPS printing.  See also the cupsaddsmb(8) manpage in the# cupsys-client package.  printing = cups  printcap name = cups

and in the Share Definitions section append and/or modify the [printers] part ending up like this:

# ======================= Share Definitions =======================# [...] // File and Folder sharing, do not edit if You do not need to

[printers]  comment = All Printers  browseable = no  path = /tmp  printable = yes  public = yes  writable = no  create mode = 0700  printcap name = /etc/printcap  print command = /usr/bin/lpr -P%p -r %s  printing = cups

Some explanation what is done:

the [printers] part defines the default-behavior for all the printers that are mentioned in “printcap name”. A sort of template how to create shares for these printers. This template is applied if “load printers” is set to true. For more detailed explanation refer to the Samba documentation.

And do not forget to reload Samba:

sudo /etc/init.d/samba reload

Back to top

SMB:Configuring your computer as a server

In howto, linux, server on November 11, 2007 at 4:09 pm

A fairly comprehensive graphical Samba configuration tool is available for KDE, by installing the “kdenetwork-filesharing” package. Once install, you can find it by launching the KDE Control Center. (Alt-F2 and then type kcontrol). Browse to Internet & Network > Samba. It is fairly easy to use.

A less friendly but also graphical tool is Swat, a web-based interface.

The following tips show how to do some basic things without installing additional software, using the command line. It is not difficult, just be careful with typos.

First open a terminal: Applications > System Tools > Terminal and open the file smb.conf

sudo nano -w /etc/samba/smb.conf

How to Save: To save in nano use “ctrl/o” than “ctrl/x”.

Tip: Replacing nano with gedit gives you a nice graphical editor.

The file *smb.conf* is divided in several sections:

Global SettingsDebugging/AccountingAuthenticationPrintingFile sharingMiscShare Definitions

Let’s start with Global Settings. Here you will see several lines, which you can also see in the graphical networktool like workgroup and wins server. If you changed everything to your liking already then you can skip this section, if not change to what you need. If you do not know what items mean, leave them be and read the [WWW] relevant part in the real Samba-howto instead of randomly changing them. It will save you trouble-shooting later.

The important part for us is File sharing. We need to change:

[homes]comment = Home Directoriesbrowseable = no

# By default, the home directories are exported read-only. Change next# parameter to 'yes' if you want to be able to write to them. writable = no

This describes your /home folder. Usually you want to share this folder in a home-environment, because these are the files you want to share. To do so, make the following changes:

[homes]comment = Home Directoriesbrowseable = yes

# By default, the home directories are exported read-only. Change next# parameter to 'yes' if you want to be able to write to them. writable = yes

This finishes sharing your /home folder. The last thing we need to do is fixing a user.

Add users who can access your shares with the ’smbpasswd’ command.

sudo  smbpasswd -a username

New SMB password:Retype new SMB password:Added user username.

NOTE: the username used here should be a real user setup on your PC/Server. Reload Samba for every change to users/passwords or ’smb.conf’

sudo /etc/init.d/samba reload

That’s the basis of Samba file-sharing. Please leave your comments about what else is needed here.

Back to top

Complicating things a little

We started with the base of Samba file-sharing. The above-mentioned items should be enough to get you started. Next we will add details that you might or might not need.

Back to top

If you have more the one networkcard

If you have more the one networkcard (or interface) then you have to define where you want Samba to run. In smb.conf under the [global] section, add:

"interfaces = 127.0.0.1, 192.168.0.31/24""bind interfaces only = yes"

The first address (127.0.0.1), is a loopback network connection (it’s your own machine). The second address (192.168.0.31), is the address of the card you want Samba to run on, the second number (24) is the subnet default for a CLASS-C network. It may vary depending on your network.

With “bind interfaces only” you limit which interfaces on a machine will serve SMB requests.

You can limit which IP address can connect to your Samba server adding these lines:

"hosts allow = 127.0.0.1, 192.168.0.31, 192.168.0.32""hosts deny = 0.0.0.0/0"

The loopback address must be present in the first line. The second line deny access from all IP address not in the first line.

Back to top

Sharing CUPS Printers

If You would like to share Your printers make the following changes to Samba:

If not already done create the Samba-user You want the share to be used by.

In smb.conf uncomment and change the lines ending up with the following configuration:

########## Printing ##########

# If you want to automatically load your printer list rather# than setting them up individually then you'll need this  load printers = yes

# [...] // Some BSD printing stuff, do not edit if You do not need to

# CUPS printing.  See also the cupsaddsmb(8) manpage in the# cupsys-client package.  printing = cups  printcap name = cups

and in the Share Definitions section append and/or modify the [printers] part ending up like this:

# ======================= Share Definitions =======================# [...] // File and Folder sharing, do not edit if You do not need to

[printers]  comment = All Printers  browseable = no  path = /tmp  printable = yes  public = yes  writable = no  create mode = 0700  printcap name = /etc/printcap  print command = /usr/bin/lpr -P%p -r %s  printing = cups

Some explanation what is done:

the [printers] part defines the default-behavior for all the printers that are mentioned in “printcap name”. A sort of template how to create shares for these printers. This template is applied if “load printers” is set to true. For more detailed explanation refer to the Samba documentation.

And do not forget to reload Samba:

sudo /etc/init.d/samba reload

Back to top

SMB vs NFS

In howto, linux, server on November 11, 2007 at 1:41 am

SMB是Server Messege Block的缩写,其实就是实现Windows文件和打印共享的基础协议,后来在*nix下通过samba实现了smb协议,所以可以达成不同系统之间的文件和打印共享互通。
而NFS是在内核级别实现的Network File System。通过NFS协议import的分区,可以当成本机的磁盘来使用。所有读写都是内核负责,所以效率上比SMB要好,但是仅仅能实现文件读写,没有打印服务。

smb service

In howto, linux, server on November 11, 2007 at 1:35 am
为了实现windows 和 Linux以及其他操作系统之间的资源共享,软件商推出nfs
和samba两种解决方式。由于市场上缺乏象pc-nfs那样的客户端工具,使得Linux和windows的资源共享变得复杂。Samba的出现解决了
这一问题,它以其简洁、实用、灵活配置的特点受到越来越多人们的广泛关注。

  Windows利用SMB协议来实现操作系统间文件和打印机共享,而Samba本身具备SMB协议,它实现局域网内和Windows系列计算机的资源共享。

  本文就Samba在Linux系统下的配置为重点,讨论局域网内windows 与 Linux 的资源共享。

  一、Samba 介绍

  1、SMB协议

 
 SMB (Server Message Block,服务信息块)
协议,是局域网上的共享文件/打印机的一种协议,它可以为网络内部的其他windows和linux
机器提供文件系统、打印服务。SMB的工作原理是让NetBIOS和SMB运行在TCP/IP之上,且使用NetBIOS的nameserver让
linux机器可以在windows 网络邻居里被浏览。

  2、Samba

  Samba是用来实现SMB的一种软件,由澳大利亚的Andew Tridgell开发,是一种在Linux 环境里运行的自由软件。它可以完成如下功能:

  文件服务和打印服务,实现Windows和Linux的资源共享。

  登录服务器,可以作为局域网的服务器。

  作为主域控制器。

  WINS服务器。

  支持SSL。

  支持SWAT。

  二、 Samba服务

  1、 核心进程

  Samba 有两个守护进程:smbd 和nmbd,它们是Samba的核心进程。nmbd进程使其他计算机浏览Linux服务器,Smbd进程在SMB服务请求到达时对它们进行处理,并且为使用或共享的资源进行协调。

smbd 是提供数据传输服务,也就是我们说的Samba服务的主要功能
nmbd 是提供名称解析服务的,就是说开启此服务我们可以通过主机名来访问共享目录

  2、 启动服务

  Samba 有两种启动方式:Daemon形式和Inetd形式。

  (1)Daemon形式 建立启动脚本:rc.samba

  smbd -D -d1

  nmbd -D -d1

  -D 表示以Daemon形式执行;-d1 表示除错记录级别

  执行脚本文件rc.samba

  (2)Inetd形式

  设置文件:/etc/services

  netbios -ssn 139/ tcp

  netbios -ns 137/ udp

  设置文件:/etc/inetd.conf

  netbios -ssn stream tcp nowait root /usr/sbin/smbd smbd

  netbios -ns dgram udp wait root /usr/sbin/nmbd nmbd

  重启动Inetd daemon

  # kill -HUP 1

  3、 客户工具 smbclient

  Smbclient命令用来存取远程Samba服务器上的资源。其命令形式与ftp相似。

  命令语法是:#smbclient [password] [option]

  (1) 解释:servicename是要连接的资源名称,资源名称的形式如下:

  //server/service server 是远程服务器的NetBIOS名字,对于windows服务器而言,就是出现在网上邻居中的名字。

  Service是各server所提供的资源的名字。

  pssword 是存取该资源所需的口令

  option 各种命令选项,其中 -L 用于列出远程服务器提供的所有资源

  -I 指定远程服务器的IP地址。此时,servicesname 中的NetBIOS名部分将被忽略。

  (2)多种smbclient命令:

  执行smbclient命令成功后,进入smbclient环境,出现提示符: smb:\&gt;

  这里有许多命令和ftp命令相似,如cd 、lcd、get、megt、put、mput等。通过这些命令,我们可以访问远程主机的共享资源。

  4、 Samba系统装载与卸载

  (1) 装载其他主机的资源

  我们可以利用Samba提供的smbmount命令,装载其他主机的共享资源。

  Smbmount的命令语法:# smbmount

  其中 servicename 是资源名,mount-point是安装点。

  例如: # smbmount “\\server\tmp” -c ‘ mount /mnt’

  表示:把名字为“server”的计算机上的共享资源“tmp”的内容装载到本地的 /mnt

  目录下。

  (2) 卸载资源

  卸载一个已经装载的SMB文件系统,使用smbunmount命令,同时指定要卸载的装载点。 例如: # smbunmount / mnt

  三、Samba配置

  Samba组件的配置文件是 /etc/smb.conf ,该文件几乎包含了Samba系统程序运行时所需的所有配置信息。

  1、 配置选项

  配置文件中有比较重要的几个节:[gloabal]、[homes]、[printers],下面分别给与说明。

  (1)[gloabal]节 在全局参数中,参数的设置直接影响samba系统。

  NetBIOS name:设置主机名称

  Workgroup:用来指定主机所在网络上所属的NT域名或者工作组名称。格式是

  Workgroup= Nt Domain-Name or workgroup-name

  Server string:用来设置本机描述,缺省是 Samba Server

  Host Allow:它允许设置哪些领域的机器可以访问它的Samba服务器

  Load printers:允许自动加载打印机列表,而不需要单独设置每一台打印机。

  Interface:配置Samba使用多个网络界面。

  Domain controller: 仅当网络中有一台在安装时设置为主域控制器时使用此选项。

  Security: 设置安全参数,定义安全模式。Samba 的安全模式有四种

  Share、 user、 server 、domain

  encrypt passwords 、smb passwd file:用于适用加密口令。

  下面是一段参数配置例子:

  [global]

  smb passwd file = /etc/smbpasswd

  remote announce = 172.18.158.234 172.18.153.55 172.18.153.255

  dns proxy = no

  security = user

  encrypt passwords = yes

  server string = Ftp Server

  workgroup = turing

  socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192

  log file = /var/log/samba/log.%m

  load printers = yes

  guest account = dscan

  remote browse sync = 172.18.158.234 172.18.153.55 172.18.153.255

  printcap name = /etc/printcap

  max log size = 50

  hosts allow = 172.18.158. 172.18.153. 127.

  … …

  (2)[homes]节 所有使用者的home目录

  当任何一个客户访问Samba服务器时,在网络资源中都能出现自己的home目录共享。其配置如下:

  [homes]

  comment = Hnnw Directories

  browseable = no

  writable = yes

  (3)用户共享目录

  用来指定某一特定用户组或者用户拥有访问权限的目录配置,下列参数配置仅有hnnw组的用户有权访问目录/home/samba。

  [public]

  comment = Public Hnnw

  path = /home/samba

  public = yes

  writable = yes

  printable = no

  write list = @hnnw

  2、 用户映射

  全局参数“username map”用来控制用户映射,它允许管理员指定一个映射文件,该文件包含了在客户机和服务器之间进行用户映射的信息。

  如:username map= /etc/smbuser

  用户映射经常在windows 和linux 主机间进行。 两个系统拥有不同的用户账号,用户映射的目的是将不同的用户映射成为一个用户,便于共享文件。

  下面是一个映射文件的例子:

  # Map Windows admin to root

  root=admin administrator

  ;Map the member of developer to studio

  studio = @developer

  等号左边是单独的Linux账号,等号右边是要映射的账号列表。

  服务器逐行分析映射文件,如果提供的账号和某行有右侧列表中的账号匹配,就把它

  替换为等号左边的账号。

  3、 使用加密口令

 
 新版本的windows
95以及windows98、winnt(sp3以上版本),在网络传输中仅传递加密口令作为用户认证的信息。这类客户机和不支持加密口令并且以user
安全级运行的Samba服务器通讯时,会出现故障。为了正常的通讯,samba服务器使用加密口令。下面讨论如何在samba中使用加密口令。

  (1) 口令文件 /etc/smbpasswd

  为了使用加密口令,samba 需要一份口令文件(/etc/smbpasswd),并且该文件应该和Linux的口令文件(/etc/passwd)保持同步。下面是生成文件命令:

  # cat /etc/password | mksmbpasswd &gt;/etc/smbpasswd

  smbpasswd 是需要的口令文件,其权限是0600,所有者是root

  smbpasswd和passwd文件的记录对应,密码部分不同。密码有两部分组成,每部分

  是32个”X”,前部分用于和Lanman通讯,后部分和Windows NT通讯。

  Root用户可以使用smbpasswd命令为每个用户设定samba口令。

  (2) 修改配置文件 /etc/smb.conf

  要使Samba使用加密口令,需要在配置文件smb.conf中加入如下参数。

  Encrypt passwords=yes

  Smb passwd file= /etc/smbpasswd

  第一行通知samba使用加密口令,第二行给出口令文件的位置。

  (3) 重启动samba 服务。

  修改完配置文件后,需要重新启动samba服务,可用如下命令:

  # /usr/sbin/samba restart

  4、windows系统中的明码口令使用

 
 Samba系统中使用明码口令作为连接SMB的默认设置。当SMB服务器对协商协议做出响应时,响应信息包含了一位,以说明服务器是否支持询问或者响应

密。随着win95的网络重定向更新程序的发布,Microsoft修改了默认值,这样,windows客户就不会向不支持加密的服务器发送明码口令了。

  在这种情况下,有两种解决办法:

  (1)设置Samba服务器使用加密口令

  (2)让windows客户使用明码口令

  这里选用第2种解决办法,通过修改注册表来实现。下面对win95/win98、winnt用户分别给与说明。

  (1)win98/win95系统用户

  在注册表中加入下列注册字,并重新启动机器:

  [HKLM\System\CurrentCntrolSet\Services\VxD\VNETSUP]

  “EnablePlainTextPAssword”= dword:00000001

  (2)Winnt系统用户

  修改注册表,加入下列注册表项,并重新启动机器:

  [HKLM\System\CurrentCntrolSet\Services\Rdr\Parameters]

  “EnablePlainTextPAssword”= dword:00000001

  四、Samba应用

  1、 windows资源共享与使用

  (1)windows资源共享

  a. 使用TCP/IP协议作为网络默认通讯协议

  b. 修改网络配置,设置文件和打印机共享。

  c. 设置好计算机名和所属工作组

  d.共享系统资源

  (2)在windows系统中使用Linux共享资源

  a. 登录进入windows网络

  b. 通过网上邻居查看、使用共享资源。

  c. 命令行下工具使用共享资源

  使用命令行下的net.txt工具来查看、使用共享资源:

  net use 命令的语法: c:&gt;net use X:\\servername\sharename

  在这里,X:是共享的驱动器盘符,\\servername\sharename是到共享的UNC的网络路径。

  例如: c:\&gt;net use h:\\hey\myfile

  表示:将hey机器上的myfile共享资源映射为本地的h盘

  2、Linux资源共享与使用

  (1)将Linux 的资源共享

  通过编辑Samba配置文件,添加需要共享的Linux资源。同时可以设定访问此资源的用户群及其访问权限。下面是一段例子,将本机的 /public/data 目录共享,所有人都有读写权限。

  [data]

  comment = Public Data

  path = /public/data

  public = yes

  writable = yes

  printable = no

  (2)在Linux中使用共享资源

  可以使用smbclient命令,访问所有的Samba资源。具体使用方法见前述。

  五、Samba应用程序

  smbclient :访问所有共享资源

  smbstatus: 列出当前所有的samba连接状态

  smbpasswd:修改samba用户口令、增加samba用户。

  Nmblookup:用于查询主机的NetBIOS名,并将其映射为IP地址

  Testparam: 用于检查配置文件中的参数设置是否正确

  Linux 系统中的Samba配置

Powered by ScribeFire.

smb service

In howto, linux, server on November 11, 2007 at 1:35 am
为了实现windows 和 Linux以及其他操作系统之间的资源共享,软件商推出nfs
和samba两种解决方式。由于市场上缺乏象pc-nfs那样的客户端工具,使得Linux和windows的资源共享变得复杂。Samba的出现解决了
这一问题,它以其简洁、实用、灵活配置的特点受到越来越多人们的广泛关注。

  Windows利用SMB协议来实现操作系统间文件和打印机共享,而Samba本身具备SMB协议,它实现局域网内和Windows系列计算机的资源共享。

  本文就Samba在Linux系统下的配置为重点,讨论局域网内windows 与 Linux 的资源共享。

  一、Samba 介绍

  1、SMB协议

 
 SMB (Server Message Block,服务信息块)
协议,是局域网上的共享文件/打印机的一种协议,它可以为网络内部的其他windows和linux
机器提供文件系统、打印服务。SMB的工作原理是让NetBIOS和SMB运行在TCP/IP之上,且使用NetBIOS的nameserver让
linux机器可以在windows 网络邻居里被浏览。

  2、Samba

  Samba是用来实现SMB的一种软件,由澳大利亚的Andew Tridgell开发,是一种在Linux 环境里运行的自由软件。它可以完成如下功能:

  文件服务和打印服务,实现Windows和Linux的资源共享。

  登录服务器,可以作为局域网的服务器。

  作为主域控制器。

  WINS服务器。

  支持SSL。

  支持SWAT。

  二、 Samba服务

  1、 核心进程

  Samba 有两个守护进程:smbd 和nmbd,它们是Samba的核心进程。nmbd进程使其他计算机浏览Linux服务器,Smbd进程在SMB服务请求到达时对它们进行处理,并且为使用或共享的资源进行协调。

smbd 是提供数据传输服务,也就是我们说的Samba服务的主要功能
nmbd 是提供名称解析服务的,就是说开启此服务我们可以通过主机名来访问共享目录

  2、 启动服务

  Samba 有两种启动方式:Daemon形式和Inetd形式。

  (1)Daemon形式 建立启动脚本:rc.samba

  smbd -D -d1

  nmbd -D -d1

  -D 表示以Daemon形式执行;-d1 表示除错记录级别

  执行脚本文件rc.samba

  (2)Inetd形式

  设置文件:/etc/services

  netbios -ssn 139/ tcp

  netbios -ns 137/ udp

  设置文件:/etc/inetd.conf

  netbios -ssn stream tcp nowait root /usr/sbin/smbd smbd

  netbios -ns dgram udp wait root /usr/sbin/nmbd nmbd

  重启动Inetd daemon

  # kill -HUP 1

  3、 客户工具 smbclient

  Smbclient命令用来存取远程Samba服务器上的资源。其命令形式与ftp相似。

  命令语法是:#smbclient [password] [option]

  (1) 解释:servicename是要连接的资源名称,资源名称的形式如下:

  //server/service server 是远程服务器的NetBIOS名字,对于windows服务器而言,就是出现在网上邻居中的名字。

  Service是各server所提供的资源的名字。

  pssword 是存取该资源所需的口令

  option 各种命令选项,其中 -L 用于列出远程服务器提供的所有资源

  -I 指定远程服务器的IP地址。此时,servicesname 中的NetBIOS名部分将被忽略。

  (2)多种smbclient命令:

  执行smbclient命令成功后,进入smbclient环境,出现提示符: smb:\&gt;

  这里有许多命令和ftp命令相似,如cd 、lcd、get、megt、put、mput等。通过这些命令,我们可以访问远程主机的共享资源。

  4、 Samba系统装载与卸载

  (1) 装载其他主机的资源

  我们可以利用Samba提供的smbmount命令,装载其他主机的共享资源。

  Smbmount的命令语法:# smbmount

  其中 servicename 是资源名,mount-point是安装点。

  例如: # smbmount “\\server\tmp” -c ‘ mount /mnt’

  表示:把名字为“server”的计算机上的共享资源“tmp”的内容装载到本地的 /mnt

  目录下。

  (2) 卸载资源

  卸载一个已经装载的SMB文件系统,使用smbunmount命令,同时指定要卸载的装载点。 例如: # smbunmount / mnt

  三、Samba配置

  Samba组件的配置文件是 /etc/smb.conf ,该文件几乎包含了Samba系统程序运行时所需的所有配置信息。

  1、 配置选项

  配置文件中有比较重要的几个节:[gloabal]、[homes]、[printers],下面分别给与说明。

  (1)[gloabal]节 在全局参数中,参数的设置直接影响samba系统。

  NetBIOS name:设置主机名称

  Workgroup:用来指定主机所在网络上所属的NT域名或者工作组名称。格式是

  Workgroup= Nt Domain-Name or workgroup-name

  Server string:用来设置本机描述,缺省是 Samba Server

  Host Allow:它允许设置哪些领域的机器可以访问它的Samba服务器

  Load printers:允许自动加载打印机列表,而不需要单独设置每一台打印机。

  Interface:配置Samba使用多个网络界面。

  Domain controller: 仅当网络中有一台在安装时设置为主域控制器时使用此选项。

  Security: 设置安全参数,定义安全模式。Samba 的安全模式有四种

  Share、 user、 server 、domain

  encrypt passwords 、smb passwd file:用于适用加密口令。

  下面是一段参数配置例子:

  [global]

  smb passwd file = /etc/smbpasswd

  remote announce = 172.18.158.234 172.18.153.55 172.18.153.255

  dns proxy = no

  security = user

  encrypt passwords = yes

  server string = Ftp Server

  workgroup = turing

  socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192

  log file = /var/log/samba/log.%m

  load printers = yes

  guest account = dscan

  remote browse sync = 172.18.158.234 172.18.153.55 172.18.153.255

  printcap name = /etc/printcap

  max log size = 50

  hosts allow = 172.18.158. 172.18.153. 127.

  … …

  (2)[homes]节 所有使用者的home目录

  当任何一个客户访问Samba服务器时,在网络资源中都能出现自己的home目录共享。其配置如下:

  [homes]

  comment = Hnnw Directories

  browseable = no

  writable = yes

  (3)用户共享目录

  用来指定某一特定用户组或者用户拥有访问权限的目录配置,下列参数配置仅有hnnw组的用户有权访问目录/home/samba。

  [public]

  comment = Public Hnnw

  path = /home/samba

  public = yes

  writable = yes

  printable = no

  write list = @hnnw

  2、 用户映射

  全局参数“username map”用来控制用户映射,它允许管理员指定一个映射文件,该文件包含了在客户机和服务器之间进行用户映射的信息。

  如:username map= /etc/smbuser

  用户映射经常在windows 和linux 主机间进行。 两个系统拥有不同的用户账号,用户映射的目的是将不同的用户映射成为一个用户,便于共享文件。

  下面是一个映射文件的例子:

  # Map Windows admin to root

  root=admin administrator

  ;Map the member of developer to studio

  studio = @developer

  等号左边是单独的Linux账号,等号右边是要映射的账号列表。

  服务器逐行分析映射文件,如果提供的账号和某行有右侧列表中的账号匹配,就把它

  替换为等号左边的账号。

  3、 使用加密口令

 
 新版本的windows
95以及windows98、winnt(sp3以上版本),在网络传输中仅传递加密口令作为用户认证的信息。这类客户机和不支持加密口令并且以user
安全级运行的Samba服务器通讯时,会出现故障。为了正常的通讯,samba服务器使用加密口令。下面讨论如何在samba中使用加密口令。

  (1) 口令文件 /etc/smbpasswd

  为了使用加密口令,samba 需要一份口令文件(/etc/smbpasswd),并且该文件应该和Linux的口令文件(/etc/passwd)保持同步。下面是生成文件命令:

  # cat /etc/password | mksmbpasswd &gt;/etc/smbpasswd

  smbpasswd 是需要的口令文件,其权限是0600,所有者是root

  smbpasswd和passwd文件的记录对应,密码部分不同。密码有两部分组成,每部分

  是32个”X”,前部分用于和Lanman通讯,后部分和Windows NT通讯。

  Root用户可以使用smbpasswd命令为每个用户设定samba口令。

  (2) 修改配置文件 /etc/smb.conf

  要使Samba使用加密口令,需要在配置文件smb.conf中加入如下参数。

  Encrypt passwords=yes

  Smb passwd file= /etc/smbpasswd

  第一行通知samba使用加密口令,第二行给出口令文件的位置。

  (3) 重启动samba 服务。

  修改完配置文件后,需要重新启动samba服务,可用如下命令:

  # /usr/sbin/samba restart

  4、windows系统中的明码口令使用

 
 Samba系统中使用明码口令作为连接SMB的默认设置。当SMB服务器对协商协议做出响应时,响应信息包含了一位,以说明服务器是否支持询问或者响应

密。随着win95的网络重定向更新程序的发布,Microsoft修改了默认值,这样,windows客户就不会向不支持加密的服务器发送明码口令了。

  在这种情况下,有两种解决办法:

  (1)设置Samba服务器使用加密口令

  (2)让windows客户使用明码口令

  这里选用第2种解决办法,通过修改注册表来实现。下面对win95/win98、winnt用户分别给与说明。

  (1)win98/win95系统用户

  在注册表中加入下列注册字,并重新启动机器:

  [HKLM\System\CurrentCntrolSet\Services\VxD\VNETSUP]

  “EnablePlainTextPAssword”= dword:00000001

  (2)Winnt系统用户

  修改注册表,加入下列注册表项,并重新启动机器:

  [HKLM\System\CurrentCntrolSet\Services\Rdr\Parameters]

  “EnablePlainTextPAssword”= dword:00000001

  四、Samba应用

  1、 windows资源共享与使用

  (1)windows资源共享

  a. 使用TCP/IP协议作为网络默认通讯协议

  b. 修改网络配置,设置文件和打印机共享。

  c. 设置好计算机名和所属工作组

  d.共享系统资源

  (2)在windows系统中使用Linux共享资源

  a. 登录进入windows网络

  b. 通过网上邻居查看、使用共享资源。

  c. 命令行下工具使用共享资源

  使用命令行下的net.txt工具来查看、使用共享资源:

  net use 命令的语法: c:&gt;net use X:\\servername\sharename

  在这里,X:是共享的驱动器盘符,\\servername\sharename是到共享的UNC的网络路径。

  例如: c:\&gt;net use h:\\hey\myfile

  表示:将hey机器上的myfile共享资源映射为本地的h盘

  2、Linux资源共享与使用

  (1)将Linux 的资源共享

  通过编辑Samba配置文件,添加需要共享的Linux资源。同时可以设定访问此资源的用户群及其访问权限。下面是一段例子,将本机的 /public/data 目录共享,所有人都有读写权限。

  [data]

  comment = Public Data

  path = /public/data

  public = yes

  writable = yes

  printable = no

  (2)在Linux中使用共享资源

  可以使用smbclient命令,访问所有的Samba资源。具体使用方法见前述。

  五、Samba应用程序

  smbclient :访问所有共享资源

  smbstatus: 列出当前所有的samba连接状态

  smbpasswd:修改samba用户口令、增加samba用户。

  Nmblookup:用于查询主机的NetBIOS名,并将其映射为IP地址

  Testparam: 用于检查配置文件中的参数设置是否正确

  Linux 系统中的Samba配置

Powered by ScribeFire.

NFS service

In howto, linux, server on November 11, 2007 at 1:16 am
Linux服务配置文档—NFS – wds

NFS为network file system 的简称,最早由sun公司开发,一般NFS广泛应用在集群服务器上,他的最大特点是可以通过网络让不同的机器,不同的操作系统可以彼此的共享文件,所以它可以看作一个简单的文件服务器。NFS其实可以被视为一个RPC服务程序,在启动RPC程序前我们先要做好端口的映射工作这就是portmap,portmap的意思是当Client要连接服务器时必须知道服务器的一个空闲端口这时Client会向服务器的portmap请求一个端口然,然后Server告诉Client这端口后才可以建立连接,所以在启动NFS前要先启动portmap

[wds@localhost ~]# rpm –qa |grep nfs && rpm –qa | grep portmap #查找这两个是否安装

[wds@localhost ~]# vi /etc/exports # 这文件是NFS的主要配置文件

[wds@localhost ~]# /usr/sbin/exportfs #这个文件是nfs共享资源命令

[wds@localhost ~]# /usr/sbin/showmount #可以查看远程服务器的共享目录

[wds@localhost ~]# /var/lib/nfs/xtab #nfs 的日志文件

[wds@localhost ~]# vi /etc/exports

[你想要的共享的目录] + ip 地址(参数一,参数二) [主机名二](参数三,参数四)

参数列表

rw: 可以写入权限

ro: 只读权限

no_root_squash: 登陆NFS主机共享目录的如果是root用户那么那的权限也为root但是这样并不安全

root_squash: 登陆的用户如果为root它的权限将变成nobody

all_squash: 不论登陆的用户是什么用户都以匿名用户的权限

sync: 数据同步写入硬盘和内存中

async: 数据先暂时存放在内存中,而不写入硬盘

anounid: 这个可以自己设定uid,但是必须与/etc/passwd目录中用户uid一样

anongid: 同anonuid,但是变的是group id

服务器端配置

[wds@localhost ~]# service portmap start #首先打开portmap

[wds@localhost ~]# service nfs start # 在打开 nfs

[wds@localhost ~]#i iptables –F #清空防火墙命令

[wds@localhost ~]#

比如说我要共享/var/www/html 目录 但是只是让和我一个网段的机器访问192.168.0.0/24这个网段读或写,其他的就只能读,然后在发布一个私人目录/home/wds/只开放给192.168.0.8

这个IP

[wds@localhost ~]# vi /etc/exports

/var/www/html 192.168.0.0/24 (rw) *(ro)

/home/wds 192.168.0.8(rw)

现在想要*.chinaunix.com网段的机器登陆我的NFS,并且访问我的/home/wds/ 但是它们存储时我希望它们的uid和gid都变成40这个用户身份

[wds@localhost ~]# vi /etc/exports

/var/www/html 192.168.0.0/24 (rw) *(ro)

/home/wds 192.168.0.8(rw)

/home/wds *.chinaunix.com(rw,all)squash,anounid=40,anongid=40)

如果我们修改/etc/exports这个文件后,是否要从新启动nfs呢?答案是不不需要,只要使用exportfs来从新扫描一次/etc/exports文件,并且从新设置文件加载即可

语法为:

[wds@localhost ~]# exportfs [-aruv]

参数说明:

-a: 全部挂载(或者卸载)/etc/exports 文件的设置

-r: 从新挂载/etc/exports 里设置,此外,同步更新/etc/exports 及/var/lib/nfs/xtab的内容

-u: 卸载某一目录

-v: 在导出时,将共享目录显示在屏幕上

例如:

[wds@localhost ~]# exportfs –rv 全部从新导出一次

[wds@localhost ~]# exportfs –au 全部卸载掉

Showmount 的是显示是否有挂载

语法为:

[wds@localhost ~]# showmount [-ae] hostname

参数说明:

-a: 在屏幕上显示与当前的client连接后使用目录的状态

-e: 显示Hostname这台机器的/etc/exports中的共享信息

[wds@localhost log]# showmount -e localhost

Export list for localhost:

/var/www/html (everyone)

Rpcinfo [-p]hostname[or ip]

-p 显示端口与程序的信息

[wds@localhost log]# rpcinfo -p localhost

program vers proto port

100000 2 tcp 111 portmapper

100000 2 udp 111 portmapper

100024 1 udp 1024 status

100024 1 tcp 1024 status

100011 1 udp 837 rquotad

100011 2 udp 837 rquotad

100011 1 tcp 840 rquotad

100011 2 tcp 840 rquotad

100003 2 udp 2049 nfs

100003 3 udp 2049 nfs

100003 4 udp 2049 nfs

100003 2 tcp 2049 nfs

100003 3 tcp 2049 nfs

100003 4 tcp 2049 nfs

100021 1 udp 1026 nlockmgr

100021 3 udp 1026 nlockmgr

100021 4 udp 1026 nlockmgr

100021 1 tcp 1026 nlockmgr

100021 3 tcp 1026 nlockmgr

100021 4 tcp 1026 nlockmgr

100005 1 udp 858 mountd

100005 1 tcp 861 mountd

100005 2 udp 858 mountd

100005 2 tcp 861 mountd

100005 3 udp 858 mountd

100005 3 tcp 861 mountd

Client端的设置

Server端设置完毕,接下来就是让client端连接上server!连接server步骤如下:

1. 扫描可以使用的server目录:

2. 在client端建立装载点

3. 使用mount 命令远程挂载远程共享目录

4. 解决可能发生的问题(被防火墙过滤掉了)

Showmount是显示远程主机共享资源

[wds@localhost ~]# showmount -e 192.168.0.8

Export list for 192.168.0.8:

/var/www/html (everyone)

/home/wds *.chinaunix.com,192.168.0.6

[wds@localhost ~]# mount -t nfs 192.168.0.8:/var/www/html /mnt 把远程的/var/www/html 挂载到本地

[wds@localhost ~]# umount /mnt 卸载远程目录

如果你想要开机启动时自动加载NFS服务器导出目录,我们在NFS端/etc/fstab文件中加入以下一行

192.168.0.8:/var/www/html /mnt nfs rsize=8192,wsize=8192,timeo=14,intr

Powered by ScribeFire.

NFS service

In howto, linux, server on November 11, 2007 at 1:16 am
Linux服务配置文档—NFS – wds

NFS为network file system 的简称,最早由sun公司开发,一般NFS广泛应用在集群服务器上,他的最大特点是可以通过网络让不同的机器,不同的操作系统可以彼此的共享文件,所以它可以看作一个简单的文件服务器。NFS其实可以被视为一个RPC服务程序,在启动RPC程序前我们先要做好端口的映射工作这就是portmap,portmap的意思是当Client要连接服务器时必须知道服务器的一个空闲端口这时Client会向服务器的portmap请求一个端口然,然后Server告诉Client这端口后才可以建立连接,所以在启动NFS前要先启动portmap

[wds@localhost ~]# rpm –qa |grep nfs && rpm –qa | grep portmap #查找这两个是否安装

[wds@localhost ~]# vi /etc/exports # 这文件是NFS的主要配置文件

[wds@localhost ~]# /usr/sbin/exportfs #这个文件是nfs共享资源命令

[wds@localhost ~]# /usr/sbin/showmount #可以查看远程服务器的共享目录

[wds@localhost ~]# /var/lib/nfs/xtab #nfs 的日志文件

[wds@localhost ~]# vi /etc/exports

[你想要的共享的目录] + ip 地址(参数一,参数二) [主机名二](参数三,参数四)

参数列表

rw: 可以写入权限

ro: 只读权限

no_root_squash: 登陆NFS主机共享目录的如果是root用户那么那的权限也为root但是这样并不安全

root_squash: 登陆的用户如果为root它的权限将变成nobody

all_squash: 不论登陆的用户是什么用户都以匿名用户的权限

sync: 数据同步写入硬盘和内存中

async: 数据先暂时存放在内存中,而不写入硬盘

anounid: 这个可以自己设定uid,但是必须与/etc/passwd目录中用户uid一样

anongid: 同anonuid,但是变的是group id

服务器端配置

[wds@localhost ~]# service portmap start #首先打开portmap

[wds@localhost ~]# service nfs start # 在打开 nfs

[wds@localhost ~]#i iptables –F #清空防火墙命令

[wds@localhost ~]#

比如说我要共享/var/www/html 目录 但是只是让和我一个网段的机器访问192.168.0.0/24这个网段读或写,其他的就只能读,然后在发布一个私人目录/home/wds/只开放给192.168.0.8

这个IP

[wds@localhost ~]# vi /etc/exports

/var/www/html 192.168.0.0/24 (rw) *(ro)

/home/wds 192.168.0.8(rw)

现在想要*.chinaunix.com网段的机器登陆我的NFS,并且访问我的/home/wds/ 但是它们存储时我希望它们的uid和gid都变成40这个用户身份

[wds@localhost ~]# vi /etc/exports

/var/www/html 192.168.0.0/24 (rw) *(ro)

/home/wds 192.168.0.8(rw)

/home/wds *.chinaunix.com(rw,all)squash,anounid=40,anongid=40)

如果我们修改/etc/exports这个文件后,是否要从新启动nfs呢?答案是不不需要,只要使用exportfs来从新扫描一次/etc/exports文件,并且从新设置文件加载即可

语法为:

[wds@localhost ~]# exportfs [-aruv]

参数说明:

-a: 全部挂载(或者卸载)/etc/exports 文件的设置

-r: 从新挂载/etc/exports 里设置,此外,同步更新/etc/exports 及/var/lib/nfs/xtab的内容

-u: 卸载某一目录

-v: 在导出时,将共享目录显示在屏幕上

例如:

[wds@localhost ~]# exportfs –rv 全部从新导出一次

[wds@localhost ~]# exportfs –au 全部卸载掉

Showmount 的是显示是否有挂载

语法为:

[wds@localhost ~]# showmount [-ae] hostname

参数说明:

-a: 在屏幕上显示与当前的client连接后使用目录的状态

-e: 显示Hostname这台机器的/etc/exports中的共享信息

[wds@localhost log]# showmount -e localhost

Export list for localhost:

/var/www/html (everyone)

Rpcinfo [-p]hostname[or ip]

-p 显示端口与程序的信息

[wds@localhost log]# rpcinfo -p localhost

program vers proto port

100000 2 tcp 111 portmapper

100000 2 udp 111 portmapper

100024 1 udp 1024 status

100024 1 tcp 1024 status

100011 1 udp 837 rquotad

100011 2 udp 837 rquotad

100011 1 tcp 840 rquotad

100011 2 tcp 840 rquotad

100003 2 udp 2049 nfs

100003 3 udp 2049 nfs

100003 4 udp 2049 nfs

100003 2 tcp 2049 nfs

100003 3 tcp 2049 nfs

100003 4 tcp 2049 nfs

100021 1 udp 1026 nlockmgr

100021 3 udp 1026 nlockmgr

100021 4 udp 1026 nlockmgr

100021 1 tcp 1026 nlockmgr

100021 3 tcp 1026 nlockmgr

100021 4 tcp 1026 nlockmgr

100005 1 udp 858 mountd

100005 1 tcp 861 mountd

100005 2 udp 858 mountd

100005 2 tcp 861 mountd

100005 3 udp 858 mountd

100005 3 tcp 861 mountd

Client端的设置

Server端设置完毕,接下来就是让client端连接上server!连接server步骤如下:

1. 扫描可以使用的server目录:

2. 在client端建立装载点

3. 使用mount 命令远程挂载远程共享目录

4. 解决可能发生的问题(被防火墙过滤掉了)

Showmount是显示远程主机共享资源

[wds@localhost ~]# showmount -e 192.168.0.8

Export list for 192.168.0.8:

/var/www/html (everyone)

/home/wds *.chinaunix.com,192.168.0.6

[wds@localhost ~]# mount -t nfs 192.168.0.8:/var/www/html /mnt 把远程的/var/www/html 挂载到本地

[wds@localhost ~]# umount /mnt 卸载远程目录

如果你想要开机启动时自动加载NFS服务器导出目录,我们在NFS端/etc/fstab文件中加入以下一行

192.168.0.8:/var/www/html /mnt nfs rsize=8192,wsize=8192,timeo=14,intr

Powered by ScribeFire.

vista virtual directory

In Windows, howto on November 7, 2007 at 11:36 am

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

From here you can modify where the favorite directories are located.

Blogged with Flock

firefox ultimate optimizer

In howto, software on November 6, 2007 at 2:00 pm

it really does an amazing job. save the memory resource almost 10 times. But not sure about the security. Waiting for other’s comments.

firefoxultimateoptimizer.zip

firefox ultimate optimizer

In howto, software on November 6, 2007 at 2:00 pm

it really does an amazing job. save the memory resource almost 10 times. But not sure about the security. Waiting for other’s comments.

firefoxultimateoptimizer.zip

Four ways to extract the current directory name

In howto, linux on November 6, 2007 at 1:23 pm

When you’re programming a shell script, you often only need the current directory name, not the whole path that the pwd command returns. Here are four ways you can extract only the current directory.

Using basename

Using the basename command is the easiest and simplest way to extract the current directory:

basename /usr/local/binbin

However, it isn’t useful in a shell script with changing directory variables. You can combine it with pwd inside backticks to make it more dynamic:

cd /usr/local/binbasename `pwd`bin

Using parameter substitution with echo

The bash scripting language is full of nice tricks, including parameter substitution, which allows you to manipulate or expand variables. You can use parameter substitution with the ${var##pattern} syntax, which removes from $var the longest part of $Pattern that matches the front end of $var. Take a look at an example:

cd /var/log/squidecho ${PWD##*/}squid

PWD is the environment variable that holds the current path, and ## is the instruction that tells the script to remove everything it finds up to */. In other words, it removes everything until the last /, leaving only the last string, which here is the current directory, squid. You can learn more about parameter substitution and other ways to manipulate variables in the Advanced Bash-Scripting Guide.

Using awk and rev

A more elaborate solution uses a combination of awk (a pattern-scanning utility) and rev (a utility that reverses lines from a file or from stdin):

cd /usr/share/cups/datapwd | rev | awk –F \/ '{print $1}' | revdata

It’s a lot easier to understand this kind of script step by step:

pwd/usr/share/cups/datapwd | rev atad/supc/erahs/rsu/pwd | rev | awk –F \/ '{print $1}'atadpwd | rev | awk –F \/ '{print $1}' | revdata

The -F option indicates that you should separate by fields, where the field delimiter is /, and that you should print field 1.

Using sed

Finally, you can parse pwd output in the stream editor sed using an elaborate regular expression. This approach may be educational, but it’s not practical:

cd /home/smith/musicpwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'music

For a better understanding of how this works, remove the escape character (\), which is required for special characters such as “(“:

sed 's,^(.*/)?([^/]*),\2,'

s substitutes one string for another. It looks for two patterns, which are indicated between the first comma and the second comma. The first pattern (^(.*/)?) searches from the beginning of the line (^) until the last occurrence that it finds of / (in the example, it matches /home/smith/). The second pattern (([^/]*)) searches everything from the last pattern except the / character , which is indicated by [^/]*, where ^ at the beginning of the square brackets means not. This results in both /home/smith/ and music. The second part of this regular expression is the substitution, indicated by \2. In sed, this is called a back reference. As its name implies, it goes back and recalls a previously used reference. There may be nine of these, named \1, \2, \3, and so on. In the example, \2 refers to the second pattern found, which is music — the result expected.

As you can see, Linux gives you many ways to find a directory name. Having many choices for the same chore is one of its strengths.

Sergio Gonzalez Duran is a Linux administrator, systems developer, and network security counselor who also teaches Linux courses and publishes the Spanish-oriented Linux and open source Web site linuxtotal.com.mx.

Blogged with Flock

linux 字符串操作 tr (sed补全)

In howto, linux on November 5, 2007 at 4:21 pm

tr 用来从标准输入中通过替换或删除操作进行字符转换.tr主要用于删除文件中控制字符进行字符转换.使用tr时要转换两个字符串:字符串1用于查询,字符串2用于处理各种转换.tr刚执行时,字符串1中的字符被映射到字符串2中的字符,然后转换操作开始.

一般格式:tr -c -d -s ["string1_to_translate_from"] ["string2_to_triampsulata_te_to"]

-c:用字符串1中字符集的补集替换此字符,要求字符集为ASCII
-d:删除字符串1中所有输入字符
-s:删除所有重复出现字符序列,只保留一个,即将重复出现字符串压缩为一个字符串

12.1 字符范围:

[a-z]:a-z内的字符组成的字符串
[A-Z]:A-Z内的字符组成的字符串
[0-9]:数字串
/octal:一个三位的八进制数,对应有效的ASCII字符
[O*n]:表示字符O重复出现指定次数n,例[O*2]表示匹配[OO]字符串

12.2 保存输出

要保存输出结果,需将之重定向到一个文件.例:重定向输出到文件results.txt,输入文件是cops.txt:

$tr -s “[a-z]“<cops.txt>results.txt

12.3 去除重复出现的字符

$more cops.txt

And the cowwwwws went homeeeeeeee
Or did theyyyy
如果要去除重复字符或将其压缩在一起,可以使用-s选项,因为都是字母,故使用[a-z]:
$tr -s “[a-z]“<cops.txt
And the cows went home
Or did they

12.4 删除空行

可使用-s来作这项工作.换行的八进制表示位12,例:
$more plane.txt
and 0500 399999 2773888

or 093999 3766666

data 39

$tr -s “[12]“<plane.txt

and 0500 399999 2773888
or 093999 3766666
data 39

12.5 大小写转换

除了删除控制字符,转换大小写是tr最常用的功能.为此需指定即将转换的小写字符[a-z]和转换结果[A-Z]

例1:tr从一个包含大小写字母的字符串中接受输入:

$echo “May Day,May Day,Going Down…”|tr “[a-z]” “[A-Z]“

MAY DAY,MAY DAY,GOING DOWN…

同样也可以使用字符类[:lower:]和[:upper:]
$echo “May Day,May Day,Going Down…”|tr “[:lower:]” “[:upper:]“
MAY DAY,MAY DAY,GOING DOWN…

$echo “MAY DAY,MAY DAY,GOING DOWN…”|tr “[A-Z]” “[a-z]“
may day,may day,going down…

或者也可以使用字符类[:upper:]和[:lower:]
$echo “MAY DAY,MAY DAY,GONING DOWN…”|tr “[:upper:]” “[:lower:]“
may day,may day,going down…

12.7 删除指定字符

偶尔会从下载文件中删除之包含字母或数字的列.需要结合使用-c和-s选项来完成此功能.
下面的文件包含一个星期的日程表.任务是从其中删 除所有数字,之保留日期.日期有大写,也有小写格式.因此需指定两个字符范围[a-z]和[A-Z],命令tr -cs “[a-z][A-Z]“”[12*]“将文件每行所有不包含在[a-z]或[A-Z]的字符串放在字符串1中并转换为一新行.-s选项表明压缩所有 新行,-c表明保留所有字母不动:

$more diary.txt

monday 10:50
Tuesday 15:30
wednesday 15:30
thurday 10:30
Friday 09:20

$tr -cs “[a-z][A-Z]” “[12*]“<diary.txt

monday
Tuesday
wednesday
thurday
Friday

12.8 转换控制字符

tr的第一个功能就是转换控制字符,特别是从dos向UNIX下载文件时,忘记设置FTP关于回车换行转换的选项时更是如此.

下面是估计没有设置转换开关的一个文本文件,使用cat -v 显示控制字符.

$cat stat.tr
Boxes paper^^^^^^12^M
Clips metal^^^^^^50^M
Penciles-meduim^^^^^^10^M
^Z

猜想,’^^^^^^’是tab键,每一行以ctrl-M结尾,文件结尾ctrl-z,以下是改动方法:

使用-s选项,查看ASCII表,^的八进制代码是136,^M是015,tab键是011,^Z是032,下面按步骤完成最终功能.

用tab键替换^^^^^^,命令”\136″”[11*]“,并输出到stat.tmp:

$tr -s “[\136]” “[11*]” < stat.tr > stat.tmp
Boxes paper 12^M
Clips metal 50^M
Pencils-medium 10^M
^Z

用新行替换每行末尾的^M,并用\n去除^Z,输入文件来自stat.tmp:

$tr -s “[1532]” “\n” < stat.tmp

12.9 快速转换

如果要删除文件中^M,并代之以换行:
$tr -s “[15]” “\n” < input_file
或者:
$tr -s “[\r]” “[\n]” < input_file
或者:
$tr -s “\r” “\n” < input_file

要删除所有的tab键,代之以空格:
$tr -s “[11]” “[40*]” < intput_file

例:替换/etc/passwd文件中所有冒号,代之以tab键,可以增加可读性:

$tr -s “[:]” “[11]” < /etc/passwd

或:

$tr “[:]” “[\t]” < /etc/passwd

12.10 匹配多于一个字符

可以使用[character*n]格式匹配多于一个字符.例:
原文件:
$cat hdisk.txt

1293 hdisk3
4512 hdisk12
0000 hdisk5
4993 hdisk12
2994 hdisk7

替换第三行的0为星号:
$tr “[0*4]” “*” < hdisk.txt
1293 hdisk3
4512 hdisk12
**** hdisk5
4993 hdisk12
2994 hdisk7

或替换成百分号:
$tr “[0*4]” “%”<hdisk.txt
1293 hdisk3
4512 hdisk12
%%%% hdisk5
4993 hdisk12
2994 hdisk7

Blogged with Flock

java Programming in Linux with gcj (basic)

In howto, java, linux on November 4, 2007 at 5:33 pm

The simple Java source code in Listing 1 can be compiled into Java bytecode with gcj -C HelloWorld.java and interpreted using gij HelloWorld. The same source code can be compiled into a native executable using gcj --main=HelloWorld -o HelloWorld HelloWorld.java and executed using ./HelloWorld. This article avoids including import and other trivial statements in Java code listings; see Resources for the full source files.

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

## make executable
$ gcj -C HelloWorld.java
$ gij HelloWorld # to test if it works
$ gcj --main=HelloWorld -o HelloWorld HelloWorld.java
$ ./HelloWorld # to run it and test

## make executable jar (same way with in Windows)$ gcj -c HelloWorld.class          # compile Hello.class to Hello.o$ jar cvf hi.jar HelloWorld.class  # create a jar## You got to include "manefest" file containing the class name of the "main()" method as:Main-class: your.package.Class_NAME.without_dot_class# modify the "MANIFEST.MF", adding at the end: Main-class: HelloWorld # Note: there is a space after ':'.

## make executable with jar$ gcj -c HelloWorld.class          # compile Hello.class to Hello.o$ jar cvf hi.jar HelloWorld.class  # create a jar$ gcj -c hi.jar                    # compile hi.jar to hi.o$ gcj --main=HelloWorld -o hi hi.o # link hi.o to hi$ ./hi                             # run hiHello, World!


java Programming in Linux with gcj (basic)

In howto, java, linux on November 4, 2007 at 5:33 pm

The simple Java source code in Listing 1 can be compiled into Java bytecode with gcj -C HelloWorld.java and interpreted using gij HelloWorld. The same source code can be compiled into a native executable using gcj --main=HelloWorld -o HelloWorld HelloWorld.java and executed using ./HelloWorld. This article avoids including import and other trivial statements in Java code listings; see Resources for the full source files.

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

## make executable
$ gcj -C HelloWorld.java
$ gij HelloWorld # to test if it works
$ gcj --main=HelloWorld -o HelloWorld HelloWorld.java
$ ./HelloWorld # to run it and test

## make executable jar (same way with in Windows)$ gcj -c HelloWorld.class          # compile Hello.class to Hello.o$ jar cvf hi.jar HelloWorld.class  # create a jar## You got to include "manefest" file containing the class name of the "main()" method as:Main-class: your.package.Class_NAME.without_dot_class# modify the "MANIFEST.MF", adding at the end: Main-class: HelloWorld # Note: 1) there is a space after ':'. 2) there is NO empty line before the 'Main-class' line.

## make executable with jar$ gcj -c HelloWorld.class          # compile Hello.class to Hello.o$ jar cvf hi.jar HelloWorld.class  # create a jar$ gcj -c hi.jar                    # compile hi.jar to hi.o$ gcj --main=HelloWorld -o hi hi.o # link hi.o to hi; gcj accept all reasonable input files, such as .java files, .class files and .o files, even .jar files. Super!!!$ ./hi                             # run hiHello, World!


command-line activate wireless

In howto, linux on November 4, 2007 at 3:07 am

1.
ndiswrapper -i XXXXX
ndiswrapper -ma
modprobe ndiswrapper
2.
iwconfig
3.
iwlist wlan0 scan
4.
sudo iwconfig wlan0 essid XXXXXXXXXX
sudo iwconfig wlan0 key XXXXXXXXXXX(for normal wep:64bit,open mode security, otherwise s:XXXXX for ansi code)
dhclient [wlan0] (to activate the wireless card)

5.
ifconfig (to check whether get the IP properly or not)
ping somewhere to test
P.S. Note: the networkmanager looks do not change at all. Because it did nothing, and not reflect the status of the network.

Debian repository – sid

In howto, linux on November 2, 2007 at 9:03 pm

The code names of Debian releases are names of characters from the film Toy Story. The unstable, development distribution is nicknamed sid, after the emotionally unstable next-door neighbour boy who destroyed toys on a regular basis.

Where do these codenames come from?

So far they have been characters taken from the movie “Toy Story” by Pixar.

  • buzz (Buzz Lightyear) was the spaceman,

  • rex was the tyrannosaurus,

  • bo (Bo Peep) was the girl who took care of the sheep,

  • hamm was the piggy bank,

  • slink (Slinky Dog (R)) was the toy dog,

  • potato was, of course, Mr. Potato (R),

  • woody was the cowboy,

  • sarge was the sergeant of the Green Plastic Army Men,

  • etch was the toy blackboard (Etch-a-Sketch (R)),

  • lenny was the binoculars.

  • sid was the boy next door who destroyed toys.

Sid repository is dangerous, but it’s really powerful for developers. Almost you can find any lib packages here.
####################################
deb http://ftp.de.debian.org/debian sid main ##
####################################
the gpg key:
when you run apt-get update, you will be told error about gpg key:A70DAF536070D3A1
run:
####################################

sudo gpg --keyserver wwwkeys.eu.pgp.net --recv-keys 07DC563D1F41B907sudo apt-key add ~/.gnupg/pubring.gpg###################################################

From here you can find a lot of libs which are really difficult to get from those stable repositories.

Recovery when you remove some packages by mistake

In howto, linux on November 1, 2007 at 9:04 pm

Sometime when you install some new package, it will remove all its conflict packages, before this, you will be notified. But most of the people like me don’t want to read all of the long-winded words every time. So sooner or later you will make such mistake.

Yes, I did. when I install some package about pulseaudio, which comes with Fedora 8 next week, one of the plugins conflicts with the current system sound server, so it removed the esound server and all relative packages (including all the Gnome and Kde package). I can not log in the X windows environment.

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

Here are the solution:
1.
a. find the synaptic history log files, which are stored in /root/.synaptic/log/, sorted by date. You can not use ‘cd’ to browse the folder, so you must use ‘ls’ and ‘cp’ to get the file.
b. remove some contents of the file, just leave the removed packages.
c-1. using vi, input such command when you click’:', ‘1,$j’. Here j can make all the lines in the file into 1 line.
c-2. (another method) tr -c “[a-z][A-Z]” ” ” < thefile
d. At the beginning of the file, add ’sudo apt-get install -y’. Here ‘y’ force every installation continue without prompt.
e. sh+the file. everything start. when it finished. your system recovered.

2.
at step 1.c. using ’sed’ to add ’sudo apt-get install -y’ before each line. it works, but two slow and a lot of repeat work by computer.

quick luaunch

In howto, linux on October 30, 2007 at 7:52 pm

Quicksilver for Mac OSX

Katapult for Linux KDE (alt+space)

Gnome-launch-box for Linux Gnome

  1. Start gconf-editor from a terminal
  2. Locate /apps/metacity/keybindings_commands in the treeview
  3. Set a command, for example command_1 to gnome-launch-box
  4. Go to /apps/metacity/global_keybindings
  5. Setup the keybinding you want for running GNOME Launch Box as run_command_1

nice (Unix)

In howto, linux on October 26, 2007 at 2:07 pm

From Wikipedia, the free encyclopedia

Jump to: navigation, search

nice (IPA pronunciation: /naɪs/) is a command found on UNIX and other POSIX-like operating systems such as Linux. nice directly maps to a kernel call of the same name. For a given process, it changes the priority in the kernel’s scheduler. A nice value of −20 is the highest priority and 19 is the lowest priority. The default nice value for processes is inherited by its parent process, usually 0.

Nice becomes useful when several processes are demanding more resources than the CPU can provide. In this state, a higher priority process will get a larger chunk of the CPU time than a lower priority process. If the CPU can deliver more resources than the processes are requesting, then even the lowest priority process can get up to 99% of the CPU. Only the superuser (root) may set the nice value to a smaller (higher priority) value.

There is also a renice command, which is used to change the priority of a process that’s already running.

The exact mathematical effect of setting a particular niceness value for a process depends on the details of how the scheduler is designed on that implementation of UNIX. A particular operating system’s scheduler will also have various heuristics built into it, e.g., to favor processes that are mostly I/O-bound over processes that are CPU-bound. As a simple example, when two otherwise identical CPU-bound processes are running simultaneously on a single-CPU Linux system, each one’s share of the CPU time will be proportional to 20-p, where p is the process’s priority. Thus a process run with nice +15 will receive 1/4 of the CPU time allocated to a normal-priority process: (20-15)/(20-0)=1/4. On the BSD 4.x scheduler, on the other hand, the ratio in the same example is more like ten to one.

Contents

[hide]

//

[edit] Language bindings

[edit] C

nicegetpriority(2)

[edit] Perl

 use POSIX ();POSIX::nice(7); # like the renice shell command; increase niceness level by 7my $prio = getpriority(0,0); # like the C function

[edit] See also

[edit] External links

nice (Unix)

In howto, linux on October 26, 2007 at 2:07 pm

From Wikipedia, the free encyclopedia

Jump to: navigation, search

nice (IPA pronunciation: /naɪs/) is a command found on UNIX and other POSIX-like operating systems such as Linux. nice directly maps to a kernel call of the same name. For a given process, it changes the priority in the kernel’s scheduler. A nice value of −20 is the highest priority and 19 is the lowest priority. The default nice value for processes is inherited by its parent process, usually 0.

Nice becomes useful when several processes are demanding more resources than the CPU can provide. In this state, a higher priority process will get a larger chunk of the CPU time than a lower priority process. If the CPU can deliver more resources than the processes are requesting, then even the lowest priority process can get up to 99% of the CPU. Only the superuser (root) may set the nice value to a smaller (higher priority) value.

There is also a renice command, which is used to change the priority of a process that’s already running.

The exact mathematical effect of setting a particular niceness value for a process depends on the details of how the scheduler is designed on that implementation of UNIX. A particular operating system’s scheduler will also have various heuristics built into it, e.g., to favor processes that are mostly I/O-bound over processes that are CPU-bound. As a simple example, when two otherwise identical CPU-bound processes are running simultaneously on a single-CPU Linux system, each one’s share of the CPU time will be proportional to 20-p, where p is the process’s priority. Thus a process run with nice +15 will receive 1/4 of the CPU time allocated to a normal-priority process: (20-15)/(20-0)=1/4. On the BSD 4.x scheduler, on the other hand, the ratio in the same example is more like ten to one.

Contents

[hide]

//

[edit] Language bindings

[edit] C

nicegetpriority(2)

[edit] Perl

 use POSIX ();POSIX::nice(7); # like the renice shell command; increase niceness level by 7my $prio = getpriority(0,0); # like the C function

[edit] See also

[edit] External links

Linux Memory Usage

In howto, linux on October 26, 2007 at 1:58 pm

A lot of people made good points in the comments section of my last posting (Understanding memory usage on Linux). Here are some of the general ideas that were mentioned:

(1) Several comments noted that non-x86 hardware has a different approach to shared memory between processes. This is true; some architectures do not handle shared memory in the same way as x86. To be honest, I don’t know which platforms those are, so I’m not going to even try to list them. Thus, my previous post should be taken with a big grain of salt if you’re working on a non-x86 platform.

(2) Many people also noted that this shared library feature of Linux isn’t some fancy new thing, which is completely true. Microsoft Windows platforms undoubtedly have the same basic sharing feature, just like any full-featured modern operating system. My post only addressed Linux because, to be honest, I’m a Linux-centric kind of person.

(3) Yes, I did commit the sin of using “it’s” instead of “its”. To all of the English majors in the audience, I offer my most sincere apology.

(4) A few comments mentioned the memory size of Firefox. I must admit that I began this article with Firefox instead of KEdit as the primary example, but I was forced to switch to KEdit when I saw how big Firefox’s private/writeable size was; KEdit illustrated my point much better. :)

(5) If the word “marginal” that I used confused anyone, then feel free to just mentally replace it with the word “incremental”.

Thanks to everyone that commented on the posting; part of my reason for writing it was to see what other people thought, as other people usually know more than I do about any given subject.


Saturday, February 04, 2006


Understanding memory usage on Linux

This entry is for those people who have ever wondered, “Why the hell is a simple KDE text editor taking up 25 megabytes of memory?” Many people are led to believe that many Linux applications, especially KDE or Gnome programs, are “bloated” based solely upon what tools like ps report. While this may or may not be true, depending on the program, it is not generally true — many programs are much more memory efficient than they seem.

What ps reports
The ps tool can output various pieces of information about a process, such as its process id, current running state, and resource utilization. Two of the possible outputs are VSZ and RSS, which stand for “virtual set size” and “resident set size”, which are commonly used by geeks around the world to see how much memory pr