Google
 

12/30/08

Mac and ldconfig

In Mac system, there is NO ldconfig which exists in Linux system. The corresponding command in Mac is called "dyld". You can find out more details by "man dyld"

12/18/08

Switch between gdm and kdm

First make sure that you installed gdm and kdm. Then use the following command in a console.

>> sudo dpkg-reconfigure gdm

From the dialog choose either gdm or kdm.



9/21/08

C++ Virtual function

Purpose

The concept of the virtual function solves the following problem:

In OOP when a derived class inherits from a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class functions overridden by the derived class, a problem then arises when a derived object has been cast as the base class type. When a derived object is referred to as being of the base's type, the desired function call behavior is ambiguous.

The distinction between virtual and not virtual resolves this ambiguity. If the function in question is designated "virtual" in the base class then the derived class's function would be called (if it exists). If it is not virtual, the base class's function would be called.

Virtual functions overcome the problems with the type-field solution by allowing the programmer to declare functions in a base class that can be redefined in each derived class.

Example

For example, a base class Animal could have a virtual function eat. Subclass Fish would implement eat() differently than subclass Wolf, but you can invoke eat() on any class instance referred to as Animal, and get the eat() behavior of the specific subclass.

This allows a programmer to process a list of objects of class Animal, telling each in turn to eat (by calling eat()), with no knowledge of what kind of animal may be in the list. You also do not need to have knowledge of how each animal eats, or what the complete set of possible animal types might be.

The following is an example in C++:

#include 
using namespace std;

class Animal
{
public:
virtual void eat() { cout << "I eat like a generic Animal." << class="br0">}
};

class Wolf : public Animal
{
public:
void eat() { cout << "I eat like a wolf!" << class="br0">}
};

class Fish : public Animal
{
public:
void eat() { cout << "I eat like a fish!" << class="br0">}
};

class GoldFish : public Fish
{
public:
void eat() { cout << "I eat like a goldfish!" << class="br0">}
};


class OtherAnimal : public Animal
{
};

int main()
{
Animal* anAnimal[5];

anAnimal[0] = new Animal();
anAnimal[1] = new Wolf();
anAnimal[2] = new Fish();
anAnimal[3] = new GoldFish();
anAnimal[4] = new OtherAnimal();

for (int i = 0; i < 5; i++) {
anAnimal[i]->eat();
delete anAnimal[i];
}

return 0;
}

Output with the virtual method Animal::eat():

I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.

Output if Animal::eat() were not declared as virtual:

I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.

Pure virtual function and virtual function
from here

Finally, we arrive at the end of our long journey through inheritance! This is the last topic we will cover on the subject. So congratulations in advance on making it through the hardest part of the language!

Pure virtual (abstract) functions and abstract base classes

So far, all of the virtual functions we have written have a body (a definition). However, C++ allows you to create a special kind of virtual function called a pure virtual function (or abstract function) that has no body at all! A pure virtual function simply acts as a placeholder that is meant to be redefined by derived classes.

To create a pure virtual function, rather than define a body for the function, we simply assign the function the value 0.

  1. class Base
  2. {
  3. public:
  4. const char* SayHi() { return "Hi"; } // a normal non-virtual function
  5. virtual const char* GetName() { return "Base"; } // a normal virtual function
  6. virtual int GetValue() = 0; // a pure virtual function
  7. };
class Base { public: const char* SayHi() { return "Hi"; } // a normal non-virtual function virtual const char* GetName() { return "Base"; } // a normal virtual function virtual int GetValue() = 0; // a pure virtual function };

When we add a pure virtual function to our class, we are effectively saying, “it is up to the derived classes to implement this function”.

Using a pure virtual function has two main consequences: First, any class with one or more virtual functions becomes an abstract base class, which means that it can not be instantiated! Consider what would happen if we could create an instance of Base:

  1. int main()
  2. {
  3. Base cBase; // pretend this was legal
  4. cBase.GetValue(); // what would this do?
  5. }
int main() { Base cBase; // pretend this was legal cBase.GetValue(); // what would this do? }

Second, any derived class must define a body for this function, or that derived class will be considered an abstract base class as well.

Let’s take a look at an example of a pure virtual function in action. In a previous lesson, we wrote a simple Animal base class and derived a Cat and a Dog class from it. Here’s the code as we left it:

  1. #include
  2. class Animal
  3. {
  4. protected:
  5. std::string m_strName;
  6. // We're making this constructor protected because
  7. // we don't want people creating Animal objects directly,
  8. // but we still want derived classes to be able to use it.
  9. Animal(std::string strName)
  10. : m_strName(strName)
  11. {
  12. }
  13. public:
  14. std::string GetName() { return m_strName; }
  15. virtual const char* Speak() { return "???"; }
  16. };
  17. class Cat: public Animal
  18. {
  19. public:
  20. Cat(std::string strName)
  21. : Animal(strName)
  22. {
  23. }
  24. virtual const char* Speak() { return "Meow"; }
  25. };
  26. class Dog: public Animal
  27. {
  28. public:
  29. Dog(std::string strName)
  30. : Animal(strName)
  31. {
  32. }
  33. virtual const char* Speak() { return "Woof"; }
  34. };
#include class Animal { protected: std::string m_strName; // We're making this constructor protected because // we don't want people creating Animal objects directly, // but we still want derived classes to be able to use it. Animal(std::string strName) : m_strName(strName) { } public: std::string GetName() { return m_strName; } virtual const char* Speak() { return "???"; } }; class Cat: public Animal { public: Cat(std::string strName) : Animal(strName) { } virtual const char* Speak() { return "Meow"; } }; class Dog: public Animal { public: Dog(std::string strName) : Animal(strName) { } virtual const char* Speak() { return "Woof"; } };

We’ve prevented people from allocating objects of type Animal by making the constructor protected. However, there’s one problem that has not been addressed. It is still possible to create derived classes that do not redefine Speak(). For example:

  1. class Cow: public Animal
  2. {
  3. public:
  4. Cow(std::string strName)
  5. : Animal(strName)
  6. {
  7. }
  8. // We forgot to redefine Speak
  9. };
  10. int main()
  11. {
  12. Cow cCow("Betsy");
  13. cout << class="string">" says " <<>
  14. }
class Cow: public Animal { public: Cow(std::string strName) : Animal(strName) { } // We forgot to redefine Speak }; int main() { Cow cCow("Betsy"); cout <<>This will print:

Betsy says ???

What happened? We forgot to redefine Speak, so cCow.Speak() resolved to Animal.Speak(), which isn’t what we wanted.

A better solution to this problem is to use a pure virtual function:

  1. #include
  2. class Animal
  3. {
  4. protected:
  5. std::string m_strName;
  6. public:
  7. Animal(std::string strName)
  8. : m_strName(strName)
  9. {
  10. }
  11. std::string GetName() { return m_strName; }
  12. virtual const char* Speak() = 0; // pure virtual function
  13. };
#include class Animal { protected: std::string m_strName; public: Animal(std::string strName) : m_strName(strName) { } std::string GetName() { return m_strName; } virtual const char* Speak() = 0; // pure virtual function };

There are a couple of things to note here. First, Speak() is now a pure virtual function. This means Animal is an abstract base class, and can not be instantiated. Consequently, we do not need to make the constructor protected any longer (though it doesn’t hurt). Second, because our Cow class was derived from Animal, but we did not define Cow::Speak(), Cow is also an abstract base class. Now when we try to compile this code:

  1. class Cow: public Animal
  2. {
  3. public:
  4. Cow(std::string strName)
  5. : Animal(strName)
  6. {
  7. }
  8. // We forgot to redefine Speak
  9. };
  10. int main()
  11. {
  12. Cow cCow("Betsy");
  13. cout << class="string">" says " <<>
  14. }
class Cow: public Animal { public: Cow(std::string strName) : Animal(strName) { } // We forgot to redefine Speak }; int main() { Cow cCow("Betsy"); cout <<>The compiler will give us a warning because Cow is an abstract base class and we can not create instances of abstract base classes:

C:\\Test.cpp(141) : error C2259: 'Cow' : cannot instantiate abstract class due to following members: C:\Test.cpp(128) : see declaration of 'Cow' C:\\Test.cpp(141) : warning C4259: 'const char *__thiscall Animal::Speak(void)' : pure virtual function was not defined

This tells us that we will only be able to instantiate Cow if Cow provides a body for Speak().

Let’s go ahead and do that:

  1. class Cow: public Animal
  2. {
  3. public:
  4. Cow(std::string strName)
  5. : Animal(strName)
  6. {
  7. }
  8. virtual const char* Speak() { return "Moo"; }
  9. };
  10. int main()
  11. {
  12. Cow cCow("Betsy");
  13. cout << class="string">" says " <<>
  14. }
class Cow: public Animal { public: Cow(std::string strName) : Animal(strName) { } virtual const char* Speak() { return "Moo"; } }; int main() { Cow cCow("Betsy"); cout <<>Now this program will compile and print:

Betsy says Moo

A pure virtual function is useful when we have a function that we want to put in the base class, but only the derived classes know what it should return. A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these function before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.

Interface classes

An interface class is a class that has no members variables, and where all of the functions are pure virtual! In other words, the class is purely a definition, and has no actual implementation. Interfaces are useful when you want to define the functionality that derived classes must implement, but leave the details of how the derived class implements that functionality entirely up to the derived class.

Interface classes are often named beginning with an I. Here’s a sample interface class:

  1. class IErrorLog
  2. {
  3. virtual bool OpenLog(const char *strFilename) = 0;
  4. virtual bool CloseLog() = 0;
  5. virtual bool WriteError(const char *strErrorMessage) = 0;
  6. };
class IErrorLog { virtual bool OpenLog(const char *strFilename) = 0; virtual bool CloseLog() = 0; virtual bool WriteError(const char *strErrorMessage) = 0; };

Any class inheriting from IErrorLog must provide implementations for all three functions in order to be instantiated. You could derive a class named FileErrorLog, where OpenLog() opens a file on disk, CloseLog() closes it, and WriteError() writes the message to the file. You could derive another class called ScreenErrorLog, where OpenLog() and CloseLog() do nothing, and WriteError() prints the message in a pop-up message box on the screen.

Now, let’s say you need to write some code that uses an error log. If you write your code so it includes FileErrorLog or ScreenErrorLog directly, then you’re effectively stuck using that kind of error log. For example, the following function effectively forces callers of MySqrt() to use a FileErrorLog, which may or may not be what they want.

  1. double MySqrt(double dValue, FileErrorLog &cLog)
  2. {
  3. if (dValue <>
  4. {
  5. cLog.WriteError("Tried to take square root of value less than 0");
  6. return 0.0;
  7. }
  8. else
  9. return dValue;
  10. }
double MySqrt(double dValue, FileErrorLog &cLog) { if (dValue <>A much better way to implement this function is to use IErrorLog instead:

  1. double MySqrt(double dValue, IErrorLog &cLog)
  2. {
  3. if (dValue <>
  4. {
  5. cLog.WriteError("Tried to take square root of value less than 0");
  6. return 0.0;
  7. }
  8. else
  9. return dValue;
  10. }
double MySqrt(double dValue, IErrorLog &cLog) { if (dValue <>Now the caller can pass in any class that conforms to the IErrorLog interface. If they want the error to go to a file, they can pass in an instance of FileErrorLog. If they want it to go to the screen, they can pass in an instance of ScreenErrorLog. Or if they want to do something you haven’t even thought of, such as sending an email to someone when there’s an error, they can derive a new class from IErrorLog (eg. EmailErrorLog) and use an instance of that! By using IErrorLog, your function becomes more independent and flexible.

Interface classes have become extremely popular because they are easy to use, easy to extend, and easy to maintain. In fact, some modern languages, such as Java and C#, have added an “interface” keyword that allows programmers to directly define an interface class without having to explicitly mark all of the member functions as abstract. Furthermore, although Java and C# will not let you use multiple inheritance on normal classes, they will let you multiply inherit as many interfaces as you like. Because interfaces have no data and no function bodies, they avoid a lot of the traditional problems with multiple inheritance while still providing much of the flexibility.


Using rsync to synchronize the files.

rsync -autv username@xxx.xxx.xxx.edu:/source_directory/ ./dest_directory

Use "-autv" options. This will make sure that if the files in the dest_directory is newer, it will not be overwritten.
"t" will preserve the time stamp.
"a" archive
"u" update; skip files that are newer on the receiver
"v" print out information

Another thing needs to be careful is that "/" after source_directory is needed if you want to synchronize the files inside source_directory. If "/" is ignored, then source_directory will be copied to dest_directory.

For example: If you have source_directory inside which you have source1, source2 two files. Now you want to synchronize the files with your directory "dest_dir" which at this moment is empty.

> rsync -autv ./source_directory/ ./dest_dir
The above command will copy source1 and source2 to ./dest_dir (since at this moment ./dest_dir is still empty, so the files inside ./source_directory is newer).

What if you want to exclude ./tmp directory?
> rsync -autv --exclude "tmp/" ./source_directory/ ./dest_dir
temp
is relative to the directory you are trying to backup, which is ./source_directory/ here.


> rsync -autv ./source_directory ./dest_dir
However, the above command will copy ./source_directory to ./dest_dir. It copy it as a directory. After the command, inside your ./dest_dir you will have another folder called "source_directory".

9/16/08

42 of the Best Free Linux Graphics Software

42 of the Best Free Linux Graphics Software

The original post is here


Linux is a very strong platform for budding artists, photographers, animators, and designers. With inexpensive hardware, free software, and a modicum of talent and inspiration, anyone can create professional-looking computer graphics.

There is a huge range of Open Source software available to create, modify and convert 2D and 3D computer graphics. To provide an insight into the software that is available, we have compiled a list of 42 high quality Linux graphics applications. The vast majority of the software featured here sports an attractive graphical front-end, although we have not neglected console based applications.


Now, let's explore the 42 graphics applications at hand. For each title we have compiled its own portal page, providing a screenshot of the software in action, a full description with an in-depth analysis of its features, together with links to relevant resources and reviews.

3D Modeling and Rendering
Art of Illusion 3D-modeler, renderer and raytracer
Blender Very fast and versatile 3D modeler/renderer
K-3D 3D modeling and animation system
Pixie Photorealistic raytracing renderer for generating photorealistic images
POV-Ray Full-featured ray tracer
Radiance Suite of tools for performing lighting simulation
Sunflow Rendering system for photo-realistic image synthesis
YafRay Powerful raytracer


Raster Graphics Editor
CinePaint Painting, manipulation and image processing
GIMP GNU Image Manipulation Program
Gimpshop Fork of GIMP mimicing Adobe Photoshop's interface
Krita Edit and paint images


Vector Graphics Editor
Inkscape Vector-based drawing program
OpenOffice.org Draw Produces simple diagrams, flowcharts and 3-D artwork
Xara Xtreme Heavyweight vector graphics, illustration and DTP program


Animation
Pencil Create traditional hand-drawn animation using bitmap and vector graphics
Ktoon Produce professional cartoons
Synfig Create and edit 2D animations and compositions


Drawing
ArgoUML UML modelling tool
Dia Diagram editor
Kivio Flowcharting program for the KDE Office Suite
Skencil Interactive vector drawing program


Photo Management
blueMarine Digital photo manipulation software
F-Spot Personal photo management application


Viewers
Cornice Designed to be a free replacement of ACDSee
gThumb Advanced image viewer and browser
Gwenview Simple image viewer for KDE 4
Eye of Gnome Fast and functional image viewer
Imgv Powerful image viewer


Camera
Cheese Take pictures and videos from your webcam
digiKam Digital photo management application for KDE
gphoto2 Set of digital camera software applications
Rawstudio Raw-image converter and manipulation


Scanning
Kooka Scanner program for KDE
Tesseract Optical Character Recognition Engine
XSane Featureful graphical frontend for SANE


CAD
QCad Professional CAD System
BRL-CAD Constructive Solid Geometry (CSG) solid modeling system


Fractals
Gnofract 4D
GNOME based fractal generator
XaoS Real-time interactive fractal zoomer


Utilities
Agave Colorscheme designer for the GNOME desktop
ImageMagick Software suite to create, edit, and compose bitmap images

7/4/08

HOWTO: Backup Your Mac With rsync

About This Document

  • Created: 26 January 2005
  • Updated: 18 December 2005: added note for Mac OS X 10.4 and general clean up.
  • Updated: 18 February 2006: added note about using -x switch to reduce need for specified excludes. From suggestion by Mike Bremford.

Author: Matthew Phillips

This document describes how to setup a system for automatically backing up a Mac (OS X 10.2 or later) to an external drive using the freely available rsync utility. This applies to any kind of external drive including FireWire, USB and network drives. It does not apply to CD-R or DVD-R media. It also does not apply if you want to implement an incremental backup system.

External Drive Setup

If you've already set up the external drive you'll be backing up to, you can skip to the next section.

To create a partition on the disk drive, connect the drive and wait for Mac OS X to offer to run Disk Utility to initialise it.

The details of how to use Disk Utility are beyond this HOWTO and are well covered by the Mac's online help: just run help and search for "Partitioning a hard disk".

Below is a screenshot of a partitioned drive in Disk Utility. In this example I've chosen to create two partitions, named OSX and Data, one for backing up the core system and user accounts, and one for large data files such as music and movies. These appear as drives on the desktop and as folders in the /Volumes folder. If you're not sure what you want, just create a single OSX partition.

Disk Utility screenshot

When you've created the partitions, you'll see them appear as empty drives in the Finder and on the Desktop.

Ensuring Ownership Permissions Are Enabled

For some reason Mac OS turns off permissions management for new partitions by default, which will result in "chown" errors from rsync if not rectified.

To enable permissions, select the partition in on the Desktop and show its information page by hitting Command+I. Expand the "Ownership & Permissions" section and make sure that "Ignore ownership on this volume" is not checked as shown below.

Partition info screenshot

Software

Note to users of Mac OS X 10.4 and later: Apple extended the version of rsync shipped with Mac OS X 10.4 to directly support resource forks, so if you don't want to use the GUI provided by rsyncx, you can skip the software installation and go to the Advanced section.

You only need one piece of software to backup your Mac that's not already part of Mac OS: rsyncx. Although Mac OS X comes packaged with bog-standard Unix rsync, rsyncx is needed in order to preserve Mac-specific resource forks. While Apple is no longer recommending applications use resource forks, some classic Mac apps still rely on them. rsyncx also comes with a graphical front end that can make it much easier to get started.

You can download rsyncx from VersionTracker (version 2.1 was current when this document was last updated). More information about rsyncx and its developer, Kevin Boyd, is available here.

To install rsyncx, simply extract the rsyncx archive and find the installer package inside it which will be called something like RsyncX_v2.1.pkg. Double-clicking this will install the rsyncx GUI and the command line program /usr/local/bin/rsync (it will not delete the built-in rsync).

Simple Setup

If you just want to create a backup of your entire Mac hard disk (and optionally make it bootable), then this section is for you. If you want to back up only some of the drive or use multiple partitions, see the Advanced section.

The simplest way to use rsyncx is to use the graphical front end: just select RsyncX from the Applications folder. Below is a screenshot of how to set up the application to back up the entire Mac hard drive to the external drives' OSX partition and make it bootable.

RsyncX screenshot

Tips

  • The "Remove Unmatched" checkbox tells rsyncx to delete any files on the external drive that have been deleted since the last backup. Coupled with Archive mode (which preserves all file modification times, ownerships, etc), this will produce an exact copy of the drive.

    Note: this option will also mean that any files you may have accidentally deleted will also be deleted from the backup too, making it possible to lose a file permanently if you don't notice its deletion in time.

  • Although it's not obvious, you can resize the window by dragging the right corner which displays more than one "Source" path. You can use this to select several specific folders rather than the whole drive.
  • If you're using FileVault to encrypt your home folder, you may want to consider backing up the system from another account. This is because if you run the backup while you are logged in, the backup process will copy your unencrypted home folder's contents.

    The simplest way to do this is to create a special "Backup" user and, when you do a backup, log off from your account and log back in as Backup to run the backup process. This will result in your home folder also being encrypted in the backup (it appears as a single, large, encrypted .sparseimage file). The one downside of doing it this way is that you'll also need to grant the backup user admin rights as described in the advanced section.

    In fact running the backup while logged in as another user can be a good idea even if you're not using FileVault, since it reduces the likelihood that processes will modify files while they're being copied.

Booting From Backup

Obviously the best way to test whether the backup will work in an emergency is to boot from it. To do this, restart the Mac and hold the Option key down while it boots. You will be presented with a screen that allows you to choose the boot drive. If you can successfully boot and login from the external drive, then you can be fairly confident of being able to recover from a disaster by simply booting from backup and using rsync in reverse to restore the system.

Advanced Setup

If you want to do more funky things like backup different parts of the drive to different partitions, exclude certain files from backup or any other sort of customised stuff, then you may want to write some scripts to drive rsync from the command line. This section contains some tips on doing this. It assumes you know Unix-type stuff like vi.

Mac OS X 10.4 users

As of 10.4 Apple's shipping rsync supports resource forks by specifying the -E flag on the command line. The example script allows switching to the OS X built-in rsync by swapping commented definition of RSYNC at the top of the script.

Below is the text of a script called backup.sh that can be used to backup all of the main hard disk, with a specified set of exceptions listed in a file called backup_excludes.txt.

  #!/bin/sh

# To use Apple's rsync switch commented lines below
# To use rsyncx:
RSYNC=/usr/local/bin/rsync --eahfs --showtogo
# To use built-in rsync (OS X 10.4 and later):
# RSYNC=/usr/bin/rsync -E

# sudo runs the backup as root
# --eahfs enables HFS+ mode
# -a turns on archive mode (recursive copy + retain attributes)
# -x don't cross device boundaries (ignore mounted volumes)
# -S handle sparse files efficiently
# --showtogo shows the number of files left to process
# --delete deletes any files that have been deleted locally
# $* expands to any extra command line options you may give

sudo $RSYNC -a -x -S --delete \
--exclude-from backup_excludes.txt $* / /Volumes/OSX/

# make the backup bootable - comment this out if needed

sudo bless -folder /Volumes/OSX/System/Library/CoreServices

You can copy and paste this text into a new new and then execute chmod u+x backup.sh to make it into an executable command.

The file backup_excludes.txt contains a list of files to exclude. An example is shown below — this list can be used as the default set of directories that should not be backed up which you can add to as needed.

/tmp/*
/Network/*
/cores/*
*/.Trash
/afs/*
/automount/*
/private/tmp/*
/private/var/run/*
/private/var/spool/postfix/*
/private/var/vm/*
/Previous Systems.localized
.Spotlight-*/

Tips

  • You can run the backup script with the -n option to test it. In this mode rsync will run through the motions but not make any actual changes. Adding -v will cause rsync to print out all the files it will be changing.
  • If you're running the backup as the "backup" user as recommended in a previous tip, you will need to grant the backup user the ability to run the rsync and bless commands as root. To do this you need to run "sudo visudo" as an admin user and add the lines highlighted in green to make it look like the example below.
    # sudoers file.
    #
    # This file MUST be edited with the 'visudo' command as root.
    #
    # See the sudoers man page for the details on how to write a sudoers file.
    #

    # Host alias specification

    # User alias specification

    # Cmnd alias specification
    Cmnd_Alias BACKUP = /usr/bin/rsync, /usr/local/bin/rsync, /usr/sbin/bless

    # Defaults specification

    # User privilege specification
    root ALL=(ALL) ALL
    %admin ALL=(ALL) ALL
    backup ALL=BACKUP
  • The fact that the command line version of rsyncx has the same name as the built-in rsync carries the danger that you may not be using the right one. The standard rsync that comes with Mac OS X is in /usr/bin/rsync and, since /usr/local/bin is usually used before /usr/bin, the extended rsync should be what you get. If you want to be sure, run "rsync 2>&1 | head -n 3" and if you see "HFS+ filesystem support for OSX (C)2004 Kevin A. Boyd" as the last line, then you're using rsyncx.

4/1/08

Class with circular dependence.

Use a forward declaration.

Sometimes you must create two classes that use each other. This is called a circular dependency. For example:

class Fred {
public:
Barney* foo(); // Error: Unknown symbol 'Barney'
};

class Barney {
public:
Fred* bar();
};
The Fred class has a member function that returns a Barney*, and the Barney class has a member function that returns a Fred. You may inform the compiler about the existence of a class or structure by using a "forward declaration":

class Barney;
This line must appear before the declaration of class Fred. It simply informs the compiler that the name Barney is a class, and further it is a promise to the compiler that you will eventually supply a complete definition of that class.


The source is from here

3/5/08

Linux desktop screencasting.

In this webcast, the author uses gtk-recordmydesktop (GUI for Gnome) to record the desktop. He also showed how to use the command (recordmydesktop) in stead of GUI. Of course you don't have to switch to Gnome to use gtk-recordmydesktop, there is a corresponding GUI for KDE users. It is called qt-recordmydesktop. You can find more details on the recordmydesktop's website.

Another video regarding linux desktop recording is here, where the author used three different open source software to finish the task.


Get the Flash Player to see this movie.




Original location: 'An Introduction to Screencasting in Linux' at ShowMeDo.



Screencast Guide: Capure Your Linux Desktop on Video!

Have you ever wanted to record a video of your sleek desktop, with customized icons, taskbar and such? Or have you ever wanted to take a video of some cool XGL/AIGLX effects? Or maybe a video tutorial to teach a friend how to use something or to upload it on your personal webpage for everyone to see it? There are a lot of reasons why one would want to record his desktop and more importantly, there are a lot of ways to do it. However, anyone wanting to record his desktop should know at least a couple of methods so he can use the most suitable one, depending on each task.

In the past, creating a screencast in Linux was based on VNC technology, which often caused problems for inexperienced users. Nowadays, creating a Linux screencast requires only a few clicks.

Method 1: Using xvidcap:

Xvidcap is a rather advanced screen capture tool. It allows you to select the size and position of the rectangular area to capture. The output file can be either mpeg, avi, asf or mov but the output file can also be saved as swf, flv, dv, m1v or m2v. It can also capture an audio stream from /dev/dsp (digital sampling and digital recording device) and add it to the video stream.

To install xvidcap, you'll have to:

- Download the latest version of xvidcap.
- Untar, compile and install it:

CODE

# tar xfz xvidcap-x.x.x.tar.gz
# cd xvidcap-x.x.x
# ./compile
# make
# make install


- To run it, type xvidcap in a terminal.
- Using it is pretty straight-forward and it should be used without problems by both advanced and inexperienced users. The preferences window has some advanced options which can be set to "auto" if you don't know what they're for.

NOTE: From what I've noticed, xvidcap has the tendency to use a lot of resources while recording the desktop video, making the desktop use close to impossible. However, it works pretty well with XGL/AIGLX.

Method 2: Using Istanbul:

Istanbul is a desktop session recorder for Linux. It records your session to an OGG Theora video file. Recording your dekstop session is a very easy process, as it only required clicking the notification area icon to start the recording and clicking that icon again will end the recording process.

Istanbul can most likely be found on most distro's repositories so installing it only requires telling your distro's package manager to install it. For instance, under Fedora, run:

CODE

# yum install istanbul


Alternatively, you can download the source code, compile and install it.

- To run it, simply type istanbul

NOTE: Istanbul uses a little bit less resources during recording so using your desktop while recording it would be a little bit less stressful than when using xvidcap.

Method 3: Using recordMyDesktop

recordMyDesktop is a desktop session recorder which attempts to be very easy to use, yet effective at its primary task. The program is separated in two: a simple command line tool that performs the basic tasks of capturing and encoding and an (optional) interface written in Python, which reveals the program’s functionality in a usable and easy way.

- To install recordMyDesktop, you'll have to download the source package from the project's website.
- You can either download the console version of this program or both the console and the GTK version.
- Uncompress them both, compile and install it with the usual ./configure ; make ; make install.
- Run it with the command recordmydesktop or gtk-recordmydesktop, depending on which files you’ve compiled and installed.
- The console version (if ran without parameters), will save an out.ogg file in $HOME, while the gtk version will open a window through which you can set several configuration options. Each option is explained in detail. The GTK version will also save an out.ogg file in $HOME.

NOTE1: By default, recordMyDesktop first records the desktop capture as an uncompressed video file and when the capture is stopped, it will be compressed with a codec. This way, you can use your desktop more easily while capturing the video. Unfortunately, this method will use a lot more disk space. However, if you want realtime compressing, you can define so in the configuration window.

NOTE2: recordMyDesktop will only produce files using only open formats (theora for video and vorbis for audio).

If the GTK version will output ImportError: from recordMyDesktop import rmdSimple, you should try running the following command and then try running the program again:

CODE

ln -s /usr/local/lib/python2.4/site-packages/recordMyDesktop/ /usr/lib/python2.4/site-packages/recordMyDesktop


Method 4: Using Pyvnc2swf

Pyvnc2swf is a cross-platform application that captures the Desktop and saves it as a ShockWave Flash (swf) format. This is useful when the recording you're about to make will be added to a website. You'll have the ability to choose the framerate, as well as the movie size.

To start using pyvnc2swf, you'll have to:

- Download the latest version of x11vnc.
- Download the latest version of pyvnc2swf.
- Compile and install x11vnc:

CODE

cd download_folder
tar xfz x11vnc-versionnumber.tar.gz
cd x11vnc-versionnumber/
./configure
make
make install


- Uncompress the python version of vnc2swf to the $HOME directory:

CODE

cd $HOME
tar xfz pyvnc2swf-versionnumber.tar.gz


- To start using the program, simply type:

# x11vnc -localhost -viewonly -wait 10 -defer 10 &
# python ~/pyvnc2swf*/vnc2swf.py -o tutorial.swf -N -S localhost:0


- A small window will appear. You can set the capture options from the Options menu and press the Start button to record your desktop activity. Finally, to stop recording and saving the swf file, press the Stop button and go to File / Save as to save the swf file, together with a html file for easy movie viewing through a browser.

By: Mihai Marinof, Linux Editor

Vedio: record the linux desktop (screencast)

This is a nice video tutorial for linux desktop screencasting. In this video, the author used several software to do the job. The reason for that is he wanted better quality of sound. You can use "recordMyDesktop" alone to do the same thing, which is for most people easier. You can find how to use "recordMyDesktop" alone to do screencasting here.

A thorough explanation about Linux Desktop broadcasting is here.

Introduction to Gimp.

The following video tells you about the interface of Gimp.


This video is an introduction to use Gimp.

Introduction to R.

These videos are from Youtube. It is based on Windows system, but I think it doesn't matter so much to learn the R programming. Of course it would be the best if someone can provide some video based on Linux system.















OpenOffice tutorial.

3/1/08

C++ QUICK REFERENCE

PREPROCESSOR



// Comment to end of line
/* Multi-line comment */
#include <stdio.h> // Insert standard header file
#include "myfile.h" // Insert file in current directory
#define X some text // Replace X with some text
#define F(a,b) a+b // Replace F(1,2) with 1+2
#define X \
some text // Line continuation
#undef X // Remove definition
#if defined(X) // Condional compilation (#ifdef X)
#else // Optional (#ifndef X or #if !defined(X))
#endif // Required after #if, #ifdef


LITERALS




255, 0377, 0xff // Integers (decimal, octal, hex)
2147483647L, 0x7fffffffl // Long (32-bit) integers
123.0, 1.23e2 // double (real) numbers
'a', '\141', '\x61' // Character (literal, octal, hex)
'\n', '\\', '\'', '\"' // Newline, backslash, single quote, double quote
"string\n" // Array of characters ending with newline and \0
"hello" "world" // Concatenated strings
true, false // bool constants 1 and 0

DECLARATIONS



int x; // Declare x to be an integer (value undefined)
int x=255; // Declare and initialize x to 255
short s; long l; // Usually 16 or 32 bit integer (int may be either)
char c='a'; // Usually 8 bit character
unsigned char u=255; signed char s=-1; // char might be either
unsigned long x=0xffffffffL; // short, int, long are signed
float f; double d; // Single or double precision real (never unsigned)
bool b=true; // true or false, may also use int (1 or 0)
int a, b, c; // Multiple declarations
int a[10]; // Array of 10 ints (a[0] through a[9])
int a[]={0,1,2}; // Initialized array (or a[3]={0,1,2}; )
int a[2][3]={{1,2,3},{4,5,6}}; // Array of array of ints
char s[]="hello"; // String (6 elements including '\0')
int* p; // p is a pointer to (address of) int
char* s="hello"; // s points to unnamed array containing "hello"
void* p=NULL; // Address of untyped memory (NULL is 0)
int& r=x; // r is a reference to (alias of) int x
enum weekend {SAT,SUN}; // weekend is a type with values SAT and SUN
enum weekend day; // day is a variable of type weekend
enum weekend {SAT=0,SUN=1}; // Explicit representation as int
enum {SAT,SUN} day; // Anonymous enum
typedef String char*; // String s; means char* s;
const int c=3; // Constants must be initialized, cannot assign to
const int* p=a; // Contents of p (elements of a) are constant
int* const p=a; // p (but not contents) are constant
const int* const p=a; // Both p and its contents are constant
const int& cr=x; // cr cannot be assigned to change x

STORAGE CLASSES


int x;                    // Auto (memory exists only while in scope)
static int x; // Global lifetime even if local scope
extern int x; // Information only, declared elsewhere

STATEMENTS

x=y; // Every expression is a statement
int x;                    // Declarations are statements
; // Empty statement

{ // A block is a single statement
int x; // Scope of x is from declaration to end of block
a; // In C, declarations must precede statements
}




if (x) a; // If x is true (not 0), evaluate a
else if (y) b; // If not x and y (optional, may be repeated)
else c; // If not x and not y (optional)

while (x) a; // Repeat 0 or more times while x is true

for (x; y; z) a; // Equivalent to: x; while(y) {a; z;}

do a; while (x); // Equivalent to: a; while(x) a;

switch (x) { // x must be int
case X1: a; // If x == X1 (must be a const), jump here
case X2: b; // Else if x == X2, jump here
default: c; // Else jump here (optional)
}



break; // Jump out of while, do, or for loop, or switch
continue; // Jump to bottom of while, do, or for loop
return x; // Return x from function to caller




try { a; }
catch (T t) { b; } // If a throws a T, then jump here
catch (...) { c; } // If a throws something else, jump here

FUNCTIONS

int f(int x, int); // f is a function taking 2 ints and returning int
void f();                 // f is a procedure taking no arguments
void f(int a=0); // f() is equivalent to f(0)
f(); // Default return type is int
inline f(); // Optimize for speed
f() { statements; } // Function definition (must be global)
T operator+(T x, T y); // a+b (if type T) calls operator+(a, b)
T operator-(T x); // -a calls function operator-(a)
T operator++(int); // postfix ++ or -- (parameter ignored)
extern "C" {void f();} // f() was compiled in C
Function parameters and return values may be of any type.

A function must either be declared or defined before it is used. It may
be declared first and defined later. Every program consists of a set of
a set of global variable declarations and a set of function
definitions (possibly in separate files), one of which must be:


int main() { statements... } or
int main(int argc, char* argv[]) { statements... }

argv is an array of argc strings from the command line. By convention,
main returns status 0 if successful, 1 or higher for errors.

Functions with different parameters may have the same name

(overloading). Operators except :: . .* ?: may be overloaded. Precedence
order is not affected. New operators may not be created.


EXPRESSIONS


Operators are grouped by precedence, highest first. Unary operators and
assignment evaluate right to left. All others are left to right.
Precedence does not affect order of evaluation, which is undefined. There
are no run time checks for arrays out of bounds, invalid pointers, etc.


T::X                      // Name X defined in class T
N::X // Name X defined in namespace N
::X // Global name X

t.x // Member x of struct or class t
p->x // Member x of struct or class pointed to by p
a[i] // i'th element of array a
f(x,y) // Call to function f with arguments x and y
T(x,y) // Object of class T initialized with x and y
x++ // Add 1 to x, evaluates to original x (postfix)
x-- // Subtract 1 from x, evaluates to original x
typeid(x) // Type of x
typeid(T) // Equals typeid(x) if x is a T
dynamic_cast<T>(x) // Converts x to a T, checked at run time
static_cast<T>(x) // Converts x to a T, not checked
reinterpret_cast<T>(x) // Interpret bits of x as a T
const_cast<T>(x) // Converts x to same type T but not const

sizeof x // Number of bytes used to represent object x
sizeof(T) // Number of bytes to represent type T
++x // Add 1 to x, evaluates to new value (prefix)
--x // Subtract 1 from x, evaluates to new value
~x // Bitwise complement of x
!x // true if x is 0, else false (1 or 0 in C)
-x // Unary minus
+x // Unary plus (default)

&x // Address of x
*p // Contents of address p (*&x equals x)
new T // Address of newly allocated T object
new T(x, y) // Address of a T initialized with x, y
new T[x] // Address of allocated n-element array of T
delete p // Destroy and free object at address p
delete[] p // Destroy and free array of objects at p
(T) x // Convert x to T (obsolete, use .._cast<T>(x))

x * y // Multiply
x / y // Divide (integers round toward 0)
x % y // Modulo (result has sign of x)

x + y // Add, or &x[y]
x - y // Subtract, or number of elements from *x to *y

x << y // x shifted y bits to left (x * pow(2, y))
x >> y // x shifted y bits to right (x / pow(2, y))

x < y // Less than
x <= y // Less than or equal to
x > y // Greater than
x >= y // Greater than or equal to

x == y // Equals
x != y // Not equals

x & y // Bitwise and (3 & 6 is 2)

x ^ y // Bitwise exclusive or (3 ^ 6 is 5)

x | y // Bitwise or (3 | 6 is 7)

x && y // x and then y (evaluates y only if x (not 0))

x || y // x or else y (evaluates y only if x is false (0))

x = y // Assign y to x, returns new value of x
x += y // x = x + y, also -= *= /= <<= >>= &= |= ^=

x ? y : z // y if x is true (nonzero), else z

throw x // Throw exception, aborts if not caught

x , y // evaluates x and y, returns y (seldom used)


CLASSES

class T { // A new type
private:                  // Section accessible only to T's member functions
protected: // Also accessable to classes derived from T
public: // Accessable to all
int x; // Member data
void f(); // Member function
void g() {return;} // Inline member function
void h() const; // Does not modify any data members
int operator+(int y); // t+y means t.operator+(y)
int operator-(); // -t means t.operator-()
T(): x(1) {} // Constructor with initialization list
T(const T& t): x(t.x) {} // Copy constructor
T& operator=(const T& t) {x=t.x; return *this; } // Assignment operator
~T(); // Destructor (automatic cleanup routine)
explicit T(int a); // Allow t=T(3) but not t=3
operator int() const {return x;} // Allows int(t)
friend void i(); // Global function i() has private access
friend class U; // Members of class U have private access
static int y; // Data shared by all T objects
static void l(); // Shared code. May access y but not x
class Z {}; // Nested class T::Z
typedef int V; // T::V means int
};
void T::f() { // Code for member function f of class T
this->x = x;} // this is address of self (means x=x;)
int T::y = 2; // Initialization of static member (required)
T::l(); // Call to static member
struct T { // Equivalent to: class T { public:
virtual void f(); // May be overridden at run time by derived class
virtual void g()=0; }; // Must be overridden (pure virtual)
class U: public T {}; // Derived class U inherits all members of base T
class V: private T {}; // Inherited members of T become private
class W: public T, public U {}; // Multiple inheritance
class X: public virtual T {}; // Classes derived from X have base T directly

All classes have a default copy constructor, assignment operator, and
destructor, which perform the corresponding operations on each data member
and each base class as shown above. There is also a default no-argument
constructor (required to create arrays) if the class has no constructors.
Constructors, assignment, and destructors do not inherit.


TEMPLATES

template <class T> T f(T t); // Overload f for all types
template <class T> class X {        // Class with type parameter T
X(T t); }; // A constructor
template <class T> X<T>::X(T t) {} // Definition of constructor
X<int> x(3); // An object of type "X of int"
template <class T, class U=T, int n=0> // Template with default parameters


NAMESPACES


namespace N {class T {};} // Hide name T
N::T t; // Use name T in namespace N
using namespace N; // Make T visible without N::

C/C++ STANDARD LIBRARY


Only the most commonly used functions are listed. Header files without
.h are in namespace std. File names are actually lower case.


STDIO.H, CSTDIO (Input/output)


FILE* f=fopen("filename", "r"); // Open for reading, NULL (0) if error
 // Mode may also be "w" (write) "a" append, "a+" update, "rb" binary
fclose(f); // Close file f
fprintf(f, "x=%d", 3); // Print "x=3" Other conversions:
"%5d %u %-8ld" // int width 5, unsigned int, long left just.
"%o %x %X %lx" // octal, hex, HEX, long hex
"%f %5.1f" // float or double: 123.000000, 123.0
"%e %g" // 1.23e2, use either f or g
"%c %s" // char, char*
"%%" // %
sprintf(s, "x=%d", 3); // Print to array of char s
printf("x=%d”, 3); // Print to stdout (screen unless redirected)
fprintf(stderr, ... // Print to standard error (not redirected)
getc(f); // Read one char (as an int) or EOF from f
ungetc(c, f); // Put back one c to f
getchar(); // getc(stdin);
putc(c, f) // fprintf(f, "%c", c);
putchar(c); // putc(c, stdout);
fgets(s, n, f); // Read line into char s[n] from f. NULL if EOF
gets(s) // fgets(s, INT_MAX, f); no bounds check
fread(s, n, 1, f); // Read n bytes from f to s, return number read
fwrite(s, n, 1, f); // Write n bytes of s to f, return number written
fflush(f); // Force buffered writes to f
fseek(f, n, SEEK_SET); // Position binary file f at n
ftell(f); // Position in f, -1L if error
rewind(f); // fseek(f, 0L, SEEK_SET); clearerr(f);
feof(f); // Is f at end of file?
ferror(f); // Error in f?
perror(s); // Print char* s and error message
clearerr(f); // Clear error code for f
remove("filename"); // Delete file, return 0 if OK
rename("old", "new"); // Rename file, return 0 if OK
f = tmpfile(); // Create temporary file in mode "wb+"
tmpnam(s); // Put a unique file name in char s[L_tmpnam]

STDLIB.H, CSTDLIB (Misc. functions)


atof(s); atol(s); atoi(s);// Convert char* s to float, long, int
rand(), srand(seed);      // Random int 0 to RAND_MAX, reset rand()
void* p = malloc(n); // Allocate n bytes. Obsolete: use new
free(p); // Free memory. Obsolete: use delete
exit(n); // Kill program, return status n
system(s); // Execute OS command s (system dependent)
getenv("PATH"); // Environment variable or 0 (system dependent)
abs(n); labs(ln); // Absolute value as int, long

STRING.H, CSTRING (Character array handling functions)


Strings are type char[] with a '\0' in the last element used.

strcpy(dst, src);         // Copy string. Not bounds checked
strcat(dst, src); // Concatenate to dst. Not bounds checked
strcmp(s1, s2); // Compare, <0 if s1<s2, 0 if s1==s2, >0 if s1>s2
strncpy(dst, src, n); // Copy up to n chars, also strncat(), strncmp()
strlen(s); // Length of s not counting \0
strchr(s,c); strrchr(s,c);// Address of first/last char c in s or 0
strstr(s, sub); // Address of first substring in s or 0
// mem... functions are for any pointer types (void*), length n bytes
memmove(dst, src, n); // Copy n bytes from src to dst
memcmp(s1, s2, n); // Compare n bytes as in strcmp
memchr(s, c, n); // Find first byte c in s, return address or 0
memset(s, c, n); // Set n bytes of s to c

CTYPE.H, CCTYPE (Character types)



isalnum(c); // Is c a letter or digit?
isalpha(c); isdigit(c); // Is c a letter? Digit?
islower(c); isupper(c); // Is c lower case? Upper case?
tolower(c); toupper(c); // Convert c to lower/upper case


MATH.H, CMATH (Floating point math)


sin(x); cos(x); tan(x); // Trig functions, x (double) is in radians
asin(x); acos(x); atan(x);// Inverses
atan2(y, x); // atan(y/x)
sinh(x); cosh(x); tanh(x);// Hyperbolic
exp(x); log(x); log10(x); // e to the x, log base e, log base 10
pow(x, y); sqrt(x); // x to the y, square root
ceil(x); floor(x); // Round up or down (as a double)
fabs(x); fmod(x, y); // Absolute value, x mod y


TIME.H, CTIME (Clock)

clock()/CLOCKS_PER_SEC; // Time in seconds since program started
time_t t=time(0);         // Absolute time in seconds or -1 if unknown
tm* p=gmtime(&t); // 0 if UCT unavailable, else p->tm_X where X is:
sec, min, hour, mday, mon (0-11), year (-1900), wday, yday, isdst
asctime(p); // "Day Mon dd hh:mm:ss yyyy\n"
asctime(localtime(&t)); // Same format, local time


ASSERT.H, CASSERT (Debugging aid)

assert(e); // If e is false, print message and abort
#define NDEBUG            // (before #include <assert.h>), turn off assert


NEW.H, NEW (Out of memory handler)

set_new_handler(handler); // Change behavior when out of memory
void handler(void) {throw bad_alloc();}  // Default

IOSTREAM.H, IOSTREAM (Replaces stdio.h)

cin >> x >> y; // Read words x and y (any type) from stdin
cout << "x=" << 3 << endl; // Write line to stdout
cerr << x << y << flush; // Write to stderr and flush
c = cin.get(); // c = getchar();
cin.get(c); // Read char
cin.getline(s, n, '\n'); // Read line into char s[n] to '\n' (default)
if (cin) // Good state (not EOF)?
// To read/write any type T:
istream& operator>>(istream& i, T& x) {i >> ...; x=...; return i;}
ostream& operator<<(ostream& o, const T& x) {return o << ...;}



FSTREAM.H, FSTREAM (File I/O works like cin, cout as above)

ifstream f1("filename"); // Open text file for reading
if (f1)                   // Test if open and input available
f1 >> x; // Read object from file
f1.get(s); // Read char or line
f1.getline(s, n); // Read line into string s[n]
ofstream f2("filename"); // Open file for writing
if (f2) f2 << x; // Write to file


IOMANIP.H, IOMANIP (Output formatting)

cout << setw(6) << setprecision(2) << setfill('0') << 3.1; // print "003.10"


STRING (Variable sized character array)

string s1, s2="hello"; // Create strings
s1.size(), s2.size();     // Number of characters: 0, 5
s1 += s2 + ' ' + "world"; // Concatenation
s1 == "hello world" // Comparison, also <, >, !=, etc.
s1[0]; // 'h'
s1.substr(m, n); // Substring of size n starting at s1[m]
s1.c_str(); // Convert to const char*
getline(cin, s); // Read line ending in '\n'


VECTOR (Variable sized array/stack with built in memory allocation)

vector<int> a(10); // a[0]..a[9] are int (default size is 0)
a.size();                 // Number of elements (10)
a.push_back(3); // Increase size to 11, a[10]=3
a.back()=4; // a[10]=4;
a.pop_back(); // Decrease size by 1
a.front(); // a[0];
a[20]=1; // Crash: not bounds checked
a.at(20)=1; // Like a[20] but throws out_of_range()
for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p)
*p=0; // Set all elements of a to 0
vector<int> b(a.begin(), a.end()); // b is copy of a
vector<T> c(n, x); // c[0]..c[n-1] init to x
T d[10]; vector<T> e(d, d+10); // e is initialized from d

DEQUE (array/stack/queue)

deque<T> is like vector<T>, but also supports:

a.push_front(x); // Puts x at a[0], shifts elements toward back
a.pop_front(); // Removes a[0], shifts toward front


UTILITY (Pair)

pair<string, int> a("hello", 3); // A 2-element struct
a.first;                  // "hello"
a.second; // 3


MAP (associative array)

map<string, int> a; // Map from string to int
a["hello"]=3;             // Add or replace element a["hello"]
for (map<string, int>::iterator p=a.begin(); p!=a.end(); ++p)
cout << (*p).first << (*p).second; // Prints hello, 3
a.size(); // 1

ALGORITHM (A collection of 60 algorithms on sequences with iterators)

min(x, y); max(x, y); // Smaller/larger of x, y (any type defining <)
swap(x, y);               // Exchange values of variables x and y
sort(a, a+n); // Sort array a[0]..a[n-1] by <
sort(a.begin(), a.end()); // Sort vector or deque
by Matt Mahoney, mmahoney@cs.fit.edu