Category Archives: Programming

FLTK is fantastic

FLTK has many very cool demos under the /test directory. I realy like it.


difference between stack & heap (general, for a newbie)

Sean Cook wrote:
> Andrey (and others),
> What I should’ve asked is "what is the scope of data when allocated
> from the heap, and what is the scope of data when allocated from the
> stack (where “heap” and “stack” are not standards, but are merely
> common terms.)
Now we are getting somewhere
The scope of memory allocated on the ‘stack’ is the scope
of the enclosing block. They get destroyed when the enclosing
block is finished. Thats why they are called ‘auto’ objects.
int i;
} // block ends, i gets destroyed
The scope of memory allocated on the ‘heap’ is different. Objects
get allocated with new (or malloc) and get destroyed when a corresponding
delete (or free) is executed. Blocks do no longer influence the scope of
these objects.
int* pJ;
int* pI = new int [20];
// Note that 2 things are happening here:
// 1.) An int array is allocated on the free store (aka heap).
// This array will be there until a corresponding delete [] is
// executed
// 2.) A variable pI is created. Since pI was not dynamically created
// with new or malloc, it is an auto object (created on the stack)
// Thus the enclosing block determines its lifetime
pJ = pI;
} // block ends. pI gets destroyed, but not so the int array. It
// will stay there in memory until a delete is done.
delete [] pJ; // now the memory in the free store (aka heap) gets
// released.
> And also, is there a performance difference, in general, of objects
> allocated on the stack versus those allocated on the heap, or is this
> a completely meaningless question?
Free store allocation usually takes more time

Karl Heinz Buchegger


看了一天的KDE+QT还是找不到北,虽然也尝试了一个例子,Qt designer 和 KDevelop也都还很好用,但还是觉得比较难上手,进展比较慢。中午终于第2次放弃了Qt,下午开始看FLTK。希望以后的程序都用fltk来写,下面是FLTK的简单配置。

1. C/C++
    a. code generation, change runtime library to Multi-threaded DLL
    b. Command Line. /Ic:\fltk-1.1.4
    c. precompiled header, turn off.
2. Linker
    a. Command Line. c:\fltk-1.1.4\lib\fltk.lib wsock32.lib comctl32.lib

很不错的FLTK tutorial;
FLTK Video Tutorials—-
Beginner FLTK Tutorial —

#include <FL/fl.h>
#include <FL/fl_window.h>

int main()
 Fl_Window win(720, 486);;
 return Fl::run();



float:         4字节         6-7位有效数字         -3.4E-38     到     3.4E38    
double:     8字节         15~16位有效数字     -1.7E-308   到     1.7E308

GNU Emacs Reference Card

(for version 18)

To enter Emacs, type emacs

suspend Emacs (the usual way of leaving it)          C-z
exit Emacs permanently                               C-x    C-c

read a file into Emacs                               C-x    C-f
save a file back to disk                             C-x    C-s
insert content of another file into this buffer      C-x    i
replace this file with the file you really want      C-x    C-v
write buffer to a specified file                     C-x    C-w
run Dired, the directory editor                      C-x    d

The Help system is simple. Type C-h and follow the directions. If
you are a first-time user, type C-h t for a tutorial.

get rid of Help Window                               C-x    1
scroll Help Windows                                  ESC    C-v
apropos: show commands matching a string             C-h    a
show the function a key runs                         C-h    c
describe a function                                  C-h    f
get mode-specific information                        C-h    m

about partially typed or executing command           C-g
recover a file lost by a system crash          M-x recover-file
undo an unwanted change                              C-x  u or C-_
restore a buffer to its original contents      M-x revert-buffer
redraw garbaged screen                               C-l    

search forward                                       C-s
search backward                                      C-r
regular expression search                            C-M-s

Use C-s or C-r again to repeat the search in either direction

exit incremental search                              ESC
undo effect of last character                        DEL
abort current search                                 C-g

If Emacs is still searching, C-g will cancel the part of the search
not done, otherwise it aborts the entire search.

Cursor Motion:
   entity to move over             backward       forward
   character                       C-b            C-f
   word                            M-b            M-f
   line                            C-p            C-n
   go to line beginning (or end)   C-a            C-e
   sentence                        M-a            M-e
   paragraph                       M-[            M-]
   page                            C-x [          C-x ]
   sexp                            C-M-b          C-M-f
   function                        C-M-a          C-M-e
   go to buffer beginning (or end) M-<            M->

Screen Motion:
   scroll to next screen           C-v
   scroll to previous screen       M-v
   scroll left                     C-x <
   scroll right                    C-x >

   entity to kill                  backward       forward
   character (delete, not kill)    DEL            C-d
   word                            M-DEL          M-d
   line (to end of)                M-O C-k        C-k
   sentence                        C-x DEL        M-k
   sexp                            M-- C-M-k      C-M-k
   kill region                            C-w
   kill to next occurrence of character   M-z char
   yank back last thing killed            C-y
   replace last yank with previous kill   M-y

set mark here                             C-@ ir C-SPC
exchange point and mark                   C-x C-x
set mark arg words away                   M-@
mark paragraph                            M-h
mark page                                 C-x C-p
mark sexp                                 C-M-@
mark function                             C-M-h
mark entire buffer                        C-x h

interactively replace a text string       M-%
using regular expressions                 M-x query-replace-regexp

Valid responses in query-replace mode are
replace this one, go on to next           SPC
replace this one, don't move              ,
skip to next without replacing            DEL
replace all remaining matches             !
back up to the previous match             ^
exit query-replace                        ESC
enter recursive edit (C-M-c to exit)      C-r

delete all other windows                  C-x 1
delete this window                        C-x 0
split window into 2 vertically            C-x 2
split window into 2 horizontally          C-x 5

scroll other window                       C-M-v
switch cursor to another window           C-x o

shrink window shorter                     M-x shrink-window
grow window taller                        C-x ^
shrink window narrower                    C-x {
grow window wider                         C-x }

select a buffer in other window           C-x 4 b
find file in other window                 C-x 4 f
compose mail in other window              C-x 4 m
run Dired in other window                 C-x 4 d
find tag in other window                  C-x 4 .

indent current line (mode-dependant)      TAB
indent region (mode-dependant)            C-M-\
indent sexp (mode-dependant)              C-M-q
indent region rigidly arg columns         C-x TAB

insert newline after point                C-o
move rest of line vertically down         C-M-o
delete blank lines around point           C-x C-o
delete all whitespace around point        M-\
put exactly one space at point            M-SPC

fill paragraph                            M-q
fill region                               M-g
set fill column                           C-x f
set prefix each line starts with          C-x .

uppercase word                            M-u
lowercase word                            M-l
capitalize word                           M-c

uppercase region                          C-x C-u
lowercase region                          C-x C-l
capitalize region                         M-x capitalize-region

The following keys are defined in the Minibuffer.

complete as much as possible              TAB
complete up to one word                   SPC
complete and execute                      RET
show possible completions                 ?
abort command                             C-g

Type C-x ESC to edit and repeat the last command that used the
minibuffer. The following keys are then defined.

previous minibuffer command               M-p
next minibuffer command                   M-n

select another buffer                     C-x b
list all buffers                          C-x C-b
kill a buffer                             C-x k

transpose characters                      C-t
transpose words                           M-t
transpose lines                           C-x C-t
transpose sexps                           C-M-t

check spelling of current word            M-$
check spelling of all words in region     M-x spell-region
check spelling of entire buffer           M-x spell-buffer

find tag                                  M-.
find next occurrence of tag               C-u M-.
specify a new tags file                   M-x visit-tags-table

regexp search on all files in tags table  M-x tags-search
query replace on all the files            M-x tags-query-replace
continue last tags search or query-replace   M-,

execute a shell command                   M-!
run a shell command on the region         M-|
filter region through a shell command     C-u M-|
start a shell in window *shell*           M-x shell

scroll forward                            SPC
scroll reverse                            DEL
beginning of message                      . (dot)
next non-deleted message                  n
previous non-deleted message              p
next message                              M-n
previous message                          M-p
delete message                            d
delete message and back-up                C-d
undelete message                          u
reply to message                          r
forward message to someone                f
send mail                                 m
get newly arrived mail                    g
quit Rmail                                q
output message to another Rmail file      o
output message in Unix-mail style         C-o
show summary of headers                   h

The following have special meaning inside a regular expression.

any single character                      . (dot)
zero or more repeats                      *
one or more repeats                       +
zero or one repeat                        ?
any character in set                      [ ... ]
any character not in set                  [^ ...]
beginning of line                         ^
end of line                               $
quote a special character c               \c
alternative ("or")                        \|
grouping                                  \( ... \)
nth group                                 \n
beginning of buffer                       \`
end of buffer                             \'
word break                                \b
not beginning or end of word              \B
beginning of word                         \<
end of word                               \>
any word-syntax character                 \w
any non-word-syntax character             \W
character with syntax c                   \sc
character with syntax not c               \Sc

copy region to register                   C-x x
insert register contents                  C-x g
save point in register                    C-x /
move point to saved location              C-x j

enter the Info documentation reader       C-h i

Moving within a mode:
   scroll forward                         SPC
   scroll reverse                         DEL
   beginning of node                      . (dot)

Moving between nodes:
   next node                              n
   previous node                          p
   move up                                u
   select menu item by name               m
   select nth menu item by number (1-5)   n
   follow cress reference (return with l) f
   return to last node you saw            l
   return to directory node               d
   go to any node by name                 g

   run Info tutorial                      h
   list Info commands                     ?
   quit Info                              q
   search nodes for regexp                s

start defining a keyboard macro           C-x (
end keyboard macro definition             C-x )
execute last-defined keyboard macro       C-x e
append to last keyboard macro             C-u C-x (
name last keyboard macro                  M-x name-last-kbd-macro
insert lisp definition in buffer          M-x insert-kbd-macro

eval sexp before point                    C-x C-e
eval current defun                        C-M-x
eval region                               M-x eval-region
eval entire buffer                        M-x eval-current-buffer
read and eval minibuffer                  M-ESC
re-execute last minibuffer command        C-x ESC
read and eval Emacs Lisp file             M-x load-file
load from standard system directory       M-x load-library

Here are some examples of binding global keys in Emacs Lisp. Note
that you cannot say "\M-#"; you must say "\e#".

(global-set-key "C-cg" 'goto-line)
(global-set-key "\e\C-r" 'isearch-backward-regexp)
(global-set-key "\e#" 'query-replace-regexp)

An example of setting a variable in Emacs Lisp:

(setq backup-by-copying-when-linked t)

(defun  ()
   (interactive "")

An example:

(defun this-line-to-top-of-screen (line)
   "Reposition line point is on to the top
of the screen. With ARG, put point online ARG. 
Negative counts from bottom."
   (interactive "P")
   (recenter (if (null line)
          (prefix-numeric-value line))))

The argument to "interactive" is a string specifying how to get the
arguments when the function is called interactively. Type "C-h
interactive" for more information.

Copyright 1987 Free Software Products Inc
designed by Stephen Gildea, March 1987, v 1.9
for GNU Emacs version 1.8 on Unix Systems.

The std::list Container Class

Last updated May 7, 2003.

Linked lists are another widely-used data structure. Yet writing a linked list from scratch is an arduous, frustrating and time-consuming task. Instead of reinventing the wheel every time anew, use the STL std::list container class. Its uniform interface, generic nature and seamless integration with other STL constructs make it a superior choice to any homemade list class, as I will show in the following sections.

Creating a list object

The header <list> contains the declaration of std::list and its specialized algorithms. Our first step is to create an empty list of integers called li:

#include <list>
using std::list;
int main()
 list <int> li;

To insert a single element, use the push_back() member function:


To remove the last element of a list, use the pop_back() member function


As opposed to push_back(), push_front() inserts an element before the list’s beginning:

li.push_front(0); // the first element is now 0, not 1

Similarly, pop_front() removes the first element of a list:


To remove a certain value from the list without indicating its exact position, use remove(). remove(n) removes all the elements that equal to n from the list:

li.remove(0); // li doesn't contain 
       //any zeros anymore
Dealing with Sequences

Up until now I have exemplified list operations that operate on a single element at a time. std::list supports sequence operations as well. These operations enable you to traverse, fill, sort and reverse multiple elements at once.

Iteration is easy. The begin() and end() member functions return iterators pointing at the list’s beginning and end, respectively. Use them to access all the list’s elements sequentially. Note that we’re using a const_iterator instead of an ordinary iterator object because the iteration process in this case doesn’t modify the list’s state:

list<int>::const_iterator it;
for(it=li.begin(); it!=li.end(); ++it)
 cout << *it << endl; // each element on a separate line

The assign() member function fills a list with the contents of another sequence such as a vector or an array. It takes two input iterators (for further information on iterator categories, see the resources below) that mark the sequence’s beginning and end, respectively. In the following example, we fill a list with the elements of an array:

int arr[3] = {10,20,30};
li.assign( &arr[0], &arr[3]);

You can merge two lists into one. The merge() member function takes a reference to another list object:

list <int> x;
//..fill x
li.merge(x); // merge the elements of x into li

merge() merges x into li. x becomes empty after the merge operations. To erase one or more elements, use the erase() member function. This function has two overloaded versions; the first of which takes an iterator and erases the element to which it points. The second version takes two iterators that mark the beginning and the end of the sequence to be erased. Suppose you have a list of 10 elements and you want to remove all the elements but the first two. Use erase() as follows:

++it; ++it; // advance to third element
li.erase(it, li.end()); // erase elements 3 – 10
Support for User-Defined Types

The generic nature of list enables you to define specializations, or instances, of user-defined types. For example, you may create lists of strings and Date objects like this:

#include <string>
#include "Date.h"
list<std::string> ls;
list <Date> ld;

Operations that require element comparison such as sort() and unique() use the overloaded < operator. If you intend to use any of these algorithms with lists, define a matching overloaded version of this operator for your class first:

bool operator < (const Date& d1, const Date& d2);
ld.sort(); // OK, using overloaded < operator

Note that in general, sorting a list is less efficient than sorting a vector or a queue. Therefore, if you need to sort elements frequently, you probably shouldn’t use a list in the first place. The same is true for reverse(), which is also supported:

for(it=ld.begin(); it!=ld.end(); ++it)
 cout << *it << endl; // descending order


对ptgrey的camera进行编程还是比较painful的。想想以前自己写olympus和DH-400的程序也没这么麻烦呀,可能是应用相对简单吧。现在写ptgrey的程序真是头疼,没有人可以请教请教,API的doc也讲的很简单,提供的sample也比较少,有时候基本上全靠自己一个人在那瞎琢磨,简直就在挑战自己的想象力和排列组合能力。经过3天的排练组合,程序终于可以了修改frame rate和video mode了,但是改成任意大小显示还有点问题,不过应该可以将就着用了。



程序是从timeSliceDemo这个例子该过来的,创建了单文档多视图的程序,还创建了CMultiDocTemplate。修改frame rate和video mode主要是修改startSync()和grabAndCheckSync()这两个函数,

grabAndCheckSync(), 其中grab image主要由两个函数实现flycaptureLockNext和flycaptureConvertImage。flycaptureConvertImage将arbitrary image type转成dst image,转换之前要设置dst image的格式,我试了一下,这里只能是FLYCAPTURE_BGRU,不然该程序就会报错,血的教训呀,2天时间。如果设置成FLYCAPTURE_BGRU的话,在startSync中创建buffer的时候就要为cols * rows * 4,因为4个channel嘛。

startSync(),这个函数里pixelFormat也要设置成FLYCAPTURE_BGRU,如果设置成FLYCAPTURE_MONO8, FLYCAPTURE_422YUV8, FLYCAPTURE_BGR, FLYCAPTURE_RGB8等都会出错。doc里没有说,显然ptgrey连明年版本里的功能都先写进doc里了,可把我害惨了。如果要改变图像的分辨率,要在这两个函数里改,flycaptureGetCustomImagePacketInfo和flycaptureStartLockNextCustomImagePacket。或者不用packet,直接用flycaptureStartLockNext,而不用flycaptureStartLockNextCustomImagePacket,这样就可以设置VIDEO_MODE和FRAME_RATE。比如设置成15Hz,省得server的workload太大。


lab买的server内存大了也麻烦,整个8G内存居然camera的驱动就不认了,只好拔掉4根内存条,或者将OS从windows2003server Enterprise转成winxp32bit,这时PTgrey的camera才能用(据说ptgrey做的camera还是最好的)。这些哥们设计驱动的时候估计压根就没有想到有人将这么多个camera同时连到一个server上,就算想到了估计也没有想到会在机子里装这么多内存,可是我们就是这么干的。搞得这一星期来我就不停的重起机子,在server,winxp64,winxp32之间不停的切换,感觉自己在无偿得为ptgrey做测试,到现在提交的问题一个也没有解决,郁闷不是一两星期了。


[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows 2003 Server, Enterprise Edition" /fastdetect


How to use manifests and re-distributable assemblies?

Q: I have an MFC application that runs on my computer, but when I try to run it on another PC I receive an error message that the application failed to initialize and I should re-install it. What should I do?
A: By default, Visual C++ 2005 builds all native C/C++ applications as isolated applications, i.e. self-describing applications that use manifest files to describe their dependencies to VC++ libraries. The problem occurs because your application doesn’t have a manifest, or it has dependencies to assemblies that don’t exist on the target PC, or they have a different version number. Basically you have to do two things to solve the problem:

  • Distribute a manifest resource file along with your application
  • Deploy the re-distributable assemblies that your application depends upon

Q: What is a manifest resource?
A: A manifest resource is an XML file that describes the dependencies of your application. Such dependencies can include the most current version of the Windows common controls, as well as library assemblies, such as MFC, ATL or CRT assemblies.
Your manifest should have the same name as the application and the extension "manifest" and should specify the version number of your assembly (executable or dynamic library), processor architecture, name of the assembly and platform type; a description of your assembly is also recommended.


<?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <assemblyIdentity version="" processorArchitecture="X86" name="CompanyName.ProductName" type="win32" /> <description>Description of your application.</description> </assembly>

Q: How do I specify dependencies?
A: You have to add a element to the XML-based manifest. For instance, if you want your application to use the Windows common controls with the XP-like style, add a dependency to the assembly called "Microsoft.Windows.Common-Controls":


<?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <assemblyIdentity version="" processorArchitecture="X86" name="CompanyName.ProductName" type="win32" /> <description>Description of your application.</description> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> </assembly>

Q: I now understand what a manifest resource is, but what are re-distributable assemblies?
A: These are assemblies provided as dynamic link-libraries that you can deploy with your application, because they are required for the application to work. Assemblies are provided in several configurations, Release and Debug, but you can only re-distribute the release configurations (can be found in Visual Studio 8 installation folder, VC\redist).
Visual C++ 2005 supports a new deployment model for Windows client applications based on isolated applications and side-by-side assemblies. Basically, assemblies can be:

  • shared (they are globally registered in the system, installed in the Global Assembly Cache – GAC folder in Windows – and available to all applications) or
  • side-by-side, described with a manifest, distributed with the application and available only to that application

In Visual C++ 2005, library assemblies (such as MFC, ATL, CRT) have been rebuilt as shared side-by-side assemblies and installed in the native assembly cache, WinSxS folder in Windows. That means they are not globally registered in the system, but are globally available to the applications that specify a dependency with a manifest file.
The target machine where you run your application may already have the required dependencies installed. You can look-up for them in the WinSxS folder. Assemblies are grouped here on categories, each with its own folder. Folder names start with the platform name, followed by Microsoft, category (Windows, VC80, MSXML, Tools), assembly name, a token number, version and additional identifiers. The manifest files for these assemblies are located in the Manifest subfolder of WinSxS and have the same name as the folder of the assembly group they contain information about.
Q: How do I specify dependencies for my application in the manifest file?
A: Suppose your application uses MFC as a shared library, so it has at least a dependency on MFC and one on the C runtime library and C++ runtime library (these two part of the CRT assembly group). In this case your manifest file should look like this:


<?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <assemblyIdentity version="" processorArchitecture="X86" name="CompanyName.ProductName" type="win32" /> <description>Description of your application.</description> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50727.42' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.MFC' version='8.0.50727.42' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> </assembly>

If the target machine already has these assemblies and the version info (process architecture, version, public key token) matches, you don’t have to redistribute anything, because your application will be able to use the assemblies from the native assembly cache (WinSxS). Since you cannot be sure of that you should distribute these assemblies with your application (in the same folder with the application). Windows will first looks-up for assemblies in the current folder and then in WinSxS and GAC, so distributing them in the working folder ensures those assemblies are used.
To distribute the correct assemblies after building the application, go to the Visual Studio 8 installation folder in VC\redist and select your target platform folder, i.e. x86 or amd64. Inside, you will see folders for ATL, MFC, CRT, MFCLOC and OPENMP.
The Microsoft.VC80.MFC folder contains 4 DLLS and a manifest file, called Microsoft.VC80.MFC.manifest. You must copy at least MFC80.DLL (or MFC80U.DLL if you built for UNICODE) to your application working folder. You must make sure that the version number of the MFC assembly specified in this manifest matches the one you put in your application manifest and the one of the DLL itself (this should be implicit, but should check that from the file properties, Alt + Enter > Version).
The Microsoft.VC80.CRT contains 3 DLLs and the manifest. Of these three DLLs you need at least msvcr80.dll (C runtime library) and msvcp80.dll (C++ runtime library). The same caution for the version number must be taken.
With all these taken care of, your application should correctly run on any target machine.