Monday, June 28, 2010

How to run Control Panel tools by typing a command

This article describes how to run Control Panel tools in Windows by typing a command at a command prompt or in the Open box.
To run a Control Panel tool in Windows, type the appropriate command in the Open box or at a command prompt.

NOTE: If you want to run a command from a command prompt, you must do so from the Windows folder. Also, note that your computer may not have all of the tools listed in this article, as your Windows installation may not include all of these components.

Control panel tool Command
-----------------------------------------------------------------
Accessibility Options control access.cpl
Add New Hardware control sysdm.cpl add new hardware
Add/Remove Programs control appwiz.cpl
Date/Time Properties control timedate.cpl
Display Properties control desk.cpl
FindFast control findfast.cpl
Fonts Folder control fonts
Internet Properties control inetcpl.cpl
Joystick Properties control joy.cpl
Keyboard Properties control main.cpl keyboard
Microsoft Exchange control mlcfg32.cpl
(or Windows Messaging)
Microsoft Mail Post Office control wgpocpl.cpl
Modem Properties control modem.cpl
Mouse Properties control main.cpl
Multimedia Properties control mmsys.cpl
Network Properties control netcpl.cpl
NOTE: In Windows NT 4.0, Network
properties is Ncpa.cpl, not Netcpl.cpl
Password Properties control password.cpl
PC Card control main.cpl pc card (PCMCIA)
Power Management (Windows 95) control main.cpl power
Power Management (Windows 98) control powercfg.cpl
Printers Folder control printers
Regional Settings control intl.cpl
Scanners and Cameras control sticpl.cpl
Sound Properties control mmsys.cpl sounds
System Properties control sysdm.cpl


NOTE: The Scanners and Cameras applet (sticpl.cpl) cannot be run in Windows Millennium. It has been replaced by the Scanners and Cameras Folder, which is similar in function to folders like Printers and Dial-up Networking.

Windows substitutes the name of the tool you want to run for %1%. For example:
"rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl".
To run the Users tool in Control Panel, type control Ncpa.cpl users, and then press ENTER.

To run the Users tool for Windows 95/98/Me, type "control inetcpl.cpl users" (without the quotation marks) and then press ENTER.

How to use System Information (MSINFO32) command-line tool switches

MSINFO32 displays a comprehensive view of your hardware, system components, and software environment. This article contains an overview of the available switches that can be used with the MSINFO32 command in Windows 7, in Windows Vista, and in Windows XP.

You can use the MSINFO32 command-line tool switches to do all of the following:

* Use System Information from a batch file
* Create .nfo or .txt files that contain information from specified categories.
* Open System Information and display only specific categories.
* Save a file silently (without opening System Information).
* Start System Information connected to a remote computer.
* Create a shortcut that opens System Information in a frequently-used configuration.

Note Some command-line switches available for Windows XP are no longer supported in Windows Vista or in Windows 7.

Use the following syntax to run the MSINFO32 command on computers that are running Windows 7, Windows Vista, and Windows XP:
Msinfo32 [/?] [/pch] [/nfo Path] [/report Path] [/computer ComputerName] [/showcategories] [/category categoryID] [/categories categoryID]


Parameters
Path
Specifies the file to be opened in the format C:\folder1\file1.xxx where C is the drive letter, folder1 is the folder, file1 is the file and xxx is the file name extension.

ComputerName
This can be a Universal Naming Convention name, an IP address, or a Fully Qualified Domain Name.

categoryID
This parameter is obtained by using the /showcategories switch.


Command options that are supported in Windows 7, Windows Vista and Windows XP
/nfo {Path}
Saves the exported file as an .nfo file. If the file name that is specified in Path does not end in .nfo, an .nfo file name extension will be appended to the file name.

/report {Path}
Saves the file that is specified in Path in the .txt format. The file name will be saved exactly as it appears in path. The .txt file name extension will not be appended to the file unless it is specified in Path.

/computer {ComputerName}
Starts System Information for the specified remote computer.
Note When you connect to a remote computer, you must have appropriate permissions to access WMI on the remote computer.
Back to the top
Command options that are supported in Windows XP
/pch
Displays the history view.


/showcategories
Starts System Information with the category IDs displayed instead of the friendly names or the localized names. For example, when you use this switch, the Software Environment category is displayed as the SWEnv category. SWEnv is a valid categoryID argument for the /category switch and the /categories switch.

/category {categoryID}
Starts System Information with the specified category selected. Use /showcategories to display a list of available category IDs.

/categories {+categoryID(+categoryID)|+all(-categoryID)}
Starts System Information with only the specified category or categories displayed. It also limits the output to the selected category or categories. Use /showcategories to display a list of available category IDs.

/? Displays a brief summary of MSInfo32 command-line options.

Note Some System Information categories contain large amounts of data. You can use the start /wait command to optimize reporting performance for these categories. For more information, see Related Topics.

Examples
To open System Information in History view, type:
msinfo32 /pch

To create an .nfo file in the folder C:\Temp with a name of Test.nfo, type:
msinfo32 /nfo C:\TEMP\TEST.NFO

To create a .txt file in the folder C:\Temp with a name of Test.txt, type:
msinfo32 /report C:\TEMP\TEST.NFO

To view System Information from a remote computer with a UNC name of BIGSERVER, type:
msinfo32 /computer BIGSERVER

To list the available category IDs, type:
msinfo32 /showcategories

To start System Information with all available information displayed, except Loaded Modules, type:
msinfo32 /categories +all -loadedmodules

To create an .nfo file called SYSSUM.NFO in the C:\Temp folder that contains information in the System Summary category, type:
msinfo32 /nfo C:\TEMP\SYSSUM.NFO /categories +systemsummary

To create a .NFO file called CONFLICTS.NFO in the C:\TEMP folder that contains information about resource conflicts, type:
msinfo32 /nfo C:\TEMP\CONFLICTS.NFO /categories +componentsproblemdevices+resourcesconflicts+resourcesforcedhardware


Thanks to:
http://support.microsoft.com/kb/300887

Thursday, June 24, 2010

Top 10 reasons to learn Wireshark, the open source network analyzer

1. Wireshark is the de facto standard in network analyzer tools. With more than 500,000 downloads a month, the IT industry has embraced Wireshark as the go-to tool for network troubleshooting, optimization and security! Be at the front of the IT pack and show your true colors as a geek leader.

2. Set yourself apart as a network analyst. It's one thing to be able to configure a TCP/IP network; it's entirely different to understand the inner workings of that network. Consider yourself a true "doctor of networking" with the ability to peer into the communications to pinpoint the cause of problems quickly and accurately. Be prepared for house-call requests. IT professionals are the new "doctor in the family," as you probably already know.

3. Bond with the only source of networking truth -- the packets. The packets never lie. Users do. Salespeople do. Consultants do. You know the drill. You can live in a pure environment of "truth" when you simply watch the hosts communicate with each other and see which one totally messes up the process. (Insert calming relaxation and meditation music here.)

4. Entertain yourself -- network traffic is never boring. From analyzing the yappy traffic from your hyperactive iPhone to the itty bitty stinkin' packets seen during a database operation, there's a lot of hidden "personality" on your network. Take advantage of the fact that it's legal in every country to profile protocols and products. Witness the overbearing protectiveness of network firewalls. Marvel at the blatantly callous disregard that lousy applications have for our precious standards. This is better than Avatar (and your nose won't hurt from those 3D glasses).

5. Find problems before the users do. You can become an IT superstar by identifying problems before the users make those whimpering or demanding calls blaming everything from their PCs to the Internet itself. Proactive analysis can decrease your stress levels in the long run, enabling you to live longer and enjoy your retirement on that small secluded cove by your new beach house.

6. Wireshark is free. Wireshark is considered one of the top open source projects in the world. It costs you nothing to download it from wireshark.org, install it and start your network trace file collection today. This is much better than collecting Star Wars or Star Trek memorabilia (and better for your social life).

7. Get geeky. IT professionals have a deep-seated desire to be geeky -- look at the popularity of the slingshot monkey, for example. Non-IT folks really don't hyperventilate at the chance to win one of those monkeys at a trade show. Heck, they don't even understand the "I will wait in line 10 hours for anything Apple releases" mentality either. (Hmmm… then again, neither do I.) Wireshark lets you see packets in their dissected form or even in hex form (for a special treat on the weekends!).

8. Solve ever-changing puzzles. Extreme Sudoku can be humbling and you've already hit level 80 in World of Warcraft (or higher, with the upcoming expansion pack). Try something new. Try to analyze each packet involved in your login process. It can be solved, and there's a pay-off. You can identify login problems that may occur in the future after you learn the purpose of each packet. Become a modern-day Rubik's-cube-solving kind of freak and impress everyone at the bar (or in that line at the Apple store).

9. Know what's really happening on your network (at home or work). When your kids say they're doing research for homework you can easily sniff the traffic and see which sites they are hitting. Clear text chat traffic offers wonderful parental insight. Don't tell 'em how you know this information -- it's all part of the "eyes in the back of my head" mystery of über-parenting. (Consider blocking their access to wireshark.org to protect your magical mojo.)

10. You don't want to flip burgers for a living. Yup -- learning Wireshark is definitely a big step up from flipping burgers at the local grease pit. You'll run faster, jump higher and even begin counting in binary just for fun. ("OK, little Jimmy… I said stop that… I'm counting… 1…. 0! Time's up!" Hee hee.)

It's never too late to learn network analysis and the true inner workings of your network. Pull up a chair, pour a cup of hot java and settle in for a nice self-improvement session with Wireshark and the Wireshark Network Analysis Book. Together they are the best girlfriends/boyfriends/wives/husbands/lovers/dogs/cats/power tools you've ever had! Enjoy!

Get Wireshark

The current stable release of Wireshark is 1.2.9. It supersedes all previous releases, including all releases of Ethereal. You can also download the latest development release (1.4.0rc1) and documentation.

http://www.wireshark.org/download.html

Thanks to :
http://searchnetworking.techtarget.com/generic/0,295582,sid7_gci1511671,00.html

Saturday, June 12, 2010

How to Format a USB Flash Drive in Ubuntu

USB (Universal Serial Bus) flash drives are rewritable storage devices designed to be portable and easy to use. Flash drives are typically formatted by default with Windows file formats like FAT16/32. Since Ubuntu Linux users tend to prefer native Linux file formats like RiserFS or Ext 2/3, formatting the drive before storing data on it is a good idea. Follow these steps to format a USB flash drive in Ubuntu.

  1. Step 1

    Plug your flash drive into an empty USB port, then back up any data on the drive. Open the main menu, move your cursor over "Accessories" and then click on "Terminal." At the terminal prompt, type "sudo apt-get install gparted" (without quotes); then, hit the "Enter" key on your keyboard.

  2. Step 2

    Enter your Ubuntu administrator password when prompted; then hit the "Enter" key again. This will download and install GParted which is an open source drive partitioning program.

  3. Step 3

    Go to the Ubuntu main menu after the installation is complete, move your cursor over "System," then "Administration" and then click on "Partition Editor." Enter your administrator password when prompted; then click "OK."

  4. Step 4

    Click on "GParted" in the toolbar. Then, hover over "Devices" and select your USB flash drive from the list (dev/sdb1, for example). Right-click on the device in the main GParted window; then click "Unmount." It may take a few minutes for the device to be unmounted.

  5. Step 5

    Right-click on the device again (after it is unmounted) and then hover over "Format to." Select the desired file system type (RiserFS, linux-swap, Ext 2/3 or FAT16/32, for example); then click "Apply" in the toolbar. Depending on the size of the flash drive, it will take three to four minutes or so for GParted to complete the process.

  6. Step 6

    Close GParted after the flash drive is formatted. To mount your USB flash drive, unplug it and then plug it back in. The drive is now ready to store data in the file format you selected.

Thanks to :
http://www.ehow.com/how_4963426_format-usb-flash-drive-ubuntu.html

How to Export and Save Your Bookmarks From Firefox

The bookmarks on your computer are easily exported and saved from Firefox so that you can back up, share or use them on another computer. You can do it in a few easy steps.

Instructions
  1. Step 1

    Open up a Firefox window.

  2. Step 2

    Click on the "Bookmarks" menu and select "Manage Bookmarks..." In case of Firefox 3.6.2 select "Organize Bookmarks..."

  3. Step 3

    Click on the "File" menu and select "Export" in the window that pops up. In case of Firefox 3.6.2, click on "Import and Backup." Select "Export HTML." A save option will appear.

  4. Step 4

    Give your bookmarks whatever title you like and choose a location to save them in the save window that comes up.

  5. Step 5

    Open this file on any computer with a Web browser and click on the links to go to each bookmark, now that your bookmarks are saved as an HTML file. You can also import them into the bookmarks or favorites menu of another computer.

Thanks to :
http://www.ehow.com/how_1000389_export-save-bookmarksexport-save-bookmarksexport-save-bookmarksexport-save-bookmarks.html

Thursday, June 10, 2010

Iptux - An intranet communication tool for Linux

iptux is an IP Messenger client for Linux.

It supports both linux and Windows

It support:

 - auto detect other clients in the intranet.
- send message to other clients.
- send file to other clients.
If you need to install it
Just update your apt in your system and then type in terminal as follows
sudo apt-get install iptux
it will get automatically installed.

Or else if you want the source of it get it from the following.

http://packages.ubuntu.com/jaunty/iptux

Tuesday, June 8, 2010

Debian's APT - Top Package Management

APT

APT (Advanced Packaging Tool) is a high-level package management tool used in Debian-based Linux distributions. In this article we review APT in detail.


Introduction

Debians distribution base of the package management process is called dpkg, which stands for Debian PacKaGe. Debian-native applications have the .deb extension and dpkg is used to install, remove and provide information to the deb packages on a Debian-based system. In this manner, dpkg is a low-level utility.

Thus, with the advancement of software distribution processes through on-line repositories, together with complex dependency resolution process requirements, a higher-level tool was needed. One which could deal with downloading the packages from remote locations (on-line repositories) and be user friendly. At this point, the Debian community came up with apt, the abbreviation of Advanced Packaging Tool.
apt

apt is not a single program, but rather the name of the package that contains the necessary set of tools to enable the user to download packages from a repository and install them. With these tools, you can apt-get install application_name to download packages and install from the Internet, you can apt-get update to update the packages on your system, apt-get distro-upgrade to upgrade your distribution to the new release, apt-cache search package_name to search for a specific package in the repositories or apt-get remove package_name to remove a specific package etc.

When you want to install an application with the command apt-get install application_name, you very basically trigger the following events:

  • * Make apt search for the package in the repository,
  • * If the package is found, check if it is already installed,
  • * If not, check the dependencies,
  • * Check if any, some, or all of the dependencies are already installed,
  • * If not, download the missing dependencies in the order that they will be installed by considering their own set of dependencies,
  • * Invoke dpkg in such a way that the dependencies are installed first and the application last.

apt Files and Folders

apt uses many files and folders during operation. The main files and folders are as follows:

* /etc/apt/sources.list: The file that contains the path (and URL) of the repositories,
* /etc/apt/sources.list.d: The folder that contains the files, which contain paths (and URLs) of additional repositories,
* /etc/apt/apt.conf or /etc/apt/apt-file.conf: The file that contains the apt configuration,
* /etc/apt/apt.conf.d: The folder that contains additional apt configuration,
* /etc/apt/preferences: The file that contains apt preferences,
* /var/cache/apt/archives: The folder that contains the files apt has downloaded,
* /var/cache/apt/apt-file: The folder that contains the files which maps each file available in the Ubuntu Linux system to the package from which it originates,
* /var/lib/apt/lists: The folder that contains the state information for each package resource specified in the sources.list file,
* /var/lib/apt/keyring: The folder that holds the GPG keyrings,
* /var/lib/apt/periodic: The folder that holds the “update” and “update successful” stamp files.

apt Front-Ends

As you would expect, there are graphical front ends to apt, saving you from typing and issuing commands. These graphical front ends make the users' lives easier by presenting detailed information about the packages. Here is a list of well-known apt graphical user interfaces:

  • * Aptitude: This is a curses-based front end to apt.
  • * Synaptic: The most famous Gnome front end to apt, shows packages in groups, lets the user search for packages and can download screenshots.
  • * Adept: The add/remove package application. It presents the packages in groups and lets the user see the community popularity of the applications.
  • * Kpackage: A KDE front-end to apt. It is very similar to Synaptic with a slightly different view.

Conclusion

apt is one of the most powerful (in my personal opinion THE most powerful) package manager in the Linux world. Although I have never seen an analysis on this, the power of the package management is perhaps the reason why Debian is the distribution that has so many derivatives compared to other Linux distributions. Behind the scenes there are very strict rules for packaging and very strict rules to accept packages to the repositories. The package manager works on top of these rules and does a fantastic job. It's been three years and I haven't seen a broken package or an unresolved dependency.

Thanks to:
http://www.brighthub.com/computing/linux/articles/52300.aspx

Understanding Package Management


Introduction

Ian Murdock, the Debian distribution's founder, describes package management as the single biggest advancement Linux has brought to the industry. To understand package management, we have to understand how software is developed, installed and updated, why package managers are needed and how they fit into the software scene.

Dependency Hell

When software is developed, it is designed to take advantage of other components that are already available. We can use an analogy to build a house - if you own a piece of land and want to build a house, would you first build the factories that produce bricks, windows, doors, glasses, carpets, etc. or would you purchase them from the market? This is the same in building software. Suppose that you are writing a download manager. Rather than writing the download code totally from scratch, you can use the graphical components, dialogs, buttons that have been written in advance and focus yourself on the downloading process, just as you would focus on your house's design rather than producing bricks.

Software works the same way. Developers do not need to reinvent the wheel every time they write a program. For example, what if program A depends on components X, Y, Z to run while component X depends on components U and V, component Y depends on components S and T to run, and component U depends on component T to run? The following diagram shows how the components would depend on one another.




o install program A properly, you have to install T first, then U and V, then S, then X, Y and Z and finally A. This is the only way that each component's dependencies would be satisfied. Unless this is the case, the program will produce an error and will not be installed correctly. This is what causes "dependency hell". Don't think dependency hell is a Linux-only concept: it is called “Dependency Hell” in the Linux/UNIX world, “DLL Hell” in the Windows world and “Jar Hell” in the Java World.
Package Management

Wouldn't it be nice if there was a process or program that would allow you to select which program you want to install and then automate the dependency resolution? This is what package management is--a tool to resolve dependencies, install them, install the program, configure and update it. You search for the software, click to install and then let the package manager do the rest. Once you get used to it, a package manager an indispensable piece of software that lets you manage all the applications on your computer, including the operating system.

The packages, their dependencies and other related information are hosted on servers on the Internet, called repositories (or repos for short). For the sake of simplicity, you can think a repository as a pool of programs that can be reached and downloaded by a specific package manager.
Package Manager's Jobs

As we have seen in the previous section, the package manager resolves dependencies and installs the program without any interception from the user. This is not the only thing a package manager does. It also performs the following jobs behind the scenes:

* Verify the file integrity to ensure that the downloaded package is not corrupt and is complete
* Verify the package signature to ensure that it is downloaded from a trusted repository
* Use file archivers to open the downloaded files
* Upgrade software packages from the repositories
* Group packages and present to the user in a simple, structured way (such as Games, Productivity Applications, Internet Applications, etc.)
* Resolve dependencies and make sure that the program the user requests is installed with all dependencies satisfied and in correct working state.

Main distributions have their own package managers, which we will analyze in the oncoming articles (for a quick introduction to installing and uninstalling applications in Linux, you can check our Using Applications in Linux article).

Conclusion

As we have stated in the beginning, package management, one of the biggest advancements in the computer industry, is an excellent way to manage software. Windows, unfortunately, has no way of a central software management except the updates. However, it is your duty as a user to watch for the updates if the program does not inform you about the updates automatically. Even if you are notified, you have to go to the manufacturer's website, download the updated program and install it. In Linux world, you just press “Install updates” when you are informed that there are updates available for your system.

Thanks to :
http://www.brighthub.com/computing/linux/articles/52282.aspx

Running QTP tests using Python

Running QTP tests using Python

QTP provides an interface called the automation object model. This model is essentially a COM interface providing a bunch of objects that can be used to automate QTP. The full object list is available in the QuickTest Professional Automation documentation.

Running QTP tests from the command line is useful for doing scheduled automatic testing. If you use a continuous integration system to do automatic builds of your software, you can run your QTP tests on the latest build.

The following is a Python script that is able to run a test and print out Passed or Failed. It is a direct port of example code in the documentation written in VBScript

-------------------------------
  • import win32com, win32com.client
  • qtp = win32com.client.Dispatch("QuickTest.Application")
  • # starts up QTP
  • qtp.Launch()
  • # make the QTP window visible
  • qtp.Visible = True
  • # Open a test, replace the path
  • qtp.Open("C:\Tests\test1")
  • # to open a QTP test in Quality Center
  • # qtp.Open(r"[QualityCenter] Subject\FolderName\QTPScript")
  • # create a RunResultsOptions object
  • qtResultsOpt = win32com.client.Dispatch("QuickTest.RunResultsOptions")
  • # set the location to where the results will be save
  • qtResultsOpt.ResultsLocation = "C:\Test\test1\res"
  • qtp.Test.Run(qtResultsOpt)
  • print "Test has %s" %qtp.Test.LastRunResults.Status
  • # close the Test
  • qtp.Test.Close()
  • # quit QTP
  • qtp.Quit()
---------------------------

Thanks to :
http://bulkan-evcimen.com/running_qtp_test_using_python/

Tuesday, June 1, 2010

Internet Slang Words and Computer Slang

On this site you will find a list of slang terms, acronyms and abbreviations as used in websites, ICQ chat rooms, blogs, SMS, and Internet forums - a complete dictionary of slang.
There are many such internet slang words in use, some are more widely understood than others, and new ones are evolving all the time. This list is large but inevitably incomplete; however it contains the more commonly used slang words and slang terms. 4834 acronyms are listed at present - if you know of another that should be here then please add an acronym.
Note that a few of the internet abbreviations stand for phrases containing words that may be offensive to some people. In those cases we have substituted asterisks, or similar, for the internet slang words in question.
For eg :
LOL Laughing Out Loud



Thanks to :
http://www.internetslang.com/

Monday, May 17, 2010

Cron

Cron is a time-based job scheduler in Unix-like computer operating systems. The name cron comes from the word "chronos", Greek for "time". Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration, though its general-purpose nature means that it can be used for other purposes, such as connecting to the Internet and downloading email.[1]


Overview

Cron is driven by a crontab, a configuration file that specifies shell commands to run periodically on a given schedule. The crontab files are stored where the lists of jobs and other instructions to the cron daemon are kept. Users can have their own individual crontab files and often there is a systemwide crontab file (usually in /etc or a subdirectory of /etc) which only system administrators can edit.

Each line of a crontab file represents a job and is composed of a CRON expression, followed by a shell command to execute. Some implementations of cron, such as that in the popular 4th BSD edition written by Paul Vixie and included in many Linux distributions, add a username specification into the format as the sixth field, as whom the specified job will be run (subject to user existence in /etc/passwd and allowed permissions). This is only allowed in the system crontabs (/etc/crontab and /etc/cron.d/*), not in others which are each assigned to a single user to configure.

For "day of the week" (field 5), both 0 and 7 are considered Sunday, though some versions of Unix such as AIX do not list "7" as acceptable in the man page. While normally the job is executed when the time/date specification fields all match the current time and date, there is one exception: if both "day of month" and "day of week" are restricted (not "*"), then either the "day of month" field (3) or the "day of week" field (5) must match the current day.
[edit] Examples

The following will clear the Apache error log at one minute past midnight (00:01 of every day of the month, of every day of the week).


1 0 * * * echo -n "" > /www/apache/logs/error_log

The following will run the script /home/user/test.pl every 5 minutes.

*/5 * * * * /home/user/test.pl

.---------------- minute (0 - 59)
| .------------- hour (0 - 23)
| | .---------- day of month (1 - 31)
| | | .------- month (1 - 12) OR jan,feb,mar,apr ...
| | | | .---- day of week (0 - 7) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | |
* * * * * command to be executed

Predefined scheduling definitions

There are several special predefined values which can be used to substitute the CRON expression.
Entry Description Equivalent To

@yearly Run once a year 0 0 1 1 *

@annually (same as @yearly) 0 0 1 1 *

@monthly Run once a month 0 0 1 * *

@weekly Run once a week 0 0 * * 0

@daily Run once a day 0 0 * * *

@midnight (same as @daily) 0 0 * * *

@hourly Run once an hour 0 * * * *

Saturday, May 15, 2010

Data structure alignment

Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

For example, when the computer's word size is 4 bytes, the data to be read should be at a memory offset which is some multiple of 4. When this is not the case, e.g. the data starts at the 14th byte instead of the 16th byte, then the computer has to read two 4-byte chunks and do some calculation before the requested data has been read, or it may generate an alignment fault. Even though the previous data structure ends at the 14th byte, the next data structure should start at the 16th byte. Two padding bytes are inserted between the two data structures to align the next data structure to the 16th byte

Typical alignment of C structs on x86

Data structure members are stored sequentially in a memory so that in the structure below the member Data1 will always precede Data2 and Data2 will always precede Data3:

struct MyData
{
short Data1;
short Data2;
short Data3;
};

If the type "short" is stored in two bytes of memory then each member of the data structure depicted above would be 2-byte aligned. Data1 would be at offset 0, Data2 at offset 2 and Data3 at offset 4. The size of this structure would be 6 bytes.

The type of each member of the structure usually has a default alignment, meaning that it will, unless otherwise requested by the programmer, be aligned on a pre-determined boundary. The following typical alignments are valid for compilers from Microsoft, Borland, and GNU when compiling for 32-bit x86:

* A char (one byte) will be 1-byte aligned.
* A short (two bytes) will be 2-byte aligned.
* An int (four bytes) will be 4-byte aligned.
* A float (four bytes) will be 4-byte aligned.
* A double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux.
* A long double (twelve bytes) will be 4-byte aligned on Linux.
* Any pointer (four bytes) will be 4-byte aligned on Linux. (e.g.: char*, int*)

The only notable difference in alignment for a 64-bit Linux system when compared to a 32 bit is:

* A double (eight bytes) will be 8-byte aligned.
* A long double (Sixteen bytes) will be 16-byte aligned.
* Any pointer (eight bytes) will be 8-byte aligned.

Here is a structure with members of various types, totaling 8 bytes before compilation:

struct MixedData
{
char Data1;
short Data2;
int Data3;
char Data4;
};

After compilation the data structure will be supplemented with padding bytes to ensure a proper alignment for each of its members:

struct MixedData /* after compilation */
{
char Data1;
char Padding1[1]; /* For the following 'short' to be aligned on a 2 byte boundary */
short Data2;
int Data3;
char Data4;
char Padding2[3];
};

The compiled size of the structure is now 12 bytes. It is important to note that the last member is padded with the number of bytes required to conform to the largest type of the structure. In this case 3 bytes are added to the last member to pad the structure to the size of a long word.

It is possible to change the alignment of structures to reduce the memory they require (or to conform to an existing format) by reordering structure members or changing the compiler’s alignment (or “packing”) of structure members.

struct MixedData /* after reordering */
{
char Data1;
char Data4; /* reordered */
short Data2;
int Data3;
};

The compiled size of the structure now matches the pre-compiled size of 8 bytes. Note that Padding1[1] has been replaced (and thus eliminated) by Data4 and Padding2[3] is no longer necessary as the structure is already aligned to the size of a long word.

The alternative method of enforcing the MixedData structure to be aligned to a one byte boundary will cause the pre-processor to discard the pre-determined alignment of the structure members and thus no padding bytes would be inserted.

Thanks to wikipedia:
http://en.wikipedia.org/wiki/Data_structure_alignment

Thursday, May 13, 2010

Missing .emacs file

Missing emacs init file

you can't find your .emacs file anywhere in your system. You've already looked in you home directory and it's nowhere to be found. Could somebody help me out?

So the solution is here.

There are two main versions of emacs - emacs and Xemacs and I don't think that either of them creates a .emacs file automatically - you have to create your own.

So what do you put in your .emacs? There are lots of examples of .emacs's that you can google for on the net, but here's one to start you off...
http://www.dotemacs.de/dotfiles/sample.emacs.html
...just save it to .emacs in your home directory.

If you have Xemacs installed, they don't use a file called .emacs but create a directory called .xemacs. Inside that directory you create a file called custom.el and that functions as your .emacs.

location of .emacs file :
/home/yourname/.emacs

eg: /home/siva/.emacs

Then add according to your need of your choice in emacs and save the file

sample .emacs file

;; -*- Mode: Emacs-Lisp -*-

;;; This is a sample .emacs file.
;;;
;;; The .emacs file, which should reside in your home directory, allows you to
;;; customize the behavior of Emacs. In general, changes to your .emacs file
;;; will not take effect until the next time you start up Emacs. You can load
;;; it explicitly with `M-x load-file RET ~/.emacs RET'.
;;;
;;; There is a great deal of documentation on customization in the Emacs
;;; manual. You can read this manual with the online Info browser: type
;;; `C-h i' or select "Emacs Info" from the "Help" menu.


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Basic Customization ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Enable the command `narrow-to-region' ("C-x n n"), a useful
;; command, but possibly confusing to a new user, so it's disabled by
;; default.
(put 'narrow-to-region 'disabled nil)

;;; Define a variable to indicate whether we're running XEmacs/Lucid Emacs.
;;; (You do not have to defvar a global variable before using it --
;;; you can just call `setq' directly like we do for `emacs-major-version'
;;; below. It's clearer this way, though.)

(defvar running-xemacs (string-match "XEmacs\\|Lucid" emacs-version))

;; Make the sequence "C-x w" execute the `what-line' command,
;; which prints the current line number in the echo area.
(global-set-key "\C-xw" 'what-line)

;; set up the function keys to do common tasks to reduce Emacs pinky
;; and such.

;; Make F1 invoke help
(global-set-key [f1] 'help-command)
;; Make F2 be `undo'
(global-set-key [f2] 'undo)
;; Make F3 be `find-file'
;; Note: it does not currently work to say
;; (global-set-key 'f3 "\C-x\C-f")
;; The reason is that macros can't do interactive things properly.
;; This is an extremely longstanding bug in Emacs. Eventually,
;; it will be fixed. (Hopefully ..)
(global-set-key [f3] 'find-file)

;; Make F4 be "mark", F5 be "copy", F6 be "paste"
;; Note that you can set a key sequence either to a command or to another
;; key sequence.
(global-set-key [f4] 'set-mark-command)
(global-set-key [f5] "\M-w")
(global-set-key [f6] "\C-y")

;; Shift-F4 is "pop mark off of stack"
(global-set-key [(shift f4)] (lambda () (interactive) (set-mark-command t)))

;; Make F7 be `save-buffer'
(global-set-key [f7] 'save-buffer)

;; Make F8 be "start macro", F9 be "end macro", F10 be "execute macro"
(global-set-key [f8] 'start-kbd-macro)
(global-set-key [f9] 'end-kbd-macro)
(global-set-key [f10] 'call-last-kbd-macro)

;; Here's an alternative binding if you don't use keyboard macros:
;; Make F8 be `save-buffer' followed by `delete-window'.
;;(global-set-key 'f8 "\C-x\C-s\C-x0")

;; If you prefer delete to actually delete forward then you want to
;; uncomment the next line (or use `Customize' to customize this).
;; (setq delete-key-deletes-forward t)


(cond (running-xemacs
;;
;; Code for any version of XEmacs/Lucid Emacs goes here
;;

;; Change the values of some variables.
;; (t means true; nil means false.)
;;
;; Use the "Describe Variable..." option on the "Help" menu
;; to find out what these variables mean.
(setq find-file-use-truenames nil
find-file-compare-truenames t
minibuffer-confirm-incomplete t
complex-buffers-menu-p t
next-line-add-newlines nil
mail-yank-prefix "> "
kill-whole-line t
)

;; When running ispell, consider all 1-3 character words as correct.
(setq ispell-extra-args '("-W" "3"))

(cond ((or (not (fboundp 'device-type))
(equal (device-type) 'x))
;; Code which applies only when running emacs under X goes here.
;; (We check whether the function `device-type' exists
;; before using it. In versions before 19.12, there
;; was no such function. If it doesn't exist, we
;; simply assume we're running under X -- versions before
;; 19.12 only supported X.)

;; Remove the binding of C-x C-c, which normally exits emacs.
;; It's easy to hit this by mistake, and that can be annoying.
;; Under X, you can always quit with the "Exit Emacs" option on
;; the File menu.
(global-set-key "\C-x\C-c" nil)

;; Uncomment this to enable "sticky modifier keys" in 19.13
;; and up. With sticky modifier keys enabled, you can
;; press and release a modifier key before pressing the
;; key to be modified, like how the ESC key works always.
;; If you hold the modifier key down, however, you still
;; get the standard behavior. I personally think this
;; is the best thing since sliced bread (and a *major*
;; win when it comes to reducing Emacs pinky), but it's
;; disorienting at first so I'm not enabling it here by
;; default.

;;(setq modifier-keys-are-sticky t)

;; This changes the variable which controls the text that goes
;; in the top window title bar. (However, it is not changed
;; unless it currently has the default value, to avoid
;; interfering with a -wn command line argument I may have
;; started emacs with.)
(if (equal frame-title-format "%S: %b")
(setq frame-title-format
(concat "%S: " invocation-directory invocation-name
" [" emacs-version "]"
(if nil ; (getenv "NCD")
""
" %b"))))

;; If we're running on display 0, load some nifty sounds that
;; will replace the default beep. But if we're running on a
;; display other than 0, which probably means my NCD X terminal,
;; which can't play digitized sounds, do two things: reduce the
;; beep volume a bit, and change the pitch of the sound that is
;; made for "no completions."
;;
;; (Note that sampled sounds only work if XEmacs was compiled
;; with sound support, and we're running on the console of a
;; Sparc, HP, or SGI machine, or on a machine which has a
;; NetAudio server; otherwise, you just get the standard beep.)
;;
;; (Note further that changing the pitch and duration of the
;; standard beep only works with some X servers; many servers
;; completely ignore those parameters.)
;;
(cond ((string-match ":0" (getenv "DISPLAY"))
(load-default-sounds))
(t
(setq bell-volume 40)
(setq sound-alist
(append sound-alist '((no-completion :pitch 500))))
))

;; Make `C-x C-m' and `C-x RET' be different (since I tend
;; to type the latter by accident sometimes.)
(define-key global-map [(control x) return] nil)

;; Change the pointer used when the mouse is over a modeline
(set-glyph-image modeline-pointer-glyph "leftbutton")

;; Change the continuation glyph face so it stands out more
(and (fboundp 'set-glyph-property)
(boundp 'continuation-glyph)
(set-glyph-property continuation-glyph 'face 'bold))

;; Change the pointer used during garbage collection.
;;
;; Note that this pointer image is rather large as pointers go,
;; and so it won't work on some X servers (such as the MIT
;; R5 Sun server) because servers may have lamentably small
;; upper limits on pointer size.
;;(if (featurep 'xpm)
;; (set-glyph-image gc-pointer-glyph
;; (expand-file-name "trash.xpm" data-directory)))

;; Here's another way to do that: it first tries to load the
;; pointer once and traps the error, just to see if it's
;; possible to load that pointer on this system; if it is,
;; then it sets gc-pointer-glyph, because we know that
;; will work. Otherwise, it doesn't change that variable
;; because we know it will just cause some error messages.
(if (featurep 'xpm)
(let ((file (expand-file-name "recycle.xpm" data-directory)))
(if (condition-case error
;; check to make sure we can use the pointer.
(make-image-instance file nil
'(pointer))
(error nil)) ; returns nil if an error occurred.
(set-glyph-image gc-pointer-glyph file))))

(when (featurep 'menubar)
;; Add `dired' to the File menu
(add-menu-button '("File") ["Edit Directory" dired t])

;; Here's a way to add scrollbar-like buttons to the menubar
(add-menu-button nil ["Top" beginning-of-buffer t])
(add-menu-button nil ["<<<" scroll-down t])
(add-menu-button nil [" . " recenter t])
(add-menu-button nil [">>>" scroll-up t])
(add-menu-button nil ["Bot" end-of-buffer t]))

;; Change the behavior of mouse button 2 (which is normally
;; bound to `mouse-yank'), so that it inserts the selected text
;; at point (where the text cursor is), instead of at the
;; position clicked.
;;
;; Note that you can find out what a particular key sequence or
;; mouse button does by using the "Describe Key..." option on
;; the Help menu.
(setq mouse-yank-at-point t)

;; When editing C code (and Lisp code and the like), I often
;; like to insert tabs into comments and such. It gets to be
;; a pain to always have to use `C-q TAB', so I set up a more
;; convenient binding. Note that this does not work in
;; TTY frames, where tab and shift-tab are indistinguishable.
(define-key global-map '(shift tab) 'self-insert-command)

;; LISPM bindings of Control-Shift-C and Control-Shift-E.
;; Note that "\C-C" means Control-C, not Control-Shift-C.
;; To specify shifted control characters, you must use the
;; more verbose syntax used here.
(define-key emacs-lisp-mode-map '(control C) 'compile-defun)
(define-key emacs-lisp-mode-map '(control E) 'eval-defun)

;; If you like the FSF Emacs binding of button3 (single-click
;; extends the selection, double-click kills the selection),
;; uncomment the following:

;; Under 19.13, the following is enough:
;(define-key global-map 'button3 'mouse-track-adjust)

;; But under 19.12, you need this:
;(define-key global-map 'button3
; (lambda (event)
; (interactive "e")
; (let ((default-mouse-track-adjust t))
; (mouse-track event))))

;; Under both 19.12 and 19.13, you also need this:
;(add-hook 'mouse-track-click-hook
; (lambda (event count)
; (if (or (/= (event-button event) 3)
; (/= count 2))
; nil ;; do the normal operation
; (kill-region (point) (mark))
; t ;; don't do the normal operations.
; )))

))

))

;; Oh, and here's a cute hack you might want to put in the sample .emacs
;; file: it changes the color of the window if it's not on the local
;; machine, or if it's running as root:

;; local emacs background: whitesmoke
;; remote emacs background: palegreen1
;; root emacs background: coral2
(cond
((and (string-match "XEmacs" emacs-version)
(eq window-system 'x)
(boundp 'emacs-major-version)
(= emacs-major-version 19)
(>= emacs-minor-version 12))
(let* ((root-p (eq 0 (user-uid)))
(dpy (or (getenv "DISPLAY") ""))
(remote-p (not
(or (string-match "^\\(\\|unix\\|localhost\\):" dpy)
(let ((s (system-name)))
(if (string-match "\\.\\(netscape\\|mcom\\)\\.com" s)
(setq s (substring s 0 (match-beginning 0))))
(string-match (concat "^" (regexp-quote s)) dpy)))))
(bg (cond (root-p "coral2")
(remote-p "palegreen1")
(t nil))))
(cond (bg
(let ((def (color-name (face-background 'default)))
(faces (face-list)))
(while faces
(let ((obg (face-background (car faces))))
(if (and obg (equal def (color-name obg)))
(set-face-background (car faces) bg)))
(setq faces (cdr faces)))))))))


;;; Older versions of emacs did not have these variables
;;; (emacs-major-version and emacs-minor-version.)
;;; Let's define them if they're not around, since they make
;;; it much easier to conditionalize on the emacs version.

(if (and (not (boundp 'emacs-major-version))
(string-match "^[0-9]+" emacs-version))
(setq emacs-major-version
(string-to-int (substring emacs-version
(match-beginning 0) (match-end 0)))))
(if (and (not (boundp 'emacs-minor-version))
(string-match "^[0-9]+\\.\\([0-9]+\\)" emacs-version))
(setq emacs-minor-version
(string-to-int (substring emacs-version
(match-beginning 1) (match-end 1)))))

;;; Define a function to make it easier to check which version we're
;;; running.

(defun running-emacs-version-or-newer (major minor)
(or (> emacs-major-version major)
(and (= emacs-major-version major)
(>= emacs-minor-version minor))))

(cond ((and running-xemacs
(running-emacs-version-or-newer 19 6))
;;
;; Code requiring XEmacs/Lucid Emacs version 19.6 or newer goes here
;;
))

(cond ((>= emacs-major-version 19)
;;
;; Code for any vintage-19 emacs goes here
;;
))

(cond ((and (not running-xemacs)
(>= emacs-major-version 19))
;;
;; Code specific to FSF Emacs 19 (not XEmacs/Lucid Emacs) goes here
;;
))

(cond ((< emacs-major-version 19)
;;
;; Code specific to emacs 18 goes here
;;
))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Customization of Specific Packages ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;; Load gnuserv, which will allow you to connect to XEmacs sessions
;;; using `gnuclient'.

;; If you never run more than one XEmacs at a time, you might want to
;; always start gnuserv. Otherwise it is preferable to specify
;; `-f gnuserv-start' on the command line to one of the XEmacsen.
; (gnuserv-start)


;;; ********************
;;; Load efs, which uses the FTP protocol as a pseudo-filesystem.
;;; When this is loaded, the pathname syntax /user@host:/remote/path
;;; refers to files accessible through ftp.
;;;
(require 'dired)
;; compatible ange-ftp/efs initialization derived from code
;; from John Turner
;; As of 19.15, efs is bundled instead of ange-ftp.
;; NB: doesn't handle 20.0 properly, efs didn't appear until 20.1.
;;
;; The environment variable EMAIL_ADDRESS is used as the password
;; for access to anonymous ftp sites, if it is set. If not, one is
;; constructed using the environment variables USER and DOMAINNAME
;; (e.g. turner@lanl.gov), if set.

(if (and running-xemacs
(or (and (= emacs-major-version 20) (>= emacs-minor-version 1))
(and (= emacs-major-version 19) (>= emacs-minor-version 15))))
(progn
(message "Loading and configuring bundled packages... efs")
(require 'efs-auto)
(if (getenv "USER")
(setq efs-default-user (getenv "USER")))
(if (getenv "EMAIL_ADDRESS")
(setq efs-generate-anonymous-password (getenv "EMAIL_ADDRESS"))
(if (and (getenv "USER")
(getenv "DOMAINNAME"))
(setq efs-generate-anonymous-password
(concat (getenv "USER")"@"(getenv "DOMAINNAME")))))
(setq efs-auto-save 1))
(progn
(message "Loading and configuring bundled packages... ange-ftp")
(require 'ange-ftp)
(if (getenv "USER")
(setq ange-ftp-default-user (getenv "USER")))
(if (getenv "EMAIL_ADDRESS")
(setq ange-ftp-generate-anonymous-password (getenv "EMAIL_ADDRESS"))
(if (and (getenv "USER")
(getenv "DOMAINNAME"))
(setq ange-ftp-generate-anonymous-password
(concat (getenv "USER")"@"(getenv "DOMAINNAME")))))
(setq ange-ftp-auto-save 1)
)
)

;;; ********************
;;; Load the default-dir.el package which installs fancy handling
;;; of the initial contents in the minibuffer when reading
;;; file names.

(if (and running-xemacs
(or (and (= emacs-major-version 20) (>= emacs-minor-version 1))
(and (= emacs-major-version 19) (>= emacs-minor-version 15))))
(require 'default-dir))

;;; ********************
;;; Load the auto-save.el package, which lets you put all of your autosave
;;; files in one place, instead of scattering them around the file system.
;;;
(setq auto-save-directory (expand-file-name "~/autosave/")
auto-save-directory-fallback auto-save-directory
auto-save-hash-p nil
efs-auto-save t
efs-auto-save-remotely nil
;; now that we have auto-save-timeout, let's crank this up
;; for better interactive response.
auto-save-interval 2000
)
;; We load this afterwards because it checks to make sure the
;; auto-save-directory exists (creating it if not) when it's loaded.
(require 'auto-save)

;; This adds additional extensions which indicate files normally
;; handled by cc-mode.
(setq auto-mode-alist
(append '(("\\.C$" . c++-mode)
("\\.cc$" . c++-mode)
("\\.hh$" . c++-mode)
("\\.c$" . c-mode)
("\\.h$" . c-mode))
auto-mode-alist))


;;; ********************
;;; cc-mode (the mode you're in when editing C, C++, and Objective C files)

;; Tell cc-mode not to check for old-style (K&R) function declarations.
;; This speeds up indenting a lot.
(setq c-recognize-knr-p nil)

;; Change the indentation amount to 4 spaces instead of 2.
;; You have to do it in this complicated way because of the
;; strange way the cc-mode initializes the value of `c-basic-offset'.
(add-hook 'c-mode-hook (lambda () (setq c-basic-offset 4)))


;;; ********************
;;; Load a partial-completion mechanism, which makes minibuffer completion
;;; search multiple words instead of just prefixes; for example, the command
;;; `M-x byte-compile-and-load-file RET' can be abbreviated as `M-x b-c-a RET'
;;; because there are no other commands whose first three words begin with
;;; the letters `b', `c', and `a' respectively.
;;;
(load-library "completer")


;;; ********************
;;; Load crypt, which is a package for automatically decoding and reencoding
;;; files by various methods - for example, you can visit a .Z or .gz file,
;;; edit it, and have it automatically re-compressed when you save it again.
;;;
(setq crypt-encryption-type 'pgp ; default encryption mechanism
crypt-confirm-password t ; make sure new passwords are correct
;crypt-never-ever-decrypt t ; if you don't encrypt anything, set this to
; tell it not to assume that "binary" files
; are encrypted and require a password.
)
(require 'crypt)


;;; ********************
;;; Edebug is a source-level debugger for emacs-lisp programs.
;;;
(define-key emacs-lisp-mode-map "\C-xx" 'edebug-defun)


;;; ********************
;;; Font-Lock is a syntax-highlighting package. When it is enabled and you
;;; are editing a program, different parts of your program will appear in
;;; different fonts or colors. For example, with the code below, comments
;;; appear in red italics, function names in function definitions appear in
;;; blue bold, etc. The code below will cause font-lock to automatically be
;;; enabled when you edit C, C++, Emacs-Lisp, and many other kinds of
;;; programs.
;;;
;;; The "Options" menu has some commands for controlling this as well.
;;;
(cond (running-xemacs

;; If you want the default colors, you could do this:
;; (setq font-lock-use-default-fonts nil)
;; (setq font-lock-use-default-colors t)
;; but I want to specify my own colors, so I turn off all
;; default values.
(setq font-lock-use-default-fonts nil)
(setq font-lock-use-default-colors nil)

(require 'font-lock)

;; Mess around with the faces a bit. Note that you have
;; to change the font-lock-use-default-* variables *before*
;; loading font-lock, and wait till *after* loading font-lock
;; to customize the faces.

;; string face is green
(set-face-foreground 'font-lock-string-face "forest green")

;; comments are italic and red; doc strings are italic
;;
;; (I use copy-face instead of make-face-italic/make-face-bold
;; because the startup code does intelligent things to the
;; 'italic and 'bold faces to ensure that they are different
;; from the default face. For example, if the default face
;; is bold, then the 'bold face will be unbold.)
(copy-face 'italic 'font-lock-comment-face)
;; Underlining comments looks terrible on tty's
(set-face-underline-p 'font-lock-comment-face nil 'global 'tty)
(set-face-highlight-p 'font-lock-comment-face t 'global 'tty)
(copy-face 'font-lock-comment-face 'font-lock-doc-string-face)
(set-face-foreground 'font-lock-comment-face "red")

;; function names are bold and blue
(copy-face 'bold 'font-lock-function-name-face)
(set-face-foreground 'font-lock-function-name-face "blue")

;; misc. faces
(and (find-face 'font-lock-preprocessor-face) ; 19.13 and above
(copy-face 'bold 'font-lock-preprocessor-face))
(copy-face 'italic 'font-lock-type-face)
(copy-face 'bold 'font-lock-keyword-face)
))


;;; ********************
;;; fast-lock is a package which speeds up the highlighting of files
;;; by saving information about a font-locked buffer to a file and
;;; loading that information when the file is loaded again. This
;;; requires a little extra disk space be used.
;;;
;;; Normally fast-lock puts the cache file (the filename appended with
;;; .flc) in the same directory as the file it caches. You can
;;; specify an alternate directory to use by setting the variable
;;; fast-lock-cache-directories.

;; Let's use lazy-lock instead.
;;(add-hook 'font-lock-mode-hook 'turn-on-fast-lock)
;;(setq fast-lock-cache-directories '("/foo/bar/baz"))


;;; ********************
;;; lazy-lock is a package which speeds up the highlighting of files
;;; by doing it "on-the-fly" -- only the visible portion of the
;;; buffer is fontified. The results may not always be quite as
;;; accurate as using full font-lock or fast-lock, but it's *much*
;;; faster. No more annoying pauses when you load files.

(add-hook 'font-lock-mode-hook 'turn-on-lazy-lock)
;; I personally don't like "stealth mode" (where lazy-lock starts
;; fontifying in the background if you're idle for 30 seconds)
;; because it takes too long to wake up again on my piddly Sparc 1+.
(setq lazy-lock-stealth-time nil)


;;; ********************
;;; func-menu is a package that scans your source file for function
;;; definitions and makes a menubar entry that lets you jump to any
;;; particular function definition by selecting it from the menu. The
;;; following code turns this on for all of the recognized languages.
;;; Scanning the buffer takes some time, but not much.
;;;
;;; Send bug reports, enhancements etc to:
;;; David Hughes
;;;
(cond (running-xemacs
(require 'func-menu)
(define-key global-map 'f8 'function-menu)
(add-hook 'find-file-hooks 'fume-add-menubar-entry)
(define-key global-map "\C-cl" 'fume-list-functions)
(define-key global-map "\C-cg" 'fume-prompt-function-goto)

;; The Hyperbole information manager package uses (shift button2) and
;; (shift button3) to provide context-sensitive mouse keys. If you
;; use this next binding, it will conflict with Hyperbole's setup.
;; Choose another mouse key if you use Hyperbole.
(define-key global-map '(shift button3) 'mouse-function-menu)

;; For descriptions of the following user-customizable variables,
;; type C-h v
(setq fume-max-items 25
fume-fn-window-position 3
fume-auto-position-popup t
fume-display-in-modeline-p t
fume-menubar-menu-location "File"
fume-buffer-name "*Function List*"
fume-no-prompt-on-valid-default nil)
))


;;; ********************
;;; MH is a mail-reading system from the Rand Corporation that relies on a
;;; number of external filter programs (which do not come with emacs.)
;;; Emacs provides a nice front-end onto MH, called "mh-e".
;;;
;; Bindings that let you send or read mail using MH
;(global-set-key "\C-xm" 'mh-smail)
;(global-set-key "\C-x4m" 'mh-smail-other-window)
;(global-set-key "\C-cr" 'mh-rmail)

;; Customization of MH behavior.
(setq mh-delete-yanked-msg-window t)
(setq mh-yank-from-start-of-msg 'body)
(setq mh-summary-height 11)

;; Use lines like the following if your version of MH
;; is in a special place.
;(setq mh-progs "/usr/dist/pkgs/mh/bin.svr4/")
;(setq mh-lib "/usr/dist/pkgs/mh/lib.svr4/")


;;; ********************
;;; resize-minibuffer-mode makes the minibuffer automatically
;;; resize as necessary when it's too big to hold its contents.

(autoload 'resize-minibuffer-mode "rsz-minibuf" nil t)
(resize-minibuffer-mode)
(setq resize-minibuffer-window-exactly nil)

;;; ********************
;;; W3 is a browser for the World Wide Web, and takes advantage of the very
;;; latest redisplay features in XEmacs. You can access it simply by typing
;;; 'M-x w3'; however, if you're unlucky enough to be on a machine that is
;;; behind a firewall, you will have to do something like this first:

;(setq w3-use-telnet t
; ;;
; ;; If the Telnet program you use to access the outside world is
; ;; not called "telnet", specify its name like this.
; w3-telnet-prog "itelnet"
; ;;
; ;; If your Telnet program adds lines of junk at the beginning
; ;; of the session, specify the number of lines here.
; w3-telnet-header-length 4
; )


Thanks to :
http://www.uluga.ubuntuforums.org/showthread.php?t=1375454
http://www.dotemacs.de/dotfiles/sample.emacs.html
http://www.dotemacs.de/dotfiles/BenjaminRutt.emacs.html

Wednesday, May 12, 2010

Hangman (game)


Hangman is a paper and pencil guessing game for two or more players. One player thinks of a word and the other tries to guess it by suggesting letters.
_______
|/ |
| O
| \|/
| |
| / \
__|_________

The word to guess is represented by a row of dashes, giving the number of letters. If the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions. If the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark. The game is over when:
An example game in progress; the answer is Wikipedia.

* The guessing player completes the word, or guesses the whole word correctly
* The other player completes the diagram:
This diagram is, in fact, designed to look like a hanging man. Although debates have arisen about the questionable taste of this picture, it is still in use today. A common alternative for teachers is to draw an apple tree with ten apples, erasing or crossing out the apples as the guesses are used up.

The exact nature of the diagram differs; some players draw the gallows before play and draw parts of the man's body (traditionally the head, then the torso, then the left arm, then the right arm, then the left leg, then the right leg). Some players begin with no diagram at all, and drawing the individual elements of the gallows as part of the game, effectively giving the guessing players more chances. The amount of detail on the man can also vary, affecting the number of chances. Many players include a face on the head, either all at once or one feature at a time.

Some modifications to game play, such as "buying a vowel", result from the U.S. television game show Wheel of Fortune, created by Merv Griffin.


My -- Hangman C programming code
------------------------------------------------
#include
#include

#define len 8

int try1(){
printf("---------------\n");
printf("failed \n");
printf("---------------\n");
}

int try2(){
static int i=9;
static int j=0;
i--;
printf("\t %d more chances \n",i);
j++;
prn_galg(j);
while( i == 0){
printf("Time out \n");
exit(-1);
}
}

int showlogo() {
printf("--------------------------------------------\n");
printf("| # # # # # #### # # # # # |\n");
printf("| # # # # ## # # ## ## # # ## # |\n");
printf("| #### ##### # # # # ## # # # ##### # # # |\n");
printf("| # # # # # ## # # # # # # # ## |\n");
printf("| # # # # # # ### # # # # # # |\n");
printf("--------------------------------------------\n\n");
}

void prn_galg(int i) {
switch (i) {
case 0 :
// printf("Amount of wrong letters: %d\n\n", i);
printf("\n");
printf("\n");
printf("\n");
printf("\n");
printf("\n");
printf("\n");
printf("____________\n\n");
break;

case 1 :
// printf("Amount of wrong letters: %d\n\n", i);
printf("\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf("__|_________\n\n");
break;

case 2 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf("__|_________\n\n");
break;

case 3 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |/\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf("__|_________\n\n");
break;

case 4 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |/ | \n");
printf(" | O \n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf("__|_________\n\n");
break;

case 5 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |/ | \n");
printf(" | O \n");
printf(" | |\n");
printf(" | |\n");
printf(" |\n");
printf("__|_________\n\n");
break;

case 6 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |/ | \n");
printf(" | O \n");
printf(" | \\|\n");
printf(" | | \n");
printf(" |\n");
printf("__|_________\n\n");
break;

case 7 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |/ | \n");
printf(" | O \n");
printf(" | \\|/\n");
printf(" | | \n");
printf(" |\n");
printf("__|_________\n\n");
break;

case 8 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |/ | \n");
printf(" | O \n");
printf(" | \\|/\n");
printf(" | | \n");
printf(" | /\n");
printf("__|_________\n\n");
break;

case 9 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |/ | \n");
printf(" | O \n");
printf(" | \\|/\n");
printf(" | | \n");
printf(" | / \\\n");
printf("__|_________\n\n");
break;

case 10 :
// printf("Amount of wrong letters: %d\n\n", i);
printf(" _______\n");
printf(" |/ | \n");
printf(" | X \n");
printf(" | \\|/\n");
printf(" | | \n");
printf(" | / \\\n");
printf("__|_________\n\n");
break;

}
}

int main(){
/* here in "hangman" to be found is "h _ _ g _ _ n" */
char h[len] = "hangman";
char c[len];

stop :

showlogo();
printf("**Welcome to Hangman Code**\n");
printf("word to find is h _ _ g _ _ n\n");
// printf(" Find H 1 2 G 3 4 N \n");
printf("Press 'e' for quit \n");
printf("Try for the 1 letter: \n");

c[0] = getchar();

if(c[0]== 'e'){
exit(-1);
}

try2();
while(c[0] == h[1]){ // A

c[1] = getchar();
while (c[1] == h[2]){ // N

c[2] = getchar();
while (c[2] == h[4]){ // M

c[3] = getchar();
while (c[3] == h[5]){ //N
printf("Hurray you have completed \n");
printf("****************************************\n");
printf("****************************************\n");
printf("Completed letters are %c%c%c%c%c%c%c \n",h[0],h[1],h[2],h[3],h[4],h[5],h[6]);
printf("****************************************\n");
printf("****************************************\n");
printf("Success you have made the Hangman code \n");
goto stop;
}
try2();
printf("Completed letters are %c%c%c%c%c _ n \n",h[0],h[1],h[2],h[3],h[4]);
printf("Try for the 4 letter: \n");
}
try2();
printf("Completed letters are %c%c%cg _ _ n \n",h[0],h[1],h[2]);
printf("Try for the 3 letter: \n");
}
try2();
printf("Completed letters are %c%c _ g _ _ n \n",h[0],h[1]);
printf("Try for the 2 letter :\n");
}
{
goto stop;
}
return 0;
}

// this is a sample base code i have written . Still more efficient code will be released // as soon as possible.


Thanks to
wikipedia
http://en.wikipedia.org/wiki/Hangman_(game)
www.daniweb.com/code/post1157561.html

Tuesday, May 4, 2010

C file input/output

The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header .

The I/O functionality of C is fairly low-level by modern standards; C abstracts all file operations into operations on streams of bytes, which may be "input streams" or "output streams". Unlike some earlier programming languages, C has no direct support for random-access data files; to read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

The stream model of file I/O was popularized by the Unix operating system, which was developed concurrently with the C programming language itself. The vast majority of modern operating systems have inherited streams from Unix, and many languages in the C programming language family have inherited C's file I/O interface with few if any changes (for example, PHP). The C++ standard library reflects the "stream" concept in its syntax; see iostream.


Opening a file using fopen

A file is opened using fopen, which returns an I/O stream attached to the specified file or other device from which reading and writing can be done. If the function fails, it returns a null pointer.

The related C library function freopen performs the same operation after first closing any open stream associated with its parameters.

They are defined as

FILE *fopen(const char *path, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *fp);

The fopen function is essentially a slightly higher-level wrapper for the open system call of Unix operating systems. In the same way, fclose is often a thin wrapper for the Unix system call close, and the C FILE structure itself often corresponds to a Unix file descriptor. In POSIX environments, the fdopen function can be used to initialize a FILE structure from a file descriptor; however, file descriptors are a purely Unix concept not present in standard C.

The mode parameter to fopen and freopen must be a string that begins with one of the following sequences:

mode description starts..
r rb open for reading beginning

for further modes refer the man pages

Closing a stream using fclose

The fclose function takes one argument: a pointer to the FILE structure of the stream to close.

int fclose(FILE *fp);

Reading from a stream using fgetc

The fgetc function is used to read a character from a stream.

int fgetc(FILE *fp);

Writing a file using fwrite

fwrite is defined as

size_t fwrite (const void *array, size_t size, size_t count, FILE *stream);

fwrite function writes a block of data to the stream. It will write an array of count elements to the current position in the stream. For each element, it will write size bytes. The position indicator of the stream will be advanced by the number of bytes written successfully.

Writing a file using fwrite

fwrite is defined as

size_t fwrite (const void *array, size_t size, size_t count, FILE *stream);

fwrite function writes a block of data to the stream. It will write an array of count elements to the current position in the stream. For each element, it will write size bytes. The position indicator of the stream will be advanced by the number of bytes written successfully.

The function will return the number of elements written successfully. The return value will be equal to count if the write completes successfully. In case of a write error, the return value will be less than count.

The following program opens a file named new1.c, writes a string of characters to the file, then closes it.

#include 

#include
#include

int main(void)
{
FILE *fp;
size_t count;
const char *str = "hello\n";

fp = fopen("sample.txt", "w");
if(fp == NULL) {
perror("failed to open sample.txt");
return EXIT_FAILURE;
}
count = fwrite(str, 1, strlen(str), fp);
printf("Wrote %zu bytes. fclose(fp) %s.\n", count, fclose(fp) == 0 ? "succeeded" : "failed");
return EXIT_SUCCESS;
}

Writing to a stream using fputc

The fputc function is used to write a character to a stream.

int fputc(int c, FILE *fp);

The parameter c is silently converted to an unsigned char before being output. If successful, fputc returns the character written. If unsuccessful, fputc returns EOF.

The standard macro putc, also defined in , behaves in almost the same way as fputc, except that—being a macro—it may evaluate its arguments more than once.

The standard function putchar, also defined in , takes only the first argument, and is equivalent to putc(c, stdout) where c is that argument.

The following C program opens a binary file called myfile, reads five bytes from it, and then closes the file.
#include 

#include

int main(void)
{
char buffer[5] = {0}; /* initialized to zeroes */
int i, rc;
FILE *fp = fopen("myfile", "rb");
if (fp == NULL) {
perror("Failed to open file \"myfile\"");
return EXIT_FAILURE;
}
for (i = 0; (rc = getc(fp)) != EOF && i < 5; buffer[i++] = rc)
;
fclose(fp);
if (i == 5) {
puts("The bytes read were...");
printf("%x %x %x %x %x\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]);
} else
fputs("There was an error reading the file.\n", stderr);
return EXIT_SUCCESS;
}




Tuesday, April 27, 2010

Wget

GNU Wget (or just Wget) is a computer program that retrieves content from web servers, and is part of the GNU Project. Its name is derived from World Wide Web and get, connotative of its primary function. It currently supports downloading via HTTP, HTTPS, and FTP protocols, the most popular TCP/IP-based protocols used for web browsing.

Its features include recursive download, conversion of links for offline viewing of local HTML, support for proxies, and much more. It appeared in 1996, coinciding with the boom of popularity of the Web, causing its wide use among Unix users and distribution with most major Linux distributions. Written in portable C, Wget can be easily installed on any Unix-like system and has been ported to many environments, including Mac OS X, Microsoft Windows, OpenVMS and AmigaOS.

It has been used as the basis for graphical programs such as GWget for the GNOME Desktop and KGet for the KDE Desktop. Wget is free software.

Using Wget
Basic usage

Typical usage of GNU Wget consists of invoking it from the command line, providing one or more URLs as arguments.

# Download Wget's source code from the GNU ftp site.
wget ftp://ftp.gnu.org/pub/gnu/wget/wget-latest.tar.gz

wget http://www.example.com/

Advanced usage

# Using wget to download content protected by referer and cookies.
# 1. get base url and save its cookies in file
# 2. get protected content using stored cookies
wget --cookies=on --keep-session-cookies --save-cookies=cookie.txt http://first_page
wget --referer=http://first_page --cookies=on --load-cookies=cookie.txt
--keep-session-cookies --save-cookies=cookie.txt http://second_page

For more information see the man page of wget.


Authors and copyright

GNU Wget was written by Hrvoje Nikšić with contributions by many other people, including Dan Harkless, Ian Abbott, and Mauro Tortonesi. Significant contributions are credited in the AUTHORS file included in the distribution, and all remaining ones are documented in the changelogs, also included with the program. Wget is now maintained by Micah Cowan.

The copyright to Wget belongs to the Free Software Foundation, whose policy is to require copyright assignments for all non-trivial contributions to GNU software.

Thanks to : wikipedia