Saturday, 29 November 2008

HOWTO: stop imsetting-daemon im-info-daemon

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 Method
settings and applies the changes immediately. so it will
takes an effect without restarting applications and the
desktop.

Background
==============
Input Method is used to input some dozens of characters that
can't be represented with ASCII characters, with some
framework such as XIM and SCIM via GTK+/Qt
immodule. particularly which to handle languages that is a
bit complex to do the same thing with the keyboard layout
such as XKB. In the past, those frameworks has been applied
through the environment variables, such as XMODIFIERS and
GTK_IM_MODULE. and can't be influenced immediately and can't
be without restarting the desktop because of its nature -
it's being inherited from the parent process unless it's
being brought up with the obvious thing from the terminal
say. Also, there are no such framework to bring up the
necessary process at the run time - of course anyone could
runs it manually though, it's totally out of focus on this
project.

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 Input
Methods that hopes so has to have the information file to
let IMSettings know. those files is usually put under a
directory where you can change the default value with
--with-xinputdir. the filename has to contain .conf or
something that you can also change the default value with
--with-xinput-suffix to avoid listing every Input Methods
that might not work for some languages. Input Methods
doesn't support multiple languages such as XIM doesn't have
to have .conf suffix or so. xim.conf can deals with such
configuration files properly for appropriate languages
according to current locale.

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

The following parameters can be described as the shell
environment 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.

Friday, 28 November 2008

跳得太高了

BUGS: Samba shares

there are two type of share,
1) traditional way, GUI: system-config-samba.
2) nautilus-share, right click the folder you want to share, which is default in ubuntu. this need a line 'usershare owner only = False' to put into the global section in smb.conf, sometimes, 'usershare allow guests = yes' is also needed. This is working on the command of 'net usershare'.

1) system-config-samba will modify smb.conf; while 2) nautilus-share, using 'net usershare' will not change smb.conf. So these are different ways for sharing.

In Ubuntu, no matter what method you use, both works fine. But fedora, so far, only 1) works, while 2) always saying "'net usershare' returned error 255: net usershare: usershares are currently disabled".

Thursday, 27 November 2008

HOWTO: jython(java) calling c program in console

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. :)

happy thanksgiving

HOWTO: codecs from myplayer_win32

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

Wednesday, 26 November 2008

efficiency of python calling c exetuable

python 可以用popen调用一个c语言的可执行程序。但是效率如何呢?

1)一个c程序: 调用一个循环求和从1到1000的function 10000次。
之所以要调用循环求和从1到1000,是因为这个function要声称另外的一个可执行文件供python调用,所以外部框架c和python都差不多,就是要往复调用这个function,以得出python与c的沟通效率。
#######################
/*
* File: newmain.c
* Author: cross
*
* Created on 26 November 2008, 16:08
*/

#include <stdio.h>
#include <stdlib.h>

struct timeb {
time_t time;
unsigned short millitm;
short timezone;
short dstflag;
};
//ftime returns a struct with above structure.

int internal_loop(){
int ii=0,ss=0;
while (ii<1000)
{
ss+=ii;
ii++;
}
printf("%i\n",ss);
return ss;
}

int main(int argc, char** argv) {

struct timeb t1,t2;
double i=0,s=0;

ftime(&t1);

int repeat = 10000;
while(i<repeat){
s+=internal_loop();
i++;
}

ftime(&t2);
printf("%.1f\n",s);

printf("time = %ld.%d\n",t1.time,t1.millitm);
printf("time = %ld.%d\n",t2.time,t2.millitm);


return (EXIT_SUCCESS);
}


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

2)以上的internal_loop function被单独生成一个c的可执行文件b.o,供python调用。以下是python代码。
##################

import datetime
import os

t1= datetime.datetime.now()

j=0
k=1000
for i in range(1,k):
printed=os.popen('/home/cross/NetBeansProjects/Application_2/b.o')
printed.readlines()
printed.close()

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 'Repeated sum of 1-1000 ',k,' times : '
print tstr

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

3) 只用python单独完成和1)一样的过程,python代码如下:
########################
import datetime

t1= datetime.datetime.now()

k=10000
for i in range(1,k):
    j=0
    for ii in range(1,1000):
        j=j+ii
    print j

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 'Repeated sum of 1-1000 ',k,' times : '
print tstr

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


总结
如果成功运行以上两个程序,同样是运行10000次,1)耗时274毫秒;2)20秒。
可见python与其他程序通过popen这种字符沟通的效率是比较低的。以上,1)是同一个程序调用一个子函数,速度当然是最理想的。而2)是通过console的字符交换得以沟通,这种效率当然低,甚至这还远不如主程序和子程序的沟通效率。

通过1)和3)的比较,可以很容易看出来python的语法简单,但是python比c慢也是事实,3)用时3.8秒。

HOWTO: Calling c (or other programs) from python

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.

Friday, 21 November 2008

C语言-指针; 2008温习

指针变量在定义中允许带初始化项。如:
int i, *ip=&i;
注意, 这里是用&i 对ip初始化, 而不是对*ip初始化。和一般变量一样,对于外部或静态指针变量在定义中若不带初始化项, 指针变量被初始化为NULL, 它的值为0。 Turbo C中规定, 当指针值为零时, 指针不指向任何有效数据, 有时也称指针为空指针。
int i=200, x;
int *ip;
我们定义了两个整型变量i,x,还定义了一个指向整型数的指针变量ip。i,x中可存放整数,而ip中只能存放整型变量的地址。我们可以把i的地址赋给ip:
ip=&i;
此时指针变量ip指向整型变量i.

字符指针
char *cp;
于是可用:
cp=a string;
使cp指向字符串常量中的第0号字符a, 如图所示。
CP----- | a | | s | t | r | i | n | g | \0|

以后我们可通过cp来访问这一存贮区域, 如*cp或cp[0]就是字符a,而cp[i]或*(cp+i)就相当于字符串的第i号字符,但企图通过指针来修改字符串常量的行为是没有意义的。
而char *Names[]表示指向字符的指针数组。


Turbo C中,数组名是数组的第0号元素的地址,因此下面两个语句是等价的
p=&a[0];
p=a;
根据地址运算规则,a+1为a[1]的地址,a+i就为a[i]的地址。
下面我们用指针给出数组元素的地址和内容的几种表示形式:
(1). p+i和a+i均表示a[i]的地址, 或者讲,它们均指向数组第i号元素, 即指向a[i]。
(2). *(p+i)和*(a+i)都表示p+i和a+i所指对象的内容,即为a[i]。
(3). 指向数组元素的指针, 也可以表示成数组的形式,也就是说,它允许指针变量带下标, 如p[i]与*(p+i)等价。
对于二维数组:
我们把a[0],a[1],a[2]看成是一维数组名,可以认为它们分别代表它们所对应的数组的首地址,也就是讲,a[0]代表第 0 行中第 0 列元素的地址,即&a[0][0], a[1]是第1行中第0列元素的地址,即&a[1][0],根据地址运算规则,a[0]+1即代表第0 行第1列元素的地址,即&a[0][1],一般而言,a[i]+j即代表第i行第j列元素的地址, 即&a[i][j]。
另外,在二维数组中,我们还可用指针的形式来表示各元素的地址。如前所述,a[0]与*(a+0)等价,a[1]与*(a+1)等价,因此a[i]+j就与*(a+i)+j等价,它表示数组元素a[i][j]的地址。
因此,二维数组元素a[i][j]可表示成*(a[i]+j)或*(*(a+i)+j),它们都与a[i][j]等价,或者还可写成(*(a+i))[j]。

在Turbo C中, 可定义如下的指针变量:
int (*p)[3];
指针p为指向一个由3个元素所组成的整型数组指针。在定义中,圆括号是不能少的, 否则它是指针数组, 这将在后面介绍。

指针数组
int *a[10];
定义了一个指针数组,数组中的每个元素都是指向整型量的指针,该数组由10个元素组成,即 a[0],a[1],a[2], ..., a[9],它们均为指针变量。a为该指针数组名,和数组一样,a是常量,不能对它进行增量运算。a为指针数组元素a[0]的地址,a+i为a[i]的地址,*a就是a[0],*(a+i)就是a[i]。


指针函数
当一个函数声明其返回值为一个指针时,实际上就是返回一个地址给调用函数,以用于需要指针或地址的表达式中。
格式:
类型说明符 * 函数名(参数)
当然了,由于返回的是一个地址,所以类型说明符一般都是int。
例如:int *GetDate();

函数指针
指向函数的指针包含了函数的地址,可以通过它来调用函数。声明格式如下:
类型说明符 (*函数名)(参数)
其实这里不能称为函数名,应该叫做指针的变量名。这个特殊的指针指向一个返回整型值的函数。指针的声明笔削和它指向函数的声明保持一致。
指针名和指针运算符外面的括号改变了默认的运算符优先级。如果没有圆括号,就变成了一个返回整型指针的函数的原型声明。
例如:
void (*fptr)();
把函数的地址赋值给函数指针,可以采用下面两种形式:
fptr=&Function;
fptr=Function;
取地址运算符&不是必需的,因为单单一个函数标识符就标号表示了它的地址,如果是函数调用,还必须包含一个圆括号括起来的参数表。
可以采用如下两种方式来通过指针调用函数:
x=(*fptr)();
x=fptr();
第二种格式看上去和函数调用无异。但是有些程序员倾向于使用第一种格式,因为它明确指出是通过指针而非函数名来调用函数的。

指针的指针
指针的指针看上去有些令人费解。它们的声明有两个星号。例如:
char ** cp;
如果有三个星号,那就是指针的指针的指针,四个星号就是指针的指针的指针的指针,依次类推。当你熟悉了简单的例子以后,就可以应付复杂的情况了。当然,实际程序中,一般也只用到二级指针,三个星号不常见,更别说四个星号了。
指针的指针需要用到指针的地址。
char c='A';
char *p=&c;
char **cp=&p;
利用指针的指针可以允许被调用函数修改局部指针变量和处理指针数组。

void FindCredit(int **);

main()
{
int vals[]={7,6,5,-4,3,2,1,0};
int *fp=vals;
FindCredit(&fp);
printf(%d\n,*fp);
}

void FindCredit(int ** fpp)
{
while(**fpp!=0)
if(**fpp<0)>
=====================
char *Names[]=
{
"Bill",
"Sam",
"Jim",
"Paul",
"Charles",
0
};

main()
{
char **nm=Names; /* nm是一个2维字符数组 */
while(*nm!=0) printf("%s\n",*nm++); /* *nm是指针,以确定指针指向非null */
/* 对于字符数组,数组名虽然是指针,但是也可以表示整个数组指向的字符串。反而“*数组名“却返回错误Segmentation fault。*/
}

先用字符型指针数组Names的地址来初始化指针nm。每次printf()的调用都首先传递指针nm指向的字符型指针,然后对nm进行自增运算使其指向数组的下一个元素(还是指针)。注意完成上述认为的语法为*nm++,它首先取得指针指向的内容,然后使指针自增。
注意数组中的最后一个元素被初始化为0,while循环以次来判断是否到了数组末尾。具有零值的指针常常被用做循环数组的终止符。程序员称零值指针为空指针(NULL)。

Wednesday, 19 November 2008

Terminology: West and East

Also, is it just me, or do Japan and New Zealand look suspiciously similar?  Has anyone seen them at a party together?

Assigning in C

int main ( int argc, char **argv ){}
int main ( int argc, char *argv ) {}

Quote:
An array of char pointers can be represented as a function parameter one of two ways: char *name[] or char **name. I have chosen to use the latter, you can use either one, it is a matter of style, which I refuse to dictate
#####################
In the code you quoted, the former is correct, the latter is wrong. (But since this is C, both main functions should return 0.)

Under certain circumstances, an array decays to a pointer to its first element. In that way, char **argv and char *argv[] are equivalent.
#####################
char *argv .. u r sending a pointer to a char as an argument..this can be a normal pointer or point to a array of chars...

char **argv .. u r sending a pointer to an array of pointers as an argument . which means, each element of this array can itself point to a char array..

Tuesday, 18 November 2008

HOWTO: free up memory

Free Memory by dropping caches | Timesys Embedded Linux

From: http://linux-mm.org/Drop_Caches
To use /proc/sys/vm/drop_caches, just echo a number to it.

To free pagecache:

# echo 1 > /proc/sys/vm/drop_caches

To free dentries and inodes:

# echo 2 > /proc/sys/vm/drop_caches

To free pagecache, dentries and inodes:

# echo 3 > /proc/sys/vm/drop_caches

As this is a non-destructive operation and dirty objects are not freeable, run sync first!

Here are the before and after results from my desktop:

# free
total used free shared buffers cached
Mem: 2074840 1656052 418788 0 140108 907920
-/+ buffers/cache: 608024 1466816
Swap: 3911816 76436 3835380

# sync ; echo 3 > /proc/sys/vm/drop_caches ; free
total used free shared buffers cached
Mem: 2074840 698472 1376368 0 268 126488
-/+ buffers/cache: 571716 1503124
Swap: 3911816 76436 3835380

HOWTO: Mysql JOIN

MySQL LEFT JOIN Explanation

(blogged from: http://www.tizag.com/mysqlTutorial/mysqlleftjoin.php )

How is a LEFT JOIN different from a normal join? First of all, the syntax is quite different and somewhat more complex. Besides looking different, the LEFT JOIN gives extra consideration to the table that is on the left.

Being "on the left" simply refers to the table that appears before the LEFT JOIN in our SQL statement. Nothing tricky about that.

This extra consideration to the left table can be thought of as special kind of preservation. Each item in the left table will show up in a MySQL result, even if there isn't a match with the other table that it is being joined to.

MySQL Join and LEFT JOIN Differences

Here are the tables we used in the previous Mysql Joins lesson.

MySQL family and food Tables:

PositionAge
Dad41
Mom45
Daughter17
Dog
MealPosition
SteakDad
SaladMom
Spinach Soup
TacosDad

We executed a simple query that selected all meals that were liked by a family member with this simple join query:

Simplified MySQL Query:

SELECT food.Meal, family.Position
FROM family, food
WHERE food.Position = family.Position

Result:

Dad - Steak
Mom - Salad
Dad - Tacos

When we decide to use a LEFT JOIN in the query instead, all the family members be listed, even if they do not have a favorite dish in our food table.

This is because a left join will preserve the records of the "left" table.

MySQL LEFT JOIN Example

The code below is the exact same as the code in the previous lesson, except the LEFT JOIN has now been added to the query. Let's see if the results are what we expected.

PHP and MySQL Code:

// Make a MySQL Connection
// Construct our join query
$query = "SELECT family.Position, food.Meal ".
"FROM family LEFT JOIN food ".
"ON family.Position = food.Position";


$result = mysql_query($query) or die(mysql_error());


// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['Position']. " - ". $row['Meal'];
echo "
";

}
?>

Display:

Dad - Steak
Dad - Tacos
Mom - Salad
Daughter -
Dog -

Success! The LEFT JOIN preserved every family member, including those who don't yet have a favorite meal in the food table! Please feel free to play around with LEFT JOIN until you feel like you have a solid grasp of it. This stuff isn't easy!


Another example for 'JOIN', 'LEFT JOIN' and 'RIGHT JOIN' is here:

http://www.wellho.net/mouth/158_MySQL-LEFT-JOIN-and-RIGHT-JOIN-INNER-JOIN-and-OUTER-JOIN.html

mysql, simple commands 2008

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 table
mysql> 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.id
After 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 an
ID, and these two columns are the link between the two tables.

Saturday, 15 November 2008

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

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}}}

Kobe dunk in the air

Thursday, 6 November 2008

HOWTO: find

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.

Monday, 3 November 2008

Confusing terminology in Fedora and Ubuntu

What is called 'orphan', and what is 'obsolete'? Fedora and Ubuntu give us contradictive and confusing definition.

Let's have a look here.

=========================================
Fedora:

"package-cleanup(1)"
--orphans
List installed packages which are not available from currenly configured repositories.
--leaves
List leaf nodes in the local RPM database. Leaf nodes are RPMs that are not relied upon by any other RPM.

=========================================
Ubuntu:

--'synaptic-status-installed(local or obsolete)'
Display only packages that are not (for longer) included in one of the specified repositories.

--"deborphan"
deborphan finds "orphaned" packages on your system. It determines which packages have no other packages depending on their installation and shows you a list of these packages.

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

Accordingly, orphans(fedora)=obsolete(ubuntu), leaves(fedora)=orphan(ubuntu).

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter