--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/.hgignore Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,34 @@
+# use glob syntax.
+syntax: glob
+
+*.html
+*.aux
+*.dvi
+*.log
+*.nav
+*.snm
+*.toc
+*.pdf
+*.vrb
+*.out
+*.sty
+*.pyc
+*.zip
+*~
+.project
+.pydevproject
+app.yaml
+build
+tests/coverageResults
+*,cover
+tests/.coverage
+*.git
+*.egg-info
+eggs
+parts
+.installed.cfg
+bin
+develop-eggs
+.gitignore
+.DS_Store
+index.yaml
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/Introduction/Introduction.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,36 @@
+Introduction to the Course
+==========================
+
+Engineering students use computers for a large number of curricular
+tasks – mostly computation centred. However, they do not see this as coding or programming tasks and usually are not even aware of the tools and
+techniques that will help them to handle these tasks better. This results
+in less than optimal use of their time and resources. This also causes
+difficulties when it comes tocollaboration and building on other people’s
+work. This course is intended to train such students in good software
+practices and tools for producing code and documentation.
+
+After successfully completing the program, the participants will be able to:
+
+- understand how software tools work together and how they can be used in tandem to carry out tasks,
+
+- use unix command line tools to carry out common (mostly text processing tasks,
+
+- to generate professional documents,
+
+- use version control effectively – for both code and documents,
+
+- automate tasks by writing shell scripts and python scripts,
+
+- realise the impact of coding style and readbility on quality,
+
+- write mid-sized programs that carry out typical engineering / numerical computations such as those that involve (basic) manipulation of large arrays in an efficient manner,
+
+- generate 2D and simple 3D plots,
+
+- debug programs using a standardised approach,
+
+- understand the importance of tests and the philosophy of Test Driven Development,
+
+- write unit tests and improve the quality of code.
+
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/Python_Problem_Set_1.tex Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,91 @@
+\documentclass[11pt]{article}
+\title{Basic Python Problem Set 1}
+\author{Asokan Pichai}
+\date{}
+\begin{document}
+\maketitle
+\section{Pyramids}
+\begin{enumerate}
+ \item Write a program to display the following pyramid. The number of lines in the pyramid should not be hard-coded.
+ It should be obtained from the user. The pyramid should appear as close to the centre of the screen as possible.
+ \begin{verbatim}
+ *
+ ***
+ *****
+ *******
+ \end{verbatim}
+ \item Write a program to display the following pyramid. The number of lines in the pyramid should not be hard-coded.
+ It should be obtained from the user. The pyramid should appear as close to the centre of the screen as possible.
+ \begin{verbatim}
+ *
+ * *
+ * * *
+ * * * *
+ \end{verbatim}
+ \item Write a program to display the following pyramid. The number of lines has to be a parameter obtained from the
+ user. The pyramid must appear aligned to the left edge of the screen.
+ \begin{verbatim}
+ 1
+ 2 2
+ 3 3 3
+ 4 4 4 4
+ \end{verbatim}
+ \item Write a program to display the following pyramid. The number of lines has to be a parameter obtained from the
+ user. The pyramid must appear aligned to the left edge of the screen.
+ \begin{verbatim}
+ 1
+ 2 4
+ 3 6 9
+ 4 8 12 16
+ 5 10 15 20 25
+ \end{verbatim}
+ \item Write a program to display the following output. The last number where the program will stop printing has to
+ be a parameter obtained from the user. The pyramid must appear aligned to the left edge of the screen. Note that
+ depending on the last number, the base of the pyramid may be smaller than the line above it.
+ \begin{verbatim}
+ 1
+ 2 3
+ 4 5 6
+ 7 8 9 10
+ 11 12
+ \end{verbatim}
+\end{enumerate}
+\section{Some mathematics}
+\begin{enumerate}
+ \item Write a program to calculate the gcd of two numbers.
+ \item Write a program to generate all the Armstrong numbers: three numbers that are equal to the sum of the cubes of
+ their digits: that is $abc = a^3 + b^3 + c^3$
+ \item Write a program that lists all four digit numbers that are perfect squares \emph{and} have all their digits
+ even. An example is $6400$ which is $80^2$. Note that in order to be listed a four digit number must satisfy
+ both criteria. For example, $5625$ is a square, it does not have all digits even and
+ $4842$ is not a square and hence they should not appear in the output. You can assume that two functions
+ $areDigitsEven()$ and $isSquare()$ are available. (Please ask the instructor for the exact location of these
+ functions and copy them to your area.)
+\end{enumerate}
+\section{Code}
+\begin{verbatim}
+#-------------------------------- #
+# Accepts an integer and returns #
+# True if all digits are even #
+# False otherwise #
+#-------------------------------- #
+def areDigitsEven( n ):
+ while n > 0:
+ if (n % 10) %2 != 0:
+ return False
+ n = n / 10
+ return True
+#-------------------------------- #
+# Accepts an integer and returns #
+# True if it is a perfect square #
+# False otherwise #
+#-------------------------------- #
+def isSquare( n ):
+ i = 1
+ while i * i < n:
+ i += 1
+ return i * i == n
+
+\end{verbatim}
+\end{document}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/STTP-Design.tex Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,226 @@
+\documentclass{article}
+\title{Course Design Document\\Software Tools, Techniques and Practices\\for Engineering Studies}
+\author{Asokan Pichai\\Prabhu Ramachandran}
+\date{}
+\parindent=0pt
+\begin{document}
+\maketitle
+
+\subsection{Preamble}
+\begin{description}
+ \item[Version] 0.8
+ \item[Purpose] This document captures the design of the Software
+ Tools, Techniques and Practices course. This course is designed
+ under the project on ``Adoption of Open Source Software in Science
+ and Engineering Education'' at Indian Institute of Technology,
+ Bombay funded by the National Mission on Education through
+ Information and Communication Technology, Ministry of Human
+ Resources Development under the thrust area of ``Adaptation and
+ deployment of open source packages equivalent to MATLAB, ORCAD etc''.
+
+ \item[Recipients] in no particular order
+ \begin{enumerate}
+ \item Kannan Moudgalya
+ \item Venkatesh Choppella
+ \item Madhu Belur
+ \item Mani Bhushan
+ \item Eric Jones
+ \item Travis Oliphant
+ \item Greg Wilson
+ \end{enumerate}
+\end{description}
+\newpage
+
+\section{Specifications}
+\begin{description}
+
+\item[Audience] The course is meant for students of BE/BTech and ME/MTech programmes. While it is open to all students,
+ it has been designed with students of non-CS, non-IT streams only.
+\begin{itemize}
+\item Separate courses will be designed along similar lines targetted to students of Bsc/MSc in Physics, Chemistry and Mathematics. These courses will predominantly but not necessarily use the same tools.
+\item For students of Statistics a broadly similar course using R will be designed.
+\item Each of these courses will have a corresponding `Train the Teachers' course.
+\end{itemize}
+
+\item[Background] The students will possess good computer usage skills and some programming knowledge
+\begin{itemize}
+\item Good computer usage skills is typically using computers for preparing documents, sending email etc.
+\item Some programming knowledge is basic understanding of coding such as operators, assignments, conditionals, loops
+ and functions.
+\item Knowledge of any specific language or operating system is NOT assumed.
+\end{itemize}
+
+\item[Context] Engineering students use computers for a large number of
+ curricular tasks--mostly computation centred. However, they do not
+ see this as coding or programming tasks and usually are not even
+ aware of the tools and techniques that will help them to handle
+ these tasks better. This results in less than optimal use of their
+ time and resources. This also causes difficulties when it comes
+ tocollaboration and building on other people's work. This program is
+ intended to train such students in good software practices and tools
+ for producing code and documentation.
+\end{description}
+
+\newpage
+
+\section{Course Objectives}
+\emph{Each objective is associated with a level in the Revised Bloom's
+Taxonomy - which is a standard pedagogic tool for curriculum planning,
+instructional delivery and assessment. Please refer to:
+http://www.apa.org/ed/new\_blooms.html for a one page explanation.}
+
+
+After successfully completing the program, the participants will be able to:
+\begin{enumerate}
+\item \label{intro} understand how software tools work together and how they can be used in tandem to carry out tasks,\hfill \texttt{RBT U\phantom{p}}
+\item \label{cmd} use unix command line tools to carry out common (mostly text processing) tasks,\hfill \texttt{RBT Ap}
+\item \label{pdf} to generate professional documents, \hfill \texttt{RBT Ap}
+\item \label{VC} use version control effectively--for both code and documents,\hfill \texttt{RBT Ap}
+\item \label{scr} automate tasks by writing shell scripts and python scripts,\hfill \texttt{RBT Ap}
+\item \label{sty} realise the impact of coding style and readbility on quality,\hfill \texttt{RBT U\phantom{p}}
+\item \label{py} write mid-sized programs that carry out typical engineering/numerical computations such as those that involve (basic) manipulation of large arrays in an efficient manner,\hfill \texttt{RBT Ap}
+\item \label{plot} generate 2D and simple 3D plots, \hfill \texttt{RBT Ap}
+\item \label{dbg} debug programs using a standardised approach,\hfill \texttt{RBT Ap}
+\item \label{test} understand the importance of tests and the philosophy of Test Driven Development,\hfill \texttt{RBT U\phantom{p}}
+\item \label{unit} write unit tests and improve the quality of code. \hfill \texttt{RBT Ap}
+ \end{enumerate}
+\section{Assessment Strategies}
+We will use tests and quizzes during the course and an end of course project to evaluate the degree of achievement of the objective. The projects will be be individual but sufficient hooks will be built into projects that the participants need to work together. Such hooks will be in the nature of building dependencies--A's code will call B's function etc--rather than making people work in teams.
+
+\section{Module Plan}
+The objectives listed against the modules may be covered only partially in that module. In other words, each module may cover one or more objectives fully or partially. And each objective may be handled in one or more modules--partially or fully.
+
+\begin{tabular}{||l|l|l|r||}\hline\hline
+Seq & Module & Course Objectives & Duration\\
+Num & Name & Covered & (Hours)\\\hline
+1 & Using Linux Tools & \ref{intro}, \ref{cmd}, \ref{scr}, \ref{dbg} and \ref{test} & 7\\\hline
+2 & Basic Python Programming & \ref{scr}, \ref{sty}, \ref{dbg} and \ref{test} & 8\\\hline
+3 & LaTeX & \ref{pdf} and \ref{scr} & 2\\\hline
+4 & Version Control & \ref{VC} & 2\\\hline
+5 & Coding Style \& Approach & \ref{sty} and \ref{test} & 2\\\hline
+6 & Test Driven Development & \ref{test}, \ref{unit}, \ref{cmd} and \ref{scr} & 4\\\hline
+7 & Advanced Python & \ref{py}, \ref{dbg}, \ref{plot} and \ref{test} & 8\\\hline
+8 & Project & All applied & 6\\\hline
+\end{tabular}
+
+Session Count = 39 + 1 Buffer
+\subsection*{Note}
+\begin{itemize}
+ \item All sessions will be held in rooms where students are sitting before a computer.
+ \item We will use \texttt{bzr} as the version control tool. The course materials will be duplicated with other tools
+ such as \texttt{hg, git, svn}.
+ \item It is expected that shell scripting covered in module 1 will act as a revision for basic programming
+ concepts.
+\end{itemize}
+
+\section{Module 1: Using Linux Tools}
+\label{ULT}
+\subsection{Module Objectives}
+After successfully completing this module a participant will be able to:
+ \begin{itemize}
+ \item Understand the design philosophy of *nix \hfill U\phantom{p}
+ \item Use Linux as their day-to-day operating system\hfill Ap
+ \item Use the text processing tools such as \texttt{grep, tr}\hfill Ap
+ \item Write and execute (bash) shell scripts\hfill Ap
+ \item Use a text editor comfortably\hfill Ap
+ \end{itemize}
+\subsection{Suggested Reading}
+\begin{enumerate}
+ \item "In the beginning..." by Neal Stephenson
+ \item "The Unix Programming Environment" by Kernighan and Pike
+\end{enumerate}
+\subsection{Session Plan}
+\begin{tabular}{llr}
+Session & Topic & Duration\\\hline
+1 & Introduction to the course & ~5 mts\\
+ & Historical background and implications. Why Unix? & 10 mts\\
+ & Getting started--logging in; \tt{ls, date, who, cd, mkdir} & 10 mts\\
+ & Getting help: \tt{apropos, man, info} & 10 mts\\
+ & Basic file handling: \tt{cp, mv, rm} & 10 mts\\
+ & First session buffer & ~5 mts\\\hline
+
+2 & Command line arguments & ~5 mts\\
+ & Basic text processing: \tt{head, tail, cut, paste} & 15 mts\\
+ & Shell meta characters & 10 mts\\
+ & Looking at files: \tt{cat, less} & ~5 mts\\
+ & Directory structure: \tt{man hier, ls -l} & ~5 mts\\
+ & Permissions and ownership, \tt{chmod, chown} & 10 mts\\\hline
+
+3 & Redirection and Piping & 10 mts\\
+ & More text processing: \tt{grep, tr} & 10 mts\\
+ & Elementary regex: . ? * \^ \$ [ ] & 15 mts\\
+ & One liners: show lines n to m, show directories & 15 mts\\\hline
+
+4 & More text processing: \tt{join, sort, uniq} & 10 mts\\
+ & Generating a word frequency list & 10 mts\\
+ & Basic editing and editors: vim, scite & 10 mts\\
+ & Personalising your environment: \tt{.bashrc, .vimrc} & 10 mts\\
+ & Subshells and \tt{source} & 10 mts\\\hline
+
+5 & More tools: \tt{tar, zip, diff, cmp, comm} & 25 mts\\
+ & Environment variables, \tt{set} & 10 mts\\
+ & Writing simple shell scripts & 15 mts\\\hline
+
+6 & Control structures and operators in bash & 20 mts\\
+ & Writing shell scripts & 30 mts\\\hline
+
+7 & Functions in bash scripts & 20 mts\\
+ & Assessment Test & 30 mts\\\hline\hline
+\end{tabular}
+
+\section{Module 2: Basic Python Programming}
+\label{BPyP}
+\subsection{Module Objectives}
+After successfully completing this module a participant will be able to:
+ \begin{itemize}
+ \item write modular, procedural code in python, \hfill RBT Ap
+ \item understand the functional features of python, \hfill RBT U\phantom{p}
+ \item understand the object model of python, \hfill RBT U\phantom{p}
+ \item write programs using objects \hfill RBT Ap
+ \end{itemize}
+\subsection{Suggested Reading}
+\begin{itemize}
+ \item Python tutorial available at http://www.python.org/doc/tut
+ \item ``Dive into Python'' by Mark Pilgrim
+\end{itemize}
+
+\begin{tabular}{llr}
+Session & Topic & Duration\\\hline
+1 & Introduction to the Python language. Philosophy & 25 mts\\
+ & The interpreter(\texttt{ipython}--python as calculator & \\
+ & Editing and running a .py file & \\
+ & Basic data types and operators: Numeric and string & \\
+ & Syntax: \tt{while, if, raw\_input(), int(), def} & \\
+ & Problem set 1 & 25 mts\\\hline
+
+2 & lists and tuples: basic operations & 15 mts\\
+ & Syntax: \tt{range(),for, len()} & \\
+ & Code Reading: Example set 1 & 10 mts\\
+ & Problem set 2 & 25 mts\\\hline
+
+3 & Strings: basic operations & 10 mts\\
+ & Introduction to the standard library & \\
+ & I/O: reading and writing files & 15 mts\\
+ & Problem set 3 & 25 mts\\\hline
+
+4 & Dictionaries: basic operations & 10 mts\\
+ & Modules and code organization & 10 mts\\
+ & Executing modules as scripts: \texttt{\_\_main\_\_} &\\
+ & \texttt{import} and overview of major modules & 15 mts\\
+ & Problem set 4 & 15 mts\\\hline
+
+5 & Interim Assessment & 30 mts\\
+ & Functional approach: overview & 25 mts\\
+ & \texttt{map, filter, reduce} and list comprehensions & \\\hline
+
+6 & Classes and Objects & 20 mts\\
+ & Writing Object-oriented code & 30 mts\\
+ & Code Reading: Example set 2 &\\\hline
+
+7 & Case Studies: & 50 mts\\
+ & png notation &\\
+ & result html generation &\\\hline
+8 & Assessment & 50 mts\\\hline\hline
+\end{tabular}
+
+\end{document}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/basic_python/func.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,339 @@
+Functional Approach
+===================
+
+*Functions* allow us to enclose a set of statements and call the function again
+and again instead of repeating the group of statements everytime. Functions also
+allow us to isolate a piece of code from all the other code and provides the
+convenience of not polluting the global variables.
+
+*Function* in python is defined with the keyword **def** followed by the name
+of the function, in turn followed by a pair of parenthesis which encloses the
+list of parameters to the function. The definition line ends with a ':'. The
+definition line is followed by the body of the function intended by one block.
+The *Function* must return a value::
+
+ def factorial(n):
+ fact = 1
+ for i in range(2, n):
+ fact *= i
+
+ return fact
+
+The code snippet above defines a function with the name factorial, takes the
+number for which the factorial must be computed, computes the factorial and
+returns the value.
+
+A *Function* once defined can be used or called anywhere else in the program. We
+call a fucntion with its name followed by a pair of parenthesis which encloses
+the arguments to the function.
+
+The value that function returns can be assigned to a variable. Let's call the
+above function and store the factorial in a variable::
+
+ fact5 = factorial(5)
+
+The value of fact5 will now be 120, which is the factorial of 5. Note that we
+passed 5 as the argument to the function.
+
+It may be necessary to document what the function does, for each of the function
+to help the person who reads our code to understand it better. In order to do
+this Python allows the first line of the function body to be a string. This
+string is called as *Documentation String* or *docstring*. *docstrings* prove
+to be very handy since there are number of tools which can pull out all the
+docstrings from Python functions and generate the documentation automatically
+from it. *docstrings* for functions can be written as follows::
+
+ def factorial(n):
+ 'Returns the factorial for the number n.'
+ fact = 1
+ for i in range(2, n):
+ fact *= i
+
+ return fact
+
+An important point to note at this point is that, a function can return any
+Python value or a Python object, which also includes a *Tuple*. A *Tuple* is
+just a collection of values and those values themselves can be of any other
+valid Python datatypes, including *Lists*, *Tuples*, *Dictionaries* among other
+things. So effectively, if a function can return a tuple, it can return any
+number of values through a tuple
+
+Let us write a small function to swap two values::
+
+ def swap(a, b):
+ return b, a
+
+ c, d = swap(a, b)
+
+Function scope
+---------------
+The variables used inside the function are confined to the function's scope
+and doesn't pollute the variables of the same name outside the scope of the
+function. Also the arguments passed to the function are passed by-value if
+it is of basic Python data type::
+
+ def cant_change(n):
+ n = 10
+
+ n = 5
+ cant_change(n)
+
+Upon running this code, what do you think would have happened to value of n
+which was assigned 5 before the function call? If you have already tried out
+that snippet on the interpreter you already know that the value of n is not
+changed. This is true of any immutable types of Python like *Numbers*, *Strings*
+and *Tuples*. But when you pass mutable objects like *Lists* and *Dictionaries*
+the values are manipulated even outside the function::
+
+ >>> def can_change(n):
+ ... n[1] = James
+ ...
+
+ >>> name = ['Mr.', 'Steve', 'Gosling']
+ >>> can_change(name)
+ >>> name
+ ['Mr.', 'James', 'Gosling']
+
+If nothing is returned by the function explicitly, Python takes care to return
+None when the funnction is called.
+
+Default Arguments
+-----------------
+
+There may be situations where we need to allow the functions to take the
+arguments optionally. Python allows us to define function this way by providing
+a facility called *Default Arguments*. For example, we need to write a function
+that returns a list of fibonacci numbers. Since our function cannot generate an
+infinite list of fibonacci numbers, we need to specify the number of elements
+that the fibonacci sequence must contain. Suppose, additionally, we want to the
+function to return 10 numbers in the sequence if no option is specified we can
+define the function as follows::
+
+ def fib(n=10):
+ fib_list = [0, 1]
+ for i in range(n - 2):
+ next = fib_list[-2] + fib_list[-1]
+ fib_list.append(next)
+ return fib_list
+
+When we call this function, we can optionally specify the value for the
+parameter n, during the call as an argument. Calling with no argument and
+argument with n=5 returns the following fibonacci sequences::
+
+ fib()
+ [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
+ fib(5)
+ [0, 1, 1, 2, 3]
+
+Keyword Arguments
+-----------------
+
+When a function takes a large number of arguments, it may be difficult to
+remember the order of the parameters in the function definition or it may
+be necessary to pass values to only certain parameters since others take
+the default value. In either of these cases, Python provides the facility
+of passing arguments by specifying the name of the parameter as defined in
+the function definition. This is known as *Keyword Arguments*.
+
+In a function call, *Keyword arguments* can be used for each argument, in the
+following fashion::
+
+ argument_name=argument_value
+ Also denoted as: keyword=argument
+
+ def wish(name='World', greetings='Hello'):
+ print "%s, %s!" % (greetings, name)
+
+This function can be called in one of the following ways. It is important to
+note that no restriction is imposed in the order in which *Keyword arguments*
+can be specified. Also note, that we have combined *Keyword arguments* with
+*Default arguments* in this example, however it is not necessary::
+
+ wish(name='Guido', greetings='Hey')
+ wish(greetings='Hey', name='Guido')
+
+Calling functions by specifying arguments in the order of parameters specified
+in the function definition is called as *Positional arguments*, as opposed to
+*Keyword arguments*. It is possible to use both *Positional arguments* and
+*Keyword arguments* in a single function call. But Python doesn't allow us to
+bungle up both of them. The arguments to the function, in the call, must always
+start with *Positional arguments* which is in turn followed by *Keyword
+arguments*::
+
+ def my_func(x, y, z, u, v, w):
+ # initialize variables.
+ ...
+ # do some stuff
+ ...
+ # return the value
+
+It is valid to call the above functions in the following ways::
+
+ my_func(10, 20, 30, u=1.0, v=2.0, w=3.0)
+ my_func(10, 20, 30, 1.0, 2.0, w=3.0)
+ my_func(10, 20, z=30, u=1.0, v=2.0, w=3.0)
+ my_func(x=10, y=20, z=30, u=1.0, v=2.0, w=3.0)
+
+Following lists some of the invalid calls::
+
+ my_func(10, 20, z=30, 1.0, 2.0, 3.0)
+ my_func(x=10, 20, z=30, 1.0, 2.0, 3.0)
+ my_func(x=10, y=20, z=30, u=1.0, v=2.0, 3.0)
+
+Parameter Packing and Unpacking
+-------------------------------
+
+The positional arguments passed to a function can be collected in a tuple
+parameter and keyword arguments can be collected in a dictionary. Since keyword
+arguments must always be the last set of arguments passed to a function, the
+keyword dictionary parameter must be the last parameter. The function definition
+must include a list explicit parameters, followed by tuple paramter collecting
+parameter, whose name is preceded by a *****, for collecting positional
+parameters, in turn followed by the dictionary collecting parameter, whose name
+is preceded by a ****** ::
+
+ def print_report(title, *args, **name):
+ """Structure of *args*
+ (age, email-id)
+ Structure of *name*
+ {
+ 'first': First Name
+ 'middle': Middle Name
+ 'last': Last Name
+ }
+ """
+
+ print "Title: %s" % (title)
+ print "Full name: %(first)s %(middle)s %(last)s" % name
+ print "Age: %d\nEmail-ID: %s" % args
+
+The above function can be called as. Note, the order of keyword parameters can
+be interchanged::
+
+ >>> print_report('Employee Report', 29, 'johny@example.com', first='Johny',
+ last='Charles', middle='Douglas')
+ Title: Employee Report
+ Full name: Johny Douglas Charles
+ Age: 29
+ Email-ID: johny@example.com
+
+The reverse of this can also be achieved by using a very identical syntax while
+calling the function. A tuple or a dictionary can be passed as arguments in
+place of a list of *Positional arguments* or *Keyword arguments* respectively
+using ***** or ****** ::
+
+ def print_report(title, age, email, first, middle, last):
+ print "Title: %s" % (title)
+ print "Full name: %s %s %s" % (first, middle, last)
+ print "Age: %d\nEmail-ID: %s" % (age, email)
+
+ >>> args = (29, 'johny@example.com')
+ >>> name = {
+ 'first': 'Johny',
+ 'middle': 'Charles',
+ 'last': 'Douglas'
+ }
+ >>> print_report('Employee Report', *args, **name)
+ Title: Employee Report
+ Full name: Johny Charles Douglas
+ Age: 29
+ Email-ID: johny@example.com
+
+Nested Functions and Scopes
+---------------------------
+
+Python allows nesting one function inside another. This style of programming
+turns out to be extremely flexible and powerful features when we use *Python
+decorators*. We will not talk about decorators is beyond the scope of this
+course. If you are interested in knowing more about *decorator programming* in
+Python you are suggested to read:
+
+| http://avinashv.net/2008/04/python-decorators-syntactic-sugar/
+| http://personalpages.tds.net/~kent37/kk/00001.html
+
+However, the following is an example for nested functions in Python::
+
+ def outer():
+ print "Outer..."
+ def inner():
+ print "Inner..."
+ print "Outer..."
+ inner()
+
+ >>> outer()
+
+map, reduce and filter functions
+--------------------------------
+
+Python provides several built-in functions for convenience. The **map()**,
+**reduce()** and **filter()** functions prove to be very useful with sequences like
+*Lists*.
+
+The **map** (*function*, *sequence*) function takes two arguments: *function*
+and a *sequence* argument. The *function* argument must be the name of the
+function which in turn takes a single argument, the individual element of the
+*sequence*. The **map** function calls *function(item)*, for each item in the
+sequence and returns a list of values, where each value is the value returned
+by each call to *function(item)*. **map()** function allows to pass more than
+one sequence. In this case, the first argument, *function* must take as many
+arguments as the number of sequences passed. This function is called with each
+corresponding element in the each of the sequences, or **None** if one of the
+sequence is exhausted::
+
+ def square(x):
+ return x*x
+
+ >>> map(square, [1, 2, 3, 4])
+ [1, 4, 9, 16]
+
+ def mul(x, y):
+ return x*y
+
+ >>> map(mul, [1, 2, 3, 4], [6, 7, 8, 9])
+
+The **filter** (*function*, *sequence*) function takes two arguments, similar to
+the **map()** function. The **filter** function calls *function(item)*, for each
+item in the sequence and returns all the elements in the sequence for which
+*function(item)* returned True::
+
+ def even(x):
+ if x % 2:
+ return True
+ else:
+ return False
+
+ >>> filter(even, range(1, 10))
+ [1, 3, 5, 7, 9]
+
+The **reduce** (*function*, *sequence*) function takes two arguments, similar to
+**map** function, however multiple sequences are not allowed. The **reduce**
+function calls *function* with first two consecutive elements in the sequence,
+obtains the result, calls *function* with the result and the subsequent element
+in the sequence and so on until the end of the list and returns the final result::
+
+ def mul(x, y):
+ return x*y
+
+ >>> reduce(mul, [1, 2, 3, 4])
+ 24
+
+List Comprehensions
+~~~~~~~~~~~~~~~~~~~
+
+List Comprehension is a convenvience utility provided by Python. It is a
+syntatic sugar to create *Lists*. Using *List Comprehensions* one can create
+*Lists* from other type of sequential data structures or other *Lists* itself.
+The syntax of *List Comprehensions* consists of a square brackets to indicate
+the result is a *List* within which we include at least one **for** clause and
+multiple **if** clauses. It will be more clear with an example::
+
+ >>> num = [1, 2, 3]
+ >>> sq = [x*x for x in num]
+ >>> sq
+ [1, 4, 9]
+ >>> all_num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ >>> even = [x for x in all_num if x%2 == 0]
+
+The syntax used here is very clear from the way it is written. It can be
+translated into english as, "for each element x in the list all_num,
+if remainder of x divided by 2 is 0, add x to the list."
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/basic_python/interim_assessment.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,3 @@
+Interim Assessment
+==================
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/basic_python/intro.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,719 @@
+============
+Basic Python
+============
+
+This document is intended to be handed out at the end of the workshop. It has
+been designed for Engineering students who are Python beginners and have basic
+programming skills. The focus is on basic numerics and plotting using Python.
+
+The system requirements:
+ * Python - version 2.5.x or newer.
+ * IPython
+ * Text editor - scite, vim, emacs or whatever you are comfortable with.
+
+Introduction
+============
+
+The Python programming language was created by a dutch named Guido van Rossum.
+The idea of Python was conceived in December 1989. The name Python has nothing
+to do with the reptilian, but its been named after the 70s comedy series
+"Monty Python's Flying Circus", since it happens to be Guido's favourite
+TV series.
+
+It is a test.
+This is a test
+
+Current stable version of Python is 2.6.x, although Python 3.0 is also the stable
+version, it is not backwards compatible with the previous versions and is hence
+not entirely popular at the moment. This material will focus on the 2.6.x series.
+
+Python is licensed under the Python Software Foundation License (PSF License)
+which is GPL compatible Free Software license (excepting license version 1.6 and 2.0)
+It is a no strings attached license, which means the source code is free to modify
+and redistribute.
+
+The Python docs define Python as "Python is an interpreted, object-oriented,
+high-level programming language with dynamic semantics." A more detailed summary
+can be found at http://www.python.org/doc/essays/blurb.html. Python is a language that
+has been designed to help the programmer concentrate on solving the problem at hand
+and not worry about the programming language idiosyncrasies.
+
+Python is a highly cross platform compatible language on account of it being an
+interpreted language. It is highly scalable and hence has been adapted to run on
+the Nokia 60 series phones. Python has been designed to be readable and easy to use
+
+**Resources available for reference**
+
+* Web: http://www.python.org
+* Doc: http://www.python.org/doc
+* Free Tutorials:
+ * Official Python Tutorial: http://docs.python.org/tut/tut.html
+ * Byte of Python: http://www.byteofpython.info/
+ * Dive into Python: http://diveintopython.org/
+
+**Advantages of Python - Why Python??**
+
+* Python has been designed for readability and ease of use. Its been designed in
+ such a fashion that it imposes readability on the programmer. Python does away
+ with the braces and the semicolons and instead implements code blocks based on
+ indentation, thus enhancing readability.
+
+* Python is a high level, interpreted, modular and object oriented language.
+ Python performs memory management on its own, thus the programmer need not bother
+ about allocating and deallocating memory to variables. Python provides extensibility
+ by providing modules which can be easily imported similar to headers in C and
+ packages in Java. Python is object oriented and hence provides all the object oriented
+ characteristics such as inheritance, encapsulation and polymorphism.
+
+* Python offers a highly powerful interactive programming interface in the form
+ of the 'Interactive Interpreter' which will be discussed in more detail in the
+ following sections.
+
+* Python provides a rich standard library and an extensive set of modules. The
+ power of Python modules can be seen in this slightly exaggerated cartoon
+ http://xkcd.com/353/
+
+* Python interfaces well with most other programming languages such as C, C++
+ and FORTRAN.
+
+Although, Python has one setback. Python is not fast as some of the compiled
+languages like C or C++. Yet, the amount of flexibility and power more than make
+up for this setback.
+
+
+The Python Interpreter
+======================
+
+The Interactive Interpreter
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Typing *python* at the shell prompt on any standard Unix/Gnu-Linux system and
+hitting the enter key fires up the Python 'Interactive Interpreter'. The Python
+interpreter is one of the most integral features of Python. The prompt obtained
+when the interactive interpreter is similar to what is shown below. The exact
+appearance might differ based on the version of Python being used. The ``>>>``
+thing shown is the python prompt. When something is typed at the prompt and the
+enter key is hit, the python interpreter interprets the command entered and
+performs the appropriate action. All the examples presented in this document are
+to be tried hands on, on the interactive interpreter.
+
+::
+
+ Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)
+ [GCC 4.3.2] on linux2
+ Type "help", "copyright", "credits" or "license" for more information.
+ >>>
+
+Lets try with an example, type ``print 'Hello, World!'`` at the prompt and hit
+the enter key.
+
+::
+
+ >>> print 'Hello, World!'
+ Hello, World!
+
+This example was quite straight forward, and thus we have written our first
+line of Python code. Now let us try typing something arbitrary at the prompt.
+For example:
+
+::
+
+ >>> arbit word
+ File "<stdin>", line 1
+ arbit word
+ ^
+ SyntaxError: invalid syntax
+ >>>
+
+The interpreter gave an error message saying that 'arbit word' was invalid
+syntax which is valid. The interpreter is an amazing tool when learning to
+program in Python. The interpreter provides a help function that provides the
+necessary documentation regarding all Python syntax, constructs, modules and
+objects. Typing *help()* at the prompt gives the following output:
+
+::
+
+ >>> help()
+
+ Welcome to Python 2.5! This is the online help utility.
+
+ If this is your first time using Python, you should definitely check out
+ the tutorial on the Internet at http://www.python.org/doc/tut/.
+
+ Enter the name of any module, keyword, or topic to get help on writing
+ Python programs and using Python modules. To quit this help utility and
+ return to the interpreter, just type "quit".
+
+ To get a list of available modules, keywords, or topics, type "modules",
+ "keywords", or "topics". Each module also comes with a one-line summary
+ of what it does; to list the modules whose summaries contain a given word
+ such as "spam", type "modules spam".
+
+ help>
+
+
+As mentioned in the output, entering the name of any module, keyword or topic
+will provide the documentation and help regarding the same through the online
+help utility. Pressing *Ctrl+d* exits the help prompt and returns to the
+python prompt.
+
+Let us now try a few examples at the python interpreter.
+
+Eg 1:
+::
+
+ >>> print 'Hello, python!'
+ Hello, python!
+ >>>
+
+Eg 2:
+::
+
+ >>> print 4321*567890
+ 2453852690
+ >>>
+
+Eg 3:
+::
+
+ >>> 4321*567890
+ 2453852690L
+ >>>
+
+::
+
+ Note: Notice the 'L' at the end of the output. The 'L' signifies that the
+ output of the operation is of type *long*. It was absent in the previous
+ example because we used the print statement. This is because *print* formats
+ the output before displaying.
+
+Eg 4:
+::
+
+ >>> big = 12345678901234567890 ** 3
+ >>> print big
+ 1881676372353657772490265749424677022198701224860897069000
+ >>>
+
+::
+
+ This example is to show that unlike in C or C++ there is no limit on the
+ value of an integer.
+
+Try this on the interactive interpreter:
+``import this``
+
+*Hint: The output gives an idea of Power of Python*
+
+*ipython* - An enhanced interactive Python interpreter
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The power and the importance of the interactive interpreter was the highlight
+of the previous section. This section provides insight into the enhanced
+interpreter with more advanced set of features called **ipython**. Entering
+*ipython* at the shell prompt fires up the interactive interpreter.
+
+::
+
+ $ ipython
+ Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)
+ Type "copyright", "credits" or "license" for more information.
+
+ IPython 0.8.4 -- An enhanced Interactive Python.
+ ? -> Introduction and overview of IPython's features.
+ %quickref -> Quick reference.
+ help -> Python's own help system.
+ object? -> Details about 'object'. ?object also works, ?? prints more.
+
+ In [1]:
+
+This is the output obtained upon firing ipython. The exact appearance may
+change based on the Python version installed. The following are some of the
+various features provided by **ipython**:
+
+ Suggestions - ipython provides suggestions of the possible methods and
+ operations available for the given python object.
+
+Eg 5:
+
+::
+
+ In [4]: a = 6
+
+ In [5]: a.
+ a.__abs__ a.__divmod__ a.__index__ a.__neg__ a.__rand__ a.__rmod__ a.__rxor__
+ a.__add__ a.__doc__ a.__init__ a.__new__ a.__rdiv__ a.__rmul__ a.__setattr__
+ a.__and__ a.__float__ a.__int__ a.__nonzero__ a.__rdivmod__ a.__ror__ a.__str__
+ a.__class__ a.__floordiv__ a.__invert__ a.__oct__ a.__reduce__ a.__rpow__ a.__sub__
+ a.__cmp__ a.__getattribute__ a.__long__ a.__or__ a.__reduce_ex__ a.__rrshift__ a.__truediv__
+ a.__coerce__ a.__getnewargs__ a.__lshift__ a.__pos__ a.__repr__ a.__rshift__ a.__xor__
+ a.__delattr__ a.__hash__ a.__mod__ a.__pow__ a.__rfloordiv__ a.__rsub__
+ a.__div__ a.__hex__ a.__mul__ a.__radd__ a.__rlshift__ a.__rtruediv__
+
+In this example, we initialized 'a' (a variable - a concept that will be
+discussed in the subsequent sections.) to 6. In the next line when the *tab* key
+is pressed after typing '*a.*' ipython displays the set of all possible methods
+that are applicable on the object 'a' (an integer in this context). Ipython
+provides many such datatype specific features which will be presented in the
+further sections as and when the datatypes are introduced.
+
+Editing and running a python file
+=================================
+
+The previous sections focused on the use of the interpreter to run python code.
+While the interpeter is an excellent tool to test simple solutions and
+experiment with small code snippets, its main disadvantage is that everything
+written in the interpreter is lost once its quit. Most of the times a program is
+used by people other than the author. So the programs have to be available in
+some form suitable for distribution, and hence they are written in files. This
+section will focus on editing and running python files. Start by opening a text
+editor ( it is recommended you choose one from the list at the top of this page ).
+In the editor type down python code and save the file with an extension **.py**
+(python files have an extension of .py). Once done with the editing, save the
+file and exit the editor.
+
+Let us look at a simple example of calculating the gcd of 2 numbers using Python:
+
+**Creating the first python script(file)**
+::
+
+ $ emacs gcd.py
+ def gcd(x,y):
+ if x % y == 0:
+ return y
+ return gcd(y, x%y)
+
+ print gcd(72, 92)
+
+To run the script, open the shell prompt, navigate to the directory that
+contains the python file and run ``python <filename.py>`` at the prompt ( in this
+case filename is gcd.py )
+
+**Running the python script**
+::
+
+ $ python gcd.py
+ 4
+ $
+
+Another method to run a python script would be to include the line
+
+``#! /usr/bin/python``
+
+at the beginning of the python file and then make the file executable by
+
+$ chmod a+x *filename.py*
+
+Once this is done, the script can be run as a standalone program as follows:
+
+$ ./*filename.py*
+
+Basic Datatypes and operators in Python
+=======================================
+
+Python provides the following set of basic datatypes.
+
+ * Numbers: int, float, long, complex
+ * Strings
+ * Boolean
+
+Numbers
+~~~~~~~
+
+Numbers were introduced in the examples presented in the interactive interpreter
+section. Numbers include types as mentioned earlier viz., int (integers), float
+(floating point numbers), long (large integers), complex (complex numbers with
+real and imaginary parts). Python is not a strongly typed language, which means
+the type of a variable need not mentioned during its initialization. Let us look
+at a few examples.
+
+Eg 6:
+::
+
+ >>> a = 1 #here a is an integer variable
+
+Eg 7:
+::
+
+ >>> lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long
+ >>> lng
+ 122333444455555666666777777788888888999999999L #notice the trailing 'L'
+ >>> print lng
+ 122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L'
+ >>> lng+1
+ 122333444455555666666777777788888889000000000L
+
+
+Long numbers are the same as integers in almost all aspects. They can be used in
+operations just like integers and along with integers without any distinction.
+The only distinction comes during type checking (which is not a healthy practice).
+Long numbers are tucked with a trailing 'L' just to signify that they are long.
+Notice that in the example just lng at the prompt displays the value of the variable
+with the 'L' whereas ``print lng`` displays without the 'L'. This is because print
+formats the output before printing. Also in the example, notice that adding an
+integer to a long does not give any errors and the result is as expected. So for
+all practical purposes longs can be treated as ints.
+
+Eg 8:
+::
+
+ >>> fl = 3.14159 #fl is a float variable
+ >>> e = 1.234e-4 #e is also a float variable, specified in the exponential form
+ >>> a = 1
+ >>> b = 2
+ >>> a/b #integer division
+ 0
+ >>> a/fl #floating point division
+ 0.31831015504887655
+ >>> e/fl
+ 3.9279473133031364e-05
+
+
+Floating point numbers, simply called floats are real numbers with a decimal point.
+The example above shows the initialization of a float variable. Shown also in this
+example is the difference between integer division and floating point division.
+'a' and 'b' here are integer variables and hence the division gives 0 as the quotient.
+When either of the operands is a float, the operation is a floating point division,
+and the result is also a float as illustrated.
+
+Eg 9:
+::
+
+ >>> cplx = 3 + 4j #cplx is a complex variable
+ >>> cplx
+ (3+4j)
+ >>> print cplx.real #prints the real part of the complex number
+ 3.0
+ >>> print cplx.imag #prints the imaginary part of the complex number
+ 4.0
+ >>> print cplx*fl #multiplies the real and imag parts of the complex number with the multiplier
+ (9.42477+12.56636j)
+ >>> abs(cplx) #returns the absolute value of the complex number
+ 5.0
+
+Python provides a datatype for complex numbers. Complex numbers are initialized
+as shown in the example above. The *real* and *imag* operators return the real and
+imaginary parts of the complex number as shown. The *abs()* returns the absolute
+value of the complex number.
+
+Variables
+~~~~~~~~~
+
+Variables are just names that represent a value. Variables have already been
+introduced in the various examples from the previous sections. Certain rules about
+using variables:
+
+ * Variables have to be initialized or assigned a value before being used.
+ * Variable names can consist of letters, digits and underscores(_).
+ * Variable names cannot begin with digits, but can contain digits in them.
+
+In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx'
+are all variables of various datatypes.
+
+::
+
+ Note: Python is not a strongly typed language and hence an integer variable can at a
+ later stage be used as a float variable as well.
+
+Strings
+~~~~~~~
+
+Strings are one of the essential data structures of any programming language.
+The ``print "Hello, World!"`` program was introduced in the earlier section, and
+the *"Hello, World!"* in the print statement is a string. A string is basically
+a set of characters. Strings can be represented in various ways shown below:
+
+::
+
+ s = 'this is a string' # a string variable can be represented using single quotes
+ s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown
+ s = "I have 'single-quotes' inside!"
+ l = "A string spanning many lines\
+ one more line\
+ yet another" # a string can span more than a single line.
+ t = """A triple quoted string does # another way of representing multiline strings.
+ not need to be escaped at the end and
+ "can have nested quotes" etc."""
+
+Try the following on the interpreter:
+``s = 'this is a string with 'quotes' of similar kind'``
+
+**Exercise: How to use single quotes within single quotes in a string as shown
+in the above example without getting an error?**
+
+String operations
+-----------------
+
+A few basic string operations are presented here.
+
+**String concatenation**
+String concatenation is done by simple addition of two strings.
+
+::
+
+ >>> x = 'Hello'
+ >>> y = ' Python'
+ >>> print x+y
+ Hello Python
+
+*Try this yourself:*
+
+::
+
+ >>> somenum = 13
+ >>> print x+somenum
+
+The problem with the above example is that here a string variable and an integer
+variable are trying to be concantenated. To obtain the desired result from the
+above example the str(), repr() and the `` can be used.
+
+**str()** simply converts a value to a string in a reasonable form.
+**repr()** creates a string that is a representation of the value.
+
+The difference can be seen in the example shown below:
+
+::
+
+ >>> str(1000000000000000000000000000000000000000000000000L)
+ '1000000000000000000000000000000000000000000000000'
+ >>> repr(1000000000000000000000000000000000000000000000000L)
+ '1000000000000000000000000000000000000000000000000L'
+
+It can be observed that the 'L' in the long value shown was omitted by str(),
+whereas repr() converted that into a string too. An alternative way of using
+repr(value) is ```value```.
+
+A few more examples:
+::
+
+ >>> x = "Let's go \nto Pycon"
+ >>> print x
+ Let's go
+ to Pycon
+
+In the above example, notice that the '\n'(newline) character is formatted and
+the string is printed on two lines. The strings discussed until now were normal
+strings. Other than these there are two other types of strings namely, raw strings
+and unicode strings.
+
+**Raw strings** are strings which are unformatted, that is the backslashes(\) are
+not parsed and are left as it is in the string. Raw strings are represented with
+an 'r' at the start of a string.
+Let us look at an example
+
+::
+
+ >>> x = r"Let's go \nto Pycon"
+ >>> print x
+ Let's go \nto Pycon
+
+Note: The '\n' is not being parsed into a new line and is left as it is.
+
+*Try this yourself:*
+
+::
+
+ >>> x = r"Let's go to Pycon\"
+
+**Unicode strings** are strings where the characters are Unicode characters as
+opposed to ASCII characters. Unicode strings are represented with a 'u' at the
+start of the string.
+Let us look at an example:
+
+::
+
+ >>> x = u"Let's go to Pycon!"
+ >>> print x
+ Let's go to Pycon!
+
+Boolean
+~~~~~~~
+
+Python also provides special Boolean datatype. A boolean variable can assume a
+value of either *True* or *False* (Note the capitalizations).
+
+Let us look at examples:
+
+::
+
+ >>> t = True
+ >>> f = not t
+ >>> print f
+ False
+ >>> f or t
+ True
+ >>> f and t
+ False
+
+The **while** loop
+==================
+
+
+The Python **while** loop is similar to the C/C++ while loop. The syntax is as
+follows:
+
+::
+
+ statement 0
+ while condition:
+ statement 1 #while block
+ statement 2 #while block
+ statement 3 #outside the while block.
+
+Let us look at an example:
+
+::
+
+ >>> x = 1
+ >>> while x <= 5:
+ ... print x
+ ... x += 1
+ ...
+ 1
+ 2
+ 3
+ 4
+ 5
+
+The **if** conditional
+======================
+
+The Python **if** block provides the conditional execution of statements.
+If the condition evaluates as true the block of statements defined under the if
+block are executed.
+
+If the first block is not executed on account of the condition not being satisfied,
+the set of statements in the **else** block are executed.
+
+The **elif** block provides the functionality of evaluation of multiple conditions
+as shown in the example.
+
+The syntax is as follows:
+
+::
+
+ if condition :
+ statement_1
+ statement_2
+
+ elif condition:
+ statement_3
+ statement_4
+ else:
+ statement_5
+ statement_6
+
+Let us look at an example:
+
+::
+
+ >>> n = raw_input("Input a number:")
+ >>> if n < 0:
+ print n," is negative"
+ elif n > 0:
+ print n," is positive"
+ else:
+ print n, " is 0"
+
+**raw_input()**
+===============
+
+In the previous example we saw the call to the raw_input() subroutine.
+The **raw_input()** method is used to take user inputs through the console.
+Unlike **input()** which assumes the data entered by the user as a standard python
+expression, **raw_input()** treats all the input data as raw data and converts
+everything into a string. To illustrate this let us look at an example.
+
+::
+
+ >>> input("Enter a number thats a palindrome:")
+ Enter a number thats a palindrome:121
+ 121
+
+ >>> input("Enter your name:")
+ Enter your name:PythonFreak
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ File "<string>", line 1, in <module>
+ NameError: name 'PythonFreak' is not defined
+
+As shown above the **input()** assumes that the data entered is a valid Python
+expression. In the first call it prompts for an integer input and when entered
+it accepts the integer as an integer, whereas in the second call, when the string
+is entered without the quotes, **input()** assumes that the entered data is a valid
+Python expression and hence it raises and exception saying PythonFreak is not
+defined.
+
+::
+
+ >>> input("Enter your name:")
+ Enter your name:'PythonFreak'
+ 'PythonFreak'
+ >>>
+
+Here the name is accepted because its entered as a string (within quotes). But
+its unreasonable to go on using quotes each time a string is entered. Hence the
+alternative is to use **raw_input()**.
+
+Let us now look at how **raw_input()** operates with an example.
+
+::
+
+ >>> raw_input("Enter your name:")
+ Enter your name:PythonFreak
+ 'PythonFreak'
+
+Observe that the **raw_input()** is converting it into a string all by itself.
+
+::
+
+ >>> pal = raw_input("Enter a number thats a palindrome:")
+ Enter a number thats a palindrome:121
+ '121'
+
+Observe that **raw_input()** is converting the integer 121 also to a string as
+'121'. Let us look at another example:
+
+::
+
+ >>> pal = raw_input("Enter a number thats a palindrome:")
+ Enter a number thats a palindrome:121
+ >>> pal + 2
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ TypeError: cannot concatenate 'str' and 'int' objects
+ >>> pal
+ '121'
+
+Observe here that the variable *pal* is a string and hence integer operations
+cannot be performed on it. Hence the exception is raised.
+
+**int()** method
+================
+
+Generally for computing purposes, the data used is not strings or raw data but
+on integers, floats and similar mathematical data structures. The data obtained
+from **raw_input()** is raw data in the form of strings. In order to obtain integers
+from strings we use the method **int()**.
+
+Let us look at an example.
+
+::
+
+ >>> intpal = int(pal)
+ >>> intpal
+ 121
+
+In the previous example it was observed that *pal* was a string variable. Here
+using the **int()** method the string *pal* was converted to an integer variable.
+
+*Try This Yourself:*
+
+::
+
+ >>> stringvar = raw_input("Enter a name:")
+ Enter a name:Guido Van Rossum
+ >>> stringvar
+ 'Guido Van Rossum'
+ >>> numvar = int(stringvar)
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/basic_python/intro.rst~ Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,719 @@
+============
+Basic Python
+============
+
+This document is intended to be handed out at the end of the workshop. It has
+been designed for Engineering students who are Python beginners and have basic
+programming skills. The focus is on basic numerics and plotting using Python.
+
+The system requirements:
+ * Python - version 2.5.x or newer.
+ * IPython
+ * Text editor - scite, vim, emacs or whatever you are comfortable with.
+
+Introduction
+============
+
+The Python programming language was created by a dutch named Guido van Rossum.
+The idea of Python was conceived in December 1989. The name Python has nothing
+to do with the reptilian, but its been named after the 70s comedy series
+"Monty Python's Flying Circus", since it happens to be Guido's favourite
+TV series.
+
+It is a test.
+This is a test
+
+Current stable version of Python is 2.6.x, although Python 3.0 is also the stable
+version, it is not backwards compatible with the previous versions and is hence
+not entirely popular at the moment. This material will focus on the 2.6.x series.
+
+Python is licensed under the Python Software Foundation License (PSF License)
+which is GPL compatible Free Software license (excepting license version 1.6 and 2.0)
+It is a no strings attached license, which means the source code is free to modify
+and redistribute.
+
+The Python docs define Python as "Python is an interpreted, object-oriented,
+high-level programming language with dynamic semantics." A more detailed summary
+can be found at http://www.python.org/doc/essays/blurb.html. Python is a language that
+has been designed to help the programmer concentrate on solving the problem at hand
+and not worry about the programming language idiosyncrasies.
+
+Python is a highly cross platform compatible language on account of it being an
+interpreted language. It is highly scalable and hence has been adapted to run on
+the Nokia 60 series phones. Python has been designed to be readable and easy to use
+
+**Resources available for reference**
+
+* Web: http://www.python.org
+* Doc: http://www.python.org/doc
+* Free Tutorials:
+ * Official Python Tutorial: http://docs.python.org/tut/tut.html
+ * Byte of Python: http://www.byteofpython.info/
+ * Dive into Python: http://diveintopython.org/
+
+**Advantages of Python - Why Python??**
+
+* Python has been designed for readability and ease of use. Its been designed in
+ such a fashion that it imposes readability on the programmer. Python does away
+ with the braces and the semicolons and instead implements code blocks based on
+ indentation, thus enhancing readability.
+
+* Python is a high level, interpreted, modular and object oriented language.
+ Python performs memory management on its own, thus the programmer need not bother
+ about allocating and deallocating memory to variables. Python provides extensibility
+ by providing modules which can be easily imported similar to headers in C and
+ packages in Java. Python is object oriented and hence provides all the object oriented
+ characteristics such as inheritance, encapsulation and polymorphism.
+
+* Python offers a highly powerful interactive programming interface in the form
+ of the 'Interactive Interpreter' which will be discussed in more detail in the
+ following sections.
+
+* Python provides a rich standard library and an extensive set of modules. The
+ power of Python modules can be seen in this slightly exaggerated cartoon
+ http://xkcd.com/353/
+
+* Python interfaces well with most other programming languages such as C, C++
+ and FORTRAN.
+
+Although, Python has one setback. Python is not fast as some of the compiled
+languages like C or C++. Yet, the amount of flexibility and power more than make
+up for this setback.
+
+
+The Python Interpreter
+======================
+
+The Interactive Interpreter
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Typing *python* at the shell prompt on any standard Unix/Gnu-Linux system and
+hitting the enter key fires up the Python 'Interactive Interpreter'. The Python
+interpreter is one of the most integral features of Python. The prompt obtained
+when the interactive interpreter is similar to what is shown below. The exact
+appearance might differ based on the version of Python being used. The ``>>>``
+thing shown is the python prompt. When something is typed at the prompt and the
+enter key is hit, the python interpreter interprets the command entered and
+performs the appropriate action. All the examples presented in this document are
+to be tried hands on, on the interactive interpreter.
+
+::
+
+ Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)
+ [GCC 4.3.2] on linux2
+ Type "help", "copyright", "credits" or "license" for more information.
+ >>>
+
+Lets try with an example, type ``print 'Hello, World!'`` at the prompt and hit
+the enter key.
+
+::
+
+ >>> print 'Hello, World!'
+ Hello, World!
+
+This example was quite straight forward, and thus we have written our first
+line of Python code. Now let us try typing something arbitrary at the prompt.
+For example:
+
+::
+
+ >>> arbit word
+ File "<stdin>", line 1
+ arbit word
+ ^
+ SyntaxError: invalid syntax
+ >>>
+
+The interpreter gave an error message saying that 'arbit word' was invalid
+syntax which is valid. The interpreter is an amazing tool when learning to
+program in Python. The interpreter provides a help function that provides the
+necessary documentation regarding all Python syntax, constructs, modules and
+objects. Typing *help()* at the prompt gives the following output:
+
+::
+
+ >>> help()
+
+ Welcome to Python 2.5! This is the online help utility.
+
+ If this is your first time using Python, you should definitely check out
+ the tutorial on the Internet at http://www.python.org/doc/tut/.
+
+ Enter the name of any module, keyword, or topic to get help on writing
+ Python programs and using Python modules. To quit this help utility and
+ return to the interpreter, just type "quit".
+
+ To get a list of available modules, keywords, or topics, type "modules",
+ "keywords", or "topics". Each module also comes with a one-line summary
+ of what it does; to list the modules whose summaries contain a given word
+ such as "spam", type "modules spam".
+
+ help>
+
+
+As mentioned in the output, entering the name of any module, keyword or topic
+will provide the documentation and help regarding the same through the online
+help utility. Pressing *Ctrl+d* exits the help prompt and returns to the
+python prompt.
+
+Let us now try a few examples at the python interpreter.
+
+Eg 1:
+::
+
+ >>> print 'Hello, python!'
+ Hello, python!
+ >>>
+
+Eg 2:
+::
+
+ >>> print 4321*567890
+ 2453852690
+ >>>
+
+Eg 3:
+::
+
+ >>> 4321*567890
+ 2453852690L
+ >>>
+
+::
+
+ Note: Notice the 'L' at the end of the output. The 'L' signifies that the
+ output of the operation is of type *long*. It was absent in the previous
+ example because we used the print statement. This is because *print* formats
+ the output before displaying.
+
+Eg 4:
+::
+
+ >>> big = 12345678901234567890 ** 3
+ >>> print big
+ 1881676372353657772490265749424677022198701224860897069000
+ >>>
+
+::
+
+ This example is to show that unlike in C or C++ there is no limit on the
+ value of an integer.
+
+Try this on the interactive interpreter:
+``import this``
+
+*Hint: The output gives an idea of Power of Python*
+
+*ipython* - An enhanced interactive Python interpreter
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The power and the importance of the interactive interpreter was the highlight
+of the previous section. This section provides insight into the enhanced
+interpreter with more advanced set of features called **ipython**. Entering
+*ipython* at the shell prompt fires up the interactive interpreter.
+
+::
+
+ $ ipython
+ Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)
+ Type "copyright", "credits" or "license" for more information.
+
+ IPython 0.8.4 -- An enhanced Interactive Python.
+ ? -> Introduction and overview of IPython's features.
+ %quickref -> Quick reference.
+ help -> Python's own help system.
+ object? -> Details about 'object'. ?object also works, ?? prints more.
+
+ In [1]:
+
+This is the output obtained upon firing ipython. The exact appearance may
+change based on the Python version installed. The following are some of the
+various features provided by **ipython**:
+
+ Suggestions - ipython provides suggestions of the possible methods and
+ operations available for the given python object.
+
+Eg 5:
+
+::
+
+ In [4]: a = 6
+
+ In [5]: a.
+ a.__abs__ a.__divmod__ a.__index__ a.__neg__ a.__rand__ a.__rmod__ a.__rxor__
+ a.__add__ a.__doc__ a.__init__ a.__new__ a.__rdiv__ a.__rmul__ a.__setattr__
+ a.__and__ a.__float__ a.__int__ a.__nonzero__ a.__rdivmod__ a.__ror__ a.__str__
+ a.__class__ a.__floordiv__ a.__invert__ a.__oct__ a.__reduce__ a.__rpow__ a.__sub__
+ a.__cmp__ a.__getattribute__ a.__long__ a.__or__ a.__reduce_ex__ a.__rrshift__ a.__truediv__
+ a.__coerce__ a.__getnewargs__ a.__lshift__ a.__pos__ a.__repr__ a.__rshift__ a.__xor__
+ a.__delattr__ a.__hash__ a.__mod__ a.__pow__ a.__rfloordiv__ a.__rsub__
+ a.__div__ a.__hex__ a.__mul__ a.__radd__ a.__rlshift__ a.__rtruediv__
+
+In this example, we initialized 'a' (a variable - a concept that will be
+discussed in the subsequent sections.) to 6. In the next line when the *tab* key
+is pressed after typing '*a.*' ipython displays the set of all possible methods
+that are applicable on the object 'a' (an integer in this context). Ipython
+provides many such datatype specific features which will be presented in the
+further sections as and when the datatypes are introduced.
+
+Editing and running a python file
+=================================
+
+The previous sections focused on the use of the interpreter to run python code.
+While the interpeter is an excellent tool to test simple solutions and
+experiment with small code snippets, its main disadvantage is that everything
+written in the interpreter is lost once its quit. Most of the times a program is
+used by people other than the author. So the programs have to be available in
+some form suitable for distribution, and hence they are written in files. This
+section will focus on editing and running python files. Start by opening a text
+editor ( it is recommended you choose one from the list at the top of this page ).
+In the editor type down python code and save the file with an extension **.py**
+(python files have an extension of .py). Once done with the editing, save the
+file and exit the editor.
+
+Let us look at a simple example of calculating the gcd of 2 numbers using Python:
+
+**Creating the first python script(file)**
+::
+
+ $ emacs gcd.py
+ def gcd(x,y):
+ if x % y == 0:
+ return y
+ return gcd(y, x%y)
+
+ print gcd(72, 92)
+
+To run the script, open the shell prompt, navigate to the directory that
+contains the python file and run ``python <filename.py>`` at the prompt ( in this
+case filename is gcd.py )
+
+**Running the python script**
+::
+
+ $ python gcd.py
+ 4
+ $
+
+Another method to run a python script would be to include the line
+
+``#! /usr/bin/python``
+
+at the beginning of the python file and then make the file executable by
+
+$ chmod a+x *filename.py*
+
+Once this is done, the script can be run as a standalone program as follows:
+
+$ ./*filename.py*
+
+Basic Datatypes and operators in Python
+=======================================
+
+Python provides the following set of basic datatypes.
+
+ * Numbers: int, float, long, complex
+ * Strings
+ * Boolean
+
+Numbers
+~~~~~~~
+
+Numbers were introduced in the examples presented in the interactive interpreter
+section. Numbers include types as mentioned earlier viz., int (integers), float
+(floating point numbers), long (large integers), complex (complex numbers with
+real and imaginary parts). Python is not a strongly typed language, which means
+the type of a variable need not mentioned during its initialization. Let us look
+at a few examples.
+
+Eg 6:
+::
+
+ >>> a = 1 #here a is an integer variable
+
+Eg 7:
+::
+
+ >>> lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long
+ >>> lng
+ 122333444455555666666777777788888888999999999L #notice the trailing 'L'
+ >>> print lng
+ 122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L'
+ >>> lng+1
+ 122333444455555666666777777788888889000000000L
+
+
+Long numbers are the same as integers in almost all aspects. They can be used in
+operations just like integers and along with integers without any distinction.
+The only distinction comes during type checking (which is not a healthy practice).
+Long numbers are tucked with a trailing 'L' just to signify that they are long.
+Notice that in the example just lng at the prompt displays the value of the variable
+with the 'L' whereas ``print lng`` displays without the 'L'. This is because print
+formats the output before printing. Also in the example, notice that adding an
+integer to a long does not give any errors and the result is as expected. So for
+all practical purposes longs can be treated as ints.
+
+Eg 8:
+::
+
+ >>> fl = 3.14159 #fl is a float variable
+ >>> e = 1.234e-4 #e is also a float variable, specified in the exponential form
+ >>> a = 1
+ >>> b = 2
+ >>> a/b #integer division
+ 0
+ >>> a/fl #floating point division
+ 0.31831015504887655
+ >>> e/fl
+ 3.9279473133031364e-05
+
+
+Floating point numbers, simply called floats are real numbers with a decimal point.
+The example above shows the initialization of a float variable. Shown also in this
+example is the difference between integer division and floating point division.
+'a' and 'b' here are integer variables and hence the division gives 0 as the quotient.
+When either of the operands is a float, the operation is a floating point division,
+and the result is also a float as illustrated.
+
+Eg 9:
+::
+
+ >>> cplx = 3 + 4j #cplx is a complex variable
+ >>> cplx
+ (3+4j)
+ >>> print cplx.real #prints the real part of the complex number
+ 3.0
+ >>> print cplx.imag #prints the imaginary part of the complex number
+ 4.0
+ >>> print cplx*fl #multiplies the real and imag parts of the complex number with the multiplier
+ (9.42477+12.56636j)
+ >>> abs(cplx) #returns the absolute value of the complex number
+ 5.0
+
+Python provides a datatype for complex numbers. Complex numbers are initialized
+as shown in the example above. The *real* and *imag* operators return the real and
+imaginary parts of the complex number as shown. The *abs()* returns the absolute
+value of the complex number.
+
+Variables
+~~~~~~~~~
+
+Variables are just names that represent a value. Variables have already been
+introduced in the various examples from the previous sections. Certain rules about
+using variables:
+
+ * Variables have to be initialized or assigned a value before being used.
+ * Variable names can consist of letters, digits and underscores(_).
+ * Variable names cannot begin with digits, but can contain digits in them.
+
+In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx'
+are all variables of various datatypes.
+
+::
+
+ Note: Python is not a strongly typed language and hence an integer variable can at a
+ later stage be used as a float variable as well.
+
+Strings
+~~~~~~~
+
+Strings are one of the essential data structures of any programming language.
+The ``print "Hello, World!"`` program was introduced in the earlier section, and
+the *"Hello, World!"* in the print statement is a string. A string is basically
+a set of characters. Strings can be represented in various ways shown below:
+
+::
+
+ s = 'this is a string' # a string variable can be represented using single quotes
+ s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown
+ s = "I have 'single-quotes' inside!"
+ l = "A string spanning many lines\
+ one more line\
+ yet another" # a string can span more than a single line.
+ t = """A triple quoted string does # another way of representing multiline strings.
+ not need to be escaped at the end and
+ "can have nested quotes" etc."""
+
+Try the following on the interpreter:
+``s = 'this is a string with 'quotes' of similar kind'``
+
+**Exercise: How to use single quotes within single quotes in a string as shown
+in the above example without getting an error?**
+
+String operations
+-----------------
+
+A few basic string operations are presented here.
+
+**String concatenation**
+String concatenation is done by simple addition of two strings.
+
+::
+
+ >>> x = 'Hello'
+ >>> y = ' Python'
+ >>> print x+y
+ Hello Python
+
+*Try this yourself:*
+
+::
+
+ >>> somenum = 13
+ >>> print x+somenum
+
+The problem with the above example is that here a string variable and an integer
+variable are trying to be concantenated. To obtain the desired result from the
+above example the str(), repr() and the `` can be used.
+
+**str()** simply converts a value to a string in a reasonable form.
+**repr()** creates a string that is a representation of the value.
+
+The difference can be seen in the example shown below:
+
+::
+
+ >>> str(1000000000000000000000000000000000000000000000000L)
+ '1000000000000000000000000000000000000000000000000'
+ >>> repr(1000000000000000000000000000000000000000000000000L)
+ '1000000000000000000000000000000000000000000000000L'
+
+It can be observed that the 'L' in the long value shown was omitted by str(),
+whereas repr() converted that into a string too. An alternative way of using
+repr(value) is ```value```.
+
+A few more examples:
+::
+
+ >>> x = "Let's go \nto Pycon"
+ >>> print x
+ Let's go
+ to Pycon
+
+In the above example, notice that the '\n'(newline) character is formatted and
+the string is printed on two lines. The strings discussed until now were normal
+strings. Other than these there are two other types of strings namely, raw strings
+and unicode strings.
+
+**Raw strings** are strings which are unformatted, that is the backslashes(\) are
+not parsed and are left as it is in the string. Raw strings are represented with
+an 'r' at the start of a string.
+Let us look at an example
+
+::
+
+ >>> x = r"Let's go \nto Pycon"
+ >>> print x
+ Let's go \nto Pycon
+
+Note: The '\n' is not being parsed into a new line and is left as it is.
+
+*Try this yourself:*
+
+::
+
+ >>> x = r"Let's go to Pycon\"
+
+**Unicode strings** are strings where the characters are Unicode characters as
+opposed to ASCII characters. Unicode strings are represented with a 'u' at the
+start of the string.
+Let us look at an example:
+
+::
+
+ >>> x = u"Let's go to Pycon!"
+ >>> print x
+ Let's go to Pycon!
+
+Boolean
+~~~~~~~
+
+Python also provides special Boolean datatype. A boolean variable can assume a
+value of either *True* or *False* (Note the capitalizations).
+
+Let us look at examples:
+
+::
+
+ >>> t = True
+ >>> f = not t
+ >>> print f
+ False
+ >>> f or t
+ True
+ >>> f and t
+ False
+
+The **while** loop
+==================
+
+
+The Python **while** loop is similar to the C/C++ while loop. The syntax is as
+follows:
+
+::
+
+ statement 0
+ while condition:
+ statement 1 #while block
+ statement 2 #while block
+ statement 3 #outside the while block.
+
+Let us look at an example:
+
+::
+
+ >>> x = 1
+ >>> while x <= 5:
+ ... print x
+ ... x += 1
+ ...
+ 1
+ 2
+ 3
+ 4
+ 5
+
+The **if** conditional
+======================
+
+The Python **if** block provides the conditional execution of statements.
+If the condition evaluates as true the block of statements defined under the if
+block are executed.
+
+If the first block is not executed on account of the condition not being satisfied,
+the set of statements in the **else** block are executed.
+
+The **elif** block provides the functionality of evaluation of multiple conditions
+as shown in the example.
+
+The syntax is as follows:
+
+::
+
+ if condition :
+ statement_1
+ statement_2
+
+ elif condition:
+ statement_3
+ statement_4
+ else:
+ statement_5
+ statement_6
+
+Let us look at an example:
+
+::
+
+ >>> n = raw_input("Input a number:")
+ >>> if n < 0:
+ print n," is negative"
+ elif n > 0:
+ print n," is positive"
+ else:
+ print n, " is 0"
+
+**raw_input()**
+===============
+
+In the previous example we saw the call to the raw_input() subroutine.
+The **raw_input()** method is used to take user inputs through the console.
+Unlike **input()** which assumes the data entered by the user as a standard python
+expression, **raw_input()** treats all the input data as raw data and converts
+everything into a string. To illustrate this let us look at an example.
+
+::
+
+ >>> input("Enter a number thats a palindrome:")
+ Enter a number thats a palindrome:121
+ 121
+
+ >>> input("Enter your name:")
+ Enter your name:PythonFreak
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ File "<string>", line 1, in <module>
+ NameError: name 'PythonFreak' is not defined
+
+As shown above the **input()** assumes that the data entered is a valid Python
+expression. In the first call it prompts for an integer input and when entered
+it accepts the integer as an integer, whereas in the second call, when the string
+is entered without the quotes, **input()** assumes that the entered data is a valid
+Python expression and hence it raises and exception saying PythonFreak is not
+defined.
+
+::
+
+ >>> input("Enter your name:")
+ Enter your name:'PythonFreak'
+ 'PythonFreak'
+ >>>
+
+Here the name is accepted because its entered as a string (within quotes). But
+its unreasonable to go on using quotes each time a string is entered. Hence the
+alternative is to use **raw_input()**.
+
+Let us now look at how **raw_input()** operates with an example.
+
+::
+
+ >>> raw_input("Enter your name:")
+ Enter your name:PythonFreak
+ 'PythonFreak'
+
+Observe that the **raw_input()** is converting it into a string all by itself.
+
+::
+
+ >>> pal = raw_input("Enter a number thats a palindrome:")
+ Enter a number thats a palindrome:121
+ '121'
+
+Observe that **raw_input()** is converting the integer 121 also to a string as
+'121'. Let us look at another example:
+
+::
+
+ >>> pal = raw_input("Enter a number thats a palindrome:")
+ Enter a number thats a palindrome:121
+ >>> pal + 2
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ TypeError: cannot concatenate 'str' and 'int' objects
+ >>> pal
+ '121'
+
+Observe here that the variable *pal* is a string and hence integer operations
+cannot be performed on it. Hence the exception is raised.
+
+**int()** method
+================
+
+Generally for computing purposes, the data used is not strings or raw data but
+on integers, floats and similar mathematical data structures. The data obtained
+from **raw_input()** is raw data in the form of strings. In order to obtain integers
+from strings we use the method **int()**.
+
+Let us look at an example.
+
+::
+
+ >>> intpal = int(pal)
+ >>> intpal
+ 121
+
+In the previous example it was observed that *pal* was a string variable. Here
+using the **int()** method the string *pal* was converted to an integer variable.
+
+*Try This Yourself:*
+
+::
+
+ >>> stringvar = raw_input("Enter a name:")
+ Enter a name:Guido Van Rossum
+ >>> stringvar
+ 'Guido Van Rossum'
+ >>> numvar = int(stringvar)
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/basic_python/list_tuples.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,526 @@
+Lists and Tuples
+================
+
+Lists
+-----
+
+Python provides an intuitive way to represent a group items, called *Lists*. The
+items of a *List* are called its elements. Unlike C/C++, elements can be of any
+type. A *List* is represented as a list of comma-sepated elements with square
+brackets around them::
+
+ >>> a = [10, 'Python programming', 20.3523, 23, 3534534L]
+ >>> a
+ [10, 'Python programming', 20.3523, 23, 3534534L]
+
+
+Common List Operations
+~~~~~~~~~~~~~~~~~~~~~~
+
+The following are some of the most commonly used operations on *Lists*.
+
+
+~~~~~~~~
+Indexing
+~~~~~~~~
+
+Individual elements of a *List* can be accessed using an index to the element.
+The indices start at 0. One can also access the elements of the *List* in reverse
+using negative indices.::
+
+ >>> a[1]
+ 'Python programming'
+ >>> a[-1]
+ 3534534L
+
+It is important to note here that the last element of the *List* has an index of
+-1.
+
+~~~~~~~~~~~~~
+Concatenating
+~~~~~~~~~~~~~
+
+Two or more *Lists* can be concatenated using the + operator::
+
+ >>> a + ['foo', 12, 23.3432, 54]
+ [10, 'Python programming', 20.3523, 'foo', 12, 23.3432, 54]
+ >>> [54, 75, 23] + ['write', 67, 'read']
+ [54, 75, 23, 'write', 67, 'read']
+
+
+~~~~~~~
+Slicing
+~~~~~~~
+
+A *List* can be sliced off to contain a subset of elements of the *List*. Slicing
+can be done by using two indices separated by a colon, where the first index is
+inclusive and the second index is exclusive. The resulting slice is also a *List*.::
+
+ >>> num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ >>> num[3:6]
+ [4, 5, 6]
+ >>> num[0:1]
+ [1]
+ >>> num[7:10]
+ [7, 8, 9]
+
+The last example showed how to access last 3 elements of the *List*. There is a
+small catch here. The second index 10 actually refers to the 11th element of the
+*List* which is still valid, even though it doesn't exist because the second
+index is exclusive and tells the Python interpreter to get the last element of
+the *List*. But this can also be done in a much easier way using negative indices::
+
+ >>> num[-3:-1]
+ [7, 8, 9]
+
+Excluding the first index implies that the slice must start at the beginning of
+the *List*, while excluding the second index includes all the elements till the
+end of the *List*. A third parameter to a slice, which is implicitly taken as 1
+is the step of the slice. It is specified as a value which follows a colon after
+the second index::
+
+ >>> num[:4]
+ [1, 2, 3, 4]
+ >>> num[7:]
+ [8, 9]
+ >>> num[-3:]
+ [7, 8, 9]
+ >>> num[:]
+ [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ >>> num[4:9:3]
+ [5, 8]
+ >>> num[3::2]
+ [4, 6, 8]
+ >>> num[::4]
+ [1, 5, 9]
+
+
+~~~~~~~~~~~~~~
+Multiplication
+~~~~~~~~~~~~~~
+
+
+A *List* can be multiplied with an integer to repeat itself::
+
+ >>> [20] * 5
+ [20, 20, 20, 20, 20]
+ >>> [42, 'Python', 54] * 3
+ [42, 'Python', 54, 42, 'Python', 54, 42, 'Python', 54]
+
+
+~~~~~~~~~~
+Membership
+~~~~~~~~~~
+
+**in** operator is used to find whether an element is part of the *List*. It
+returns **True** if the element is present in the *List* or **False** if it is not
+present. Since this operator returns a Boolean value it is called a Boolean
+operator::
+
+ >>> names = ['Guido', 'Alex', 'Tim']
+ >>> 'Tim' in names
+ True
+ >>> 'Adam' in names
+ False
+
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Length, Maximum and Minimum
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Length of a *List* can be found out using the len function. The max function
+returns the element with the largest value and the min function returns the
+element with the smallest value::
+
+ >>> num = [4, 1, 32, 12, 67, 34, 65]
+ >>> len(num)
+ 7
+ >>> max(num)
+ 67
+ >>> min(num)
+ 1
+
+
+~~~~~~~~~~~~~~~~~
+Changing Elements
+~~~~~~~~~~~~~~~~~
+
+Unlike Strings *Lists* are mutable, i.e. elements of a *List* can be manipulated::
+
+ >>> a = [1, 3, 5, 7]
+ >>> a[2] = 9
+ >>> a
+ [1, 3, 9, 7]
+
+
+~~~~~~~~~~~~~~~~~
+Deleting Elements
+~~~~~~~~~~~~~~~~~
+
+An element or a slice of a *List* can be deleted by using the **del** statement::
+
+ >>> a = [1, 3, 5, 7, 9, 11]
+ >>> del a[-2:]
+ >>> a
+ [1, 3, 5, 7]
+ >>> del a[1]
+ >>> a
+ [1, 5, 7]
+
+
+~~~~~~~~~~~~~~~~
+Assign to Slices
+~~~~~~~~~~~~~~~~
+
+In the same way, values can be assigned to individual elements of the *List*,
+a *List* of elements can be assigned to a slice::
+
+ >>> a = [2, 3, 4, 5]
+ >>> a[:2] = [0, 1]
+ [0, 1, 4, 5]
+ >>> a[2:2] = [2, 3]
+ >>> a
+ [0, 1, 2, 3, 4, 5]
+ >>> a[2:4] = []
+ >>> a
+ [0, 1, 4, 5]
+
+The last two examples should be particularly noted carefully. The last but one
+example insert elements or a list of elements into a *List* and the last example
+deletes a list of elements from the *List*.
+
+
+None, Empty Lists, and Initialization
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+An *Empty List* is a *List* with no elements and is simply represented as
+[]. A *None List* is one with all elements in it being **None**. It serves
+the purpose having a container list of some fixed number of elements with
+no value::
+
+ >>> a = []
+ >>> a
+ []
+ >>> n = [None] * 10
+ >>> n
+ [None, None, None, None, None, None, None, None, None, None]
+
+
+Nested Lists
+~~~~~~~~~~~~
+
+As mentioned earlier, a List can contain elements of any data type. This also
+implies a *List* can have a *Lists* themselves as its elements. These are
+called as *Nested Lists*. There is no limit on the depth of the *Nested Lists*::
+
+ >>> a = [1, [1, 2, 3], 3, [1, [1, 2, 3]], 7]
+
+
+List Methods
+~~~~~~~~~~~~
+
+A method is a function that is coupled to an object. More about objects
+and its methods are discussed in Advanced Python module. In general, a
+method is called like::
+
+ object.method(arguments)
+
+For now, it is enough to know that a list of elements is an object and
+so *List* methods can be called upon them. Also some of the methods change
+the *List* in-place, meaning it modifies the existing list instead of creating
+a new one, while other methods don't. It must be noted as we run through
+the *List* methods.
+
+Some of the most commonly used *List* methods are as follows:
+
+
+~~~~~~
+append
+~~~~~~
+
+The *append* method is used to append an object at the end of the list::
+
+ >>> prime = [2, 3, 5]
+ >>> prime.append(7)
+ >>> prime
+ [2, 3, 5, 7]
+
+It is important to note that append changes the *List* in-place.
+
+
+~~~~~
+count
+~~~~~
+
+The *count* method returns the number of occurences of a particular element
+in a list::
+
+ >>> [1, 4, 4, 9, 9, 9].count(9)
+ 3
+ >>> tlst = ['Python', 'is', 'a', 'beautiful', 'language']
+ >>> tlst.count('Python')
+ 1
+
+
+~~~~~~
+extend
+~~~~~~
+
+The *extend* method extends the list on which it is called by the list supplied
+as argument to it::
+
+ >>> a = [1, 2, 3]
+ >>> b = [4, 5, 6]
+ >>> a.extend(b)
+ [1, 2, 3, 4, 5, 6]
+
+This is an in-place method. This method is equivalent to using the + operator, but
+using the + operator returns a new list.
+
+
+~~~~~
+index
+~~~~~
+
+The *index* method returns the index position of the element in the list
+specified as argument::
+
+ >>> a = [1, 2, 3, ,4, 5]
+ >>> a.index(4)
+ 3
+
+
+~~~~~~
+insert
+~~~~~~
+
+The *insert* method is used to insert an element specified as the second
+argument to the list at the position specified by the first argument::
+
+ >>> a = ['Python', 'is', 'cool']
+ >>> a.insert(2, 'so')
+ >>> a
+ ['Python', 'is', 'so', 'cool']
+
+The *insert* method changes the *List* in-place.
+
+
+~~~
+pop
+~~~
+
+The *pop* method removes an element from the list. The index position
+of the element to be removed can be specified as an argument to the
+*pop* method, if not it removes the last element by default::
+
+ >>> a = [1, 2, 3, 4, 5]
+ >>> a.pop()
+ >>> a
+ 5
+ >>> a.pop(2)
+ >>> a
+ 3
+
+The *pop* method changes the *List* in-place.
+
+
+~~~~~~
+remove
+~~~~~~
+
+The *remove* method removes the first occurence of an element supplied as a
+parameter::
+
+ >>> a = [1, 2, 3, 4, 2, 5, 2]
+ >>> a.remove(2)
+ >>> a
+ [1, 3, 4, 2, 5, 2]
+
+
+~~~~~~~
+reverse
+~~~~~~~
+
+The *reverse* method reverses elements in the list. It is important to note
+here that *reverse* method changes the list in-place and doesn't return any
+thing::
+
+ >>> a = ['guido', 'alex', 'tim']
+ >>> a.reverse()
+ >>> a
+ ['tim', 'alex', 'guido']
+
+
+~~~~
+sort
+~~~~
+
+The *sort* method is used to sort the elements of the list. The *sort* method
+also sorts in-place and does not return anything::
+
+ >>> a = [5, 1, 3, 7, 4]
+ >>> a.sort()
+ >>> a
+ [1, 3, 4, 5, 7]
+
+In addition to the sort method on a *List* object we can also use the built-in
+**sorted** function. This function takes the *List* as a parameter and returns
+a sorted copy of the list. However the original list is left intact::
+
+ >>> a = [5, 1, 3, 7, 4]
+ >>> b = sorted(a)
+ >>> b
+ [1, 3, 4, 5, 7]
+ >>> a
+ [5, 1, 3, 7, 4]
+
+
+Tuples
+------
+
+*Tuples* are sequences just like *Lists*, but they are immutable. In other
+words *Tuples* provides a way to represent a group of items, where the group
+of items cannot be changed in any way. The syntax of a *Tuple* is also very
+similar to *List*. A *Tuple* is represented with the list of items, called
+elements of the *Tuple* separated by comma, with the entire list being enclosed
+in parenthesis. It is not compulsory to use parenthesis around a *Tuple* but
+it may be necessary in some of the cases::
+
+ >>> a = 1, 2, 3
+ >>> a
+ (1, 2, 3)
+ >>> b = 1,
+ >>> b
+ (1,)
+
+It is interesting to note the second example. Just a value followed by a comma
+automatically makes that an element of a *Tuple* with only one element. It is
+also important to note that, irrespective of input having a parenthesis, the
+output always has a parenthesis.
+
+The first example is also known as *Tuple packing*, because values are being
+packed into a tuple. It is also possible to do *Tuple unpacking* which is more
+interesting. It is better to understand that by example. Say we have a
+co-ordinate pair from which we need to separate x and y co-ordinates::
+
+ >>> a = (1, 2)
+ >>> x, y = a
+ >>> x
+ 1
+ >>> y
+ 2
+
+*Tuple unpacking* also has several other use-cases of which the most interesting
+one is to swap the values of two variables. Using programming languages like C
+would require anywhere around 10 lines of code and an extra temporary variable
+to do this (including all the #include stuff). Python does it in the most
+intuitive way in just one line. Say we want to swap the co-ordinates in the
+above example::
+
+ >>> x, y = y, x
+ >>> x
+ 2
+ >>> y
+ 1
+
+Common Tuple Operations
+~~~~~~~~~~~~~~~~~~~~~~~
+
+There is no need to introduce all the *Tuple* operations again, since *Tuples*
+support the following operations that *List* supports in exactly the same way:
+
+ * Indexing
+ * Concatenating
+ * Slicing
+ * Membership
+ * Multiplication
+ * Length, Maximum, Minimum
+
+The following examples illustrate the above operations::
+
+ >>> a = (1, 2, 3, 4, 5, 6)
+ >>> a[5]
+ 6
+ >>> b = (7, 8, 9)
+ >>> a + b
+ (1, 2, 3, 4, 5, 6, 7, 8, 9)
+ >>> a[3:5]
+ (4, 5)
+ >>> 5 in a
+ True
+ >>> c = (1,)
+ >>> c * 5
+ (1, 1, 1, 1, 1)
+ >>> len(a)
+ 6
+ >>> max(a)
+ 6
+ >>> min(a)
+ 1
+
+However the following *List* operations are not supported by *Tuples* because
+*Tuples* cannot be changed once they are created:
+
+ * Changing elements
+ * Deleting elements
+ * Assigning to slices
+
+Similarity to *Lists* leads to the questions like, why not *Lists* only? Why do
+we even want *Tuples*? Can we do the same with *Lists*? And the answer is **Yes**
+we can do it, but *Tuples* are helpful at times, like we can return Tuples from
+functions. They are also returned by some built-in functions and methods. And
+also there are some use cases like co-ordinate among other things. So *Tuples*
+are helpful.
+
+Additional Syntax
+-----------------
+
+The following additional syntax are introduced to make it easier to operate on
+*Lists*.
+
+range()
+~~~~~~~
+
+The *range* function takes at least one argument and 2 additional optional
+arguments. If two or more arguments are specified, the range function returns
+a list of natural numbers starting from the first argument passed to it to the
+second argument. The third argument, if specified is used as a step. Suppose
+only one argument is specified, then *range* function returns a list of natural
+numbers starting from 0 upto the argument specified::
+
+ >>> range(5, 10, 2)
+ [5, 7, 9]
+ >>> range(2, 15)
+ [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
+ >>> range(12)
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
+
+for
+~~~
+
+The **for** keyword is used as a part of the looping construct. Unlike for loops
+in other languages, Python's for is used to iterate through the elements of
+sequences like *Lists*, *Tuples*, *Dictionaries*, etc. The syntax of the for loop
+consists of **for**, followed by a variable to hold the individual or the current
+element of the list during iteration and **in**, followed by the sequence and a
+semicolon(':') The next line which is part of the **for** loop, i.e the statements
+that are part of the loop should start with a new intend::
+
+ >>> names = ['Guido', 'Alex', 'Tim']
+ >>> for name in names:
+ ... print "Name =", name
+ ...
+ Name = Guido
+ Name = Alex
+ Name = Tim
+
+
+Conclusion
+----------
+
+This section on *Lists* and *Tuples* introduces almost all the necessary
+machinary required to work on *Lists* and *Tuples*. Topics like how to
+use these data structures in bigger more useful programs will be introduced
+in the subsequent chapters.
+
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/basic_python/oop.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,72 @@
+Classes and Objects
+===================
+
+In the previous sections we learnt about functions which provide certain level
+of abstraction to our code by holding the code which performs one or more
+specific functionalities. We were able to use this function as many times as we
+wanted. In addition to functions, Python also higher level of abstractions
+through *Classes* and *Objects*. *Objects* can be loosely defined as a
+collection of a set of data items and a set of methods. The data items can be
+any valid Python variable or any Python object. Functions enclosed within a class
+are called as *methods*. If you are thinking if methods are functions why is there
+a distinction between the two? The answer to this will be given as we walk through
+the concepts of *Classes* and *Objects*. *Classes* contain the definition for the
+*Objects*. *Objects* are instances of *Classes*.
+
+A class is defined using the keyword **class** followed by the class name, in
+turn followed by a semicolon. The statements that a *Class* encloses are written
+in a new block, i.e on the next indentation level::
+
+ class Employee:
+ def setName(self, name):
+ self.name = name
+
+ def getName(self):
+ return self.name
+
+In the above example, we defined a class with the name Employee. We also defined
+two methods, setName and getName for this class. It is important to note the
+differences between the normal Python functions and class methods defined above.
+Each method of the class must take the same instance of the class(object) from
+which it was called as the first argument. It is conventionally given the name,
+*self*. Note that *self* is only a convention. You can use any other name, but
+the first argument to the method will always be the same object of the class
+from which the method was called. The data memebers that belong to the class are
+called as *class attributes*. *Class attributes* are preceded by the object of
+the class and a dot. In the above example, *name* is a class attribute since it
+is preceded by the *self* object. *Class attributes* can be accessed from
+anywhere within the class.
+
+We can create objects of a class outside the class definition by using the same
+syntax we use to call a function with no parameters. We can assign this object
+to a variable::
+
+ emp = Employee()
+
+In the above example, we create an object named *emp* of the class *Employee*.
+All the attributes and methods of the class can be accessed by the object of the
+class using the standard notation *object.attribute* or *object.method()*.
+Although the first parameter of a class method is the self object, it must not
+be passed as an argument when calling the method. The *self* object is implicitly
+passed to the method by the Python interpreter. All other arguments passing rules
+like default arguments, keyword arguments, argument packing and unpacking follow
+the same rules as those for ordinary Python functions::
+
+ >>> emp.setName('John')
+ >>> name = emp.getName()
+ >>> print name
+ John
+ >>> print emp.name
+ John
+
+If we at all try to access a class attribute before assigning a value to it, i.e
+before creating it, Python raises the same error as it would raise for the
+accessing undefined variable::
+
+ >>> emp = Employee()
+ >>> emp.name
+ Traceback (most recent call last):
+ File "class.py", line 10, in <module>
+ print e.name
+ AttributeError: Employee instance has no attribute 'name'
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/basic_python/strings_dicts.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,475 @@
+=======
+Strings
+=======
+
+Strings were briefly introduced previously in the introduction document. In this
+section strings will be presented in greater detail. All the standard operations
+that can be performed on sequences such as indexing, slicing, multiplication, length
+minimum and maximum can be performed on string variables as well. One thing to
+be noted is that strings are immutable, which means that string variables are
+unchangeable. Hence, all item and slice assignments on strings are illegal.
+Let us look at a few example.
+
+::
+
+ >>> name = 'PythonFreak'
+ >>> print name[3]
+ h
+ >>> print name[-1]
+ k
+ >>> print name[6:]
+ Freak
+ >>> name[6:0] = 'Maniac'
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ TypeError: 'str' object does not support item assignment
+
+This is quite expected, since string objects are immutable as already mentioned.
+The error message is clear in mentioning that 'str' object does not support item
+assignment.
+
+String Formatting
+=================
+
+String formatting can be performed using the string formatting operator represented
+as the percent (%) sign. The string placed before the % sign is formatted with
+the value placed to the right of it. Let us look at a simple example.
+
+::
+
+ >>> format = 'Hello %s, from PythonFreak'
+ >>> str1 = 'world!'
+ >>> print format % str1
+ Hello world!, from PythonFreak
+
+The %s parts of the format string are called the coversion specifiers. The coversion
+specifiers mark the places where the formatting has to be performed in a string.
+In the example the %s is replaced by the value of str1. More than one value can
+also be formatted at a time by specifying the values to be formatted using tuples
+and dictionaries (explained in later sections). Let us look at an example.
+
+::
+
+ >>> format = 'Hello %s, from %s'
+ >>> values = ('world!', 'PythonFreak')
+ >>> print format % values
+ Hello world!, from PythonFreak
+
+In this example it can be observed that the format string contains two conversion
+specifiers and they are formatted using the tuple of values as shown.
+
+The s in %s specifies that the value to be replaced is of type string. Values of
+other types can be specified as well such as integers and floats. Integers are
+specified as %d and floats as %f. The precision with which the integer or the
+float values are to be represented can also be specified using a **.** (**dot**)
+followed by the precision value.
+
+String Methods
+==============
+
+Similar to list methods, strings also have a rich set of methods to perform various
+operations on strings. Some of the most important and popular ones are presented
+in this section.
+
+**find**
+~~~~~~~~
+
+The **find** method is used to search for a substring within a given string. It
+returns the left most index of the first occurence of the substring. If the
+substring is not found in the string then it returns -1. Let us look at a few
+examples.
+
+::
+
+ >>> longstring = 'Hello world!, from PythonFreak'
+ >>> longstring.find('Python')
+ 19
+ >>> longstring.find('Perl')
+ -1
+
+**join**
+~~~~~~~~
+
+The **join** method is used to join the elements of a sequence. The sequence
+elements that are to be join ed should all be strings. Let us look at a few
+examples.
+
+::
+
+ >>> seq = ['With', 'great', 'power', 'comes', 'great', 'responsibility']
+ >>> sep = ' '
+ >>> sep.join(seq)
+ 'With great power comes great responsibility'
+ >>> sep = ',!'
+ >>> sep.join(seq)
+ 'With,!great,!power,!comes,!great,!responsibility'
+
+*Try this yourself*
+
+::
+
+ >>> seq = [12,34,56,78]
+ >>> sep.join(seq)
+
+**lower**
+~~~~~~~~~
+
+The **lower** method, as the name indicates, converts the entire text of a string
+to lower case. It is specially useful in cases where the programmers deal with case
+insensitive data. Let us look at a few examples.
+
+::
+
+ >>> sometext = 'Hello world!, from PythonFreak'
+ >>> sometext.lower()
+ 'hello world!, from pythonfreak'
+
+**replace**
+~~~~~~~~~~~
+
+The **replace** method replaces a substring with another substring within
+a given string and returns the new string. Let us look at an example.
+
+::
+
+ >>> sometext = 'Concise, precise and criticise is some of the words that end with ise'
+ >>> sometext.replace('is', 'are')
+ 'Concaree, precaree and criticaree are some of the words that end with aree'
+
+Observe here that all the occurences of the substring *is* have been replaced,
+even the *is* in *concise*, *precise* and *criticise* have been replaced.
+
+**split**
+~~~~~~~~~
+
+The **split** is one of the very important string methods. split is the opposite of the
+**join** method. It is used to split a string based on the argument passed as the
+delimiter. It returns a list of strings. By default when no argument is passed it
+splits with *space* (' ') as the delimiter. Let us look at an example.
+
+::
+
+ >>> grocerylist = 'butter, cucumber, beer(a grocery item??), wheatbread'
+ >>> grocerylist.split(',')
+ ['butter', ' cucumber', ' beer(a grocery item??)', ' wheatbread']
+ >>> grocerylist.split()
+ ['butter,', 'cucumber,', 'beer(a', 'grocery', 'item??),', 'wheatbread']
+
+Observe here that in the second case when the delimiter argument was not set
+**split** was done with *space* as the delimiter.
+
+**strip**
+~~~~~~~~~
+
+The **strip** method is used to remove or **strip** off any whitespaces that exist
+to the left and right of a string, but not the whitespaces within a string. Let
+us look at an example.
+
+::
+
+ >>> spacedtext = " Where's the text?? "
+ >>> spacedtext.strip()
+ "Where's the text??"
+
+Observe that the whitespaces between the words have not been removed.
+
+::
+
+ Note: Very important thing to note is that all the methods shown above do not
+ transform the source string. The source string still remains the same.
+ Remember that **strings are immutable**.
+
+Introduction to the standard library
+====================================
+
+Python is often referred to as a "Batteries included!" language, mainly because
+of the Python Standard Library. The Python Standard Library provides an extensive
+set of features some of which are available directly for use while some require to
+import a few **modules**. The Standard Library provides various built-in functions
+like:
+
+ * **abs()**
+ * **dict()**
+ * **enumerate()**
+
+The built-in constants like **True** and **False** are provided by the Standard Library.
+More information about the Python Standard Library is available http://docs.python.org/library/
+
+
+I/O: Reading and Writing Files
+==============================
+
+Files are very important aspects when it comes to computing and programming.
+Up until now the focus has been on small programs that interacted with users
+through **input()** and **raw_input()**. Generally, for computational purposes
+it becomes necessary to handle files, which are usually large in size as well.
+This section focuses on basics of file handling.
+
+Opening Files
+~~~~~~~~~~~~~
+
+Files can be opened using the **open()** method. **open()** accepts 3 arguments
+out of which 2 are optional. Let us look at the syntax of **open()**:
+
+*f = open( filename, mode, buffering)*
+
+The *filename* is a compulsory argument while the *mode* and *buffering* are
+optional. The *filename* should be a string and it should be the complete path
+to the file to be opened (The path can be absolute or relative). Let us look at
+an example.
+
+::
+
+ >>> f = open ('basic_python/interim_assessment.rst')
+
+The *mode* argument specifies the mode in which the file has to be opened.
+The following are the valid mode arguments:
+
+**r** - Read mode
+**w** - Write mode
+**a** - Append mode
+**b** - Binary mode
+**+** - Read/Write mode
+
+The read mode opens the file as a read-only document. The write mode opens the
+file in the Write only mode. In the write mode, if the file existed prior to the
+opening, the previous contents of the file are erased. The append mode opens the
+file in the write mode but the previous contents of the file are not erased and
+the current data is appended onto the file.
+The binary and the read/write modes are special in the sense that they are added
+onto other modes. The read/write mode opens the file in the reading and writing
+mode combined. The binary mode can be used to open a files that do not contain
+text. Binary files such as images should be opened in the binary mode. Let us look
+at a few examples.
+
+::
+
+ >>> f = open ('basic_python/interim_assessment.rst', 'r')
+ >>> f = open ('armstrong.py', 'r+')
+
+The third argument to the **open()** method is the *buffering* argument. This takes
+a boolean value, *True* or *1* indicates that buffering has to be enabled on the file,
+that is the file is loaded on to the main memory and the changes made to the file are
+not immediately written to the disk. If the *buffering* argument is *0* or *False* the
+changes are directly written on to the disk immediately.
+
+Reading and Writing files
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+**write()**
+-----------
+
+**write()**, evidently, is used to write data onto a file. It takes the data to
+be written as the argument. The data can be a string, an integer, a float or any
+other datatype. In order to be able to write data onto a file, the file has to
+be opened in one of **w**, **a** or **+** modes.
+
+**read()**
+----------
+
+**read()** is used to read data from a file. It takes the number of bytes of data
+to be read as the argument. If nothing is specified by default it reads the entire
+contents from the current position to the end of file.
+
+Let us look at a few examples:
+
+::
+
+ >>> f = open ('randomtextfile', 'w')
+ >>> f.write('Hello all, this is PythonFreak. This is a random text file.')
+ >>> f = open ('../randomtextfile', 'r')
+ >>> f = open ('../randomtextfile', 'r')
+ >>> f.read(5)
+ 'Hello'
+ >>> f.read()
+ ' all, this is PythonFreak. This is a random text file.'
+ >>> f.close()
+
+**readline()**
+--------------
+
+**readline()** is used to read a file line by line. **readline()** reads a line
+of a file at a time. When an argument is passed to **readline()** it reads that
+many bytes from the current line.
+
+One other method to read a file line by line is using the **read()** and the
+**for** construct. Let us look at this block of code as an example.
+
+::
+
+ >>> f = open('../randomtextfile', 'r')
+ >>> for line in f:
+ ... print line
+ ...
+ Hello all!
+
+ This is PythonFreak on the second line.
+
+ This is a random text file on line 3
+
+**close()**
+-----------
+
+One must always close all the files that have been opened. Although, files opened
+will be closed automatically when the program ends. When files opened in read mode
+are not closed it might lead to uselessly locked sometimes. In case of files
+opened in the write mode it is more important to close the files. This is because,
+Python maybe using the file in the buffering mode and when the file is not closed
+the buffer maybe lost completely and the changes made to the file are lost forever.
+
+
+Dictionaries
+============
+
+A dictionary in general, are designed to be able to look up meanings of words.
+Similarly, the Python dictionaries are also designed to look up for a specific
+key and retrieve the corresponding value. Dictionaries are data structures that
+provide key-value mappings. Dictionaries are similar to lists except that instead
+of the values having integer indexes, dictionaries have keys or strings as indexes.
+Let us look at an example of how to define dictionaries.
+
+::
+
+ >>> dct = { 'Sachin': 'Tendulkar', 'Rahul': 'Dravid', 'Anil': 'Kumble'}
+
+The dictionary consists of pairs of strings, which are called *keys* and their
+corresponding *values* separated by *:* and each of these *key-value* pairs are
+comma(',') separated and the entire structure wrapped in a pair curly braces *{}*.
+
+::
+
+ Note: The data inside a dictionary is not ordered. The order in which you enter
+ the key-value pairs is not the order in which they are stored in the dictionary.
+ Python has an internal storage mechanism for that which is out of the purview
+ of this document.
+
+**dict()**
+~~~~~~~~~~
+
+The **dict()** function is used to create dictionaries from other mappings or other
+dictionaries. Let us look at an example.
+
+::
+
+ >>> diction = dict(mat = 133, avg = 52.53)
+
+**String Formatting with Dictionaries:**
+
+String formatting was discussed in the previous section and it was mentioned that
+dictionaries can also be used for formatting more than one value. This section
+focuses on the formatting of strings using dictionaries. String formatting using
+dictionaries is more appealing than doing the same with tuples. Here the *keyword*
+can be used as a place holder and the *value* corresponding to it is replaced in
+the formatted string. Let us look at an example.
+
+::
+
+ >>> player = { 'Name':'Rahul Dravid', 'Matches':133, 'Avg':52.53, '100s':26 }
+ >>> strng = '%(Name)s has played %(Matches)d with an average of %(Avg).2f and has %(100s)d hundreds to his name.'
+ >>> print strng % player
+ Rahul Dravid has played 133 with an average of 52.53 and has 26 hundreds to his name.
+
+Dictionary Methods
+~~~~~~~~~~~~~~~~~~
+
+**clear()**
+-----------
+
+The **clear()** method removes all the existing *key-value* pairs from a dictionary.
+It returns *None* or rather does not return anything. It is a method that changes
+the object. It has to be noted here that dictionaries are not immutable. Let us
+look at an example.
+
+::
+
+ >>> dct
+ {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
+ >>> dct.clear()
+ >>> dct
+ {}
+
+**copy()**
+----------
+
+The **copy()** returns a copy of a given dictionary. Let us look at an example.
+
+::
+
+ >>> dct = {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
+ >>> dctcopy = dct.copy()
+ >>> dctcopy
+ {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
+
+
+**get()**
+---------
+
+**get()** returns the *value* for the *key* passed as the argument and if the
+*key* does not exist in the dictionary, it returns *None*. Let us look at an
+example.
+
+::
+
+ >>> print dctcopy.get('Saurav')
+ None
+ >>> print dctcopy.get('Anil')
+ Kumble
+
+**has_key()**
+-------------
+
+This method returns *True* if the given *key* is in the dictionary, else it returns
+*False*.
+
+::
+
+ >>> dctcopy.has_key('Saurav')
+ False
+ >>> dctcopy.has_key('Sachin')
+ True
+
+**pop()**
+---------
+
+This method is used to retrieve the *value* of a given *key* and subsequently
+remove the *key-value* pair from the dictionary. Let us look at an example.
+
+::
+
+ >>> print dctcopy.pop('Sachin')
+ Tendulkar
+ >>> dctcopy
+ {'Anil': 'Kumble', 'Rahul': 'Dravid'}
+
+**popitem()**
+-------------
+
+This method randomly pops a *key-value* pair from a dictionary and returns it.
+The *key-value* pair returned is removed from the dictionary. Let us look at an
+example.
+
+::
+
+ >>> print dctcopy.popitem()
+ ('Anil', 'Kumble')
+ >>> dctcopy
+ {'Rahul': 'Dravid'}
+
+ Note that the item chosen is completely random since dictionaries are unordered
+ as mentioned earlier.
+
+**update()**
+------------
+
+The **update()** method updates the contents of one dictionary with the contents
+of another dictionary. For items with existing *keys* their *values* are updated,
+and the rest of the items are added. Let us look at an example.
+
+::
+
+ >>> dctcopy.update(dct)
+ >>> dct
+ {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
+ >>> dctcopy
+ {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/latex/examples/final-include.tex Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,1 @@
+This is the part of the document that has been written into another file, for convenience. This was included in the main file.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/latex/examples/final.bib Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,20 @@
+@book{Lamport94,
+author = "Leslie Lamport",
+title = "A Document Preparation System: User's Guide and Reference",
+publisher = "Addison-Wesley Professional",
+year = "1994",
+edition = "second",
+note = "illustrations by Duane Bibby"
+}
+
+@book{Knuth84,
+author = "Donald Knuth",
+title = "The TeXbook",
+publisher = "Addison-Wesley",
+year = 1984,
+note = "illustrations by Duane Bibby"
+}
+
+
+
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/latex/examples/final.tex Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,199 @@
+%hello.tex - First LaTeX document
+\documentclass[11pt,a4paper,twoside]{article}
+
+\usepackage{graphicx}
+\usepackage{listings}
+\usepackage{amsmath}
+
+\lstset{language=Python, showstringspaces=false}
+\bibliographystyle{plain}
+
+\title{LaTeX - A Two Hour Introduction}
+\author{The FOSSEE Team}
+\date{August 2009}
+
+
+\begin{document}
+\maketitle
+\tableofcontents
+\listoftables
+\listoffigures
+\begin{abstract}
+This is a sample document to be used in the STTP course for a quick introduction to \LaTeX
+\end{abstract}
+\section{Introduction}
+LaTeX is a typesetting program used to produce excellently typeset documents. It is extensively used for producing high quality scientific and mathematical documents. It may also be used for producing other kinds of documents, ranging from simple one page articles or letters
+\section{Structural Elements}
+Let us now look at giving a better structure to our document.
+\subsection{documentclass}
+The \verb+documentclass+ variable tells \LaTeX, the type of document we wish to prepare.
+
+\subsection{Sections, Chapters and Parts}
+We shall first look at how to divide the document into Sections, Chapters and Parts.
+
+\subsubsection{Appendices}
+I can't tell you how to add an appendix, in the main document. Refer Appendix \ref{append} to see how to do it.
+
+\section{Text Typesetting}
+\begin{itemize}
+\item Now we move onto some elementary \emph{Text Typesetting}.
+
+\item How do we get \emph{emphasized or italic text}?
+
+\item \emph{Did you wonder what happens when we try \emph{emphasizing text} within \emph{emphasized text}}?
+
+\item ``Beautiful is better than ugly.''
+
+\item `In the face of ambiguity, refuse the temptation to guess.'
+
+\item LaTeX has 4 different types of dashes. The names of these dashes are: `-' hyphen, `--' en-dash, `---' em-dash and `$-$' minus sign. \footnote{We shall look at how to do math in a later section}
+
+\item \LaTeX has \verb+enumerate+, \verb+itemize+ and \verb+description+ commands to generate lists.
+
+\end{itemize}
+
+\begin{flushleft}This is left flushed text. \LaTeX normally produces text with no white space at the end of the line. But, this text isn't so, if you can see.\end{flushleft}
+\begin{flushright}Similarly, Right-aligned Text here\end{flushright}
+\begin{center} and centered text here.\end{center}
+
+\begin{description}
+ \item[Description] This list is a description list.
+ \item[Enumerate] Numbered lists are often useful.
+ \begin{enumerate}
+ \item First
+ \item Second
+ \item Third
+ \item \ldots
+ \end{enumerate}
+ \item[Itemize] The list above this description list is an itemize list.
+\end{description}
+
+\subsection{Quotes \& Verbatim Text}
+Since the \emph{Zen of Python} instructs that,
+\begin{quote}
+Readability counts.
+\end{quote}
+we use the \verb+quote+ environment to include quotes.
+
+\begin{verbatim}
+def signum( r ):
+ """returns 0 if r is zero
+ -1 if r is negative
+ +1 if r is positive"""
+ if r < 0:
+ return -1
+ elif r > 0:
+ return 1
+ else:
+ return 0
+\end{verbatim}
+
+\section{Tables \& Figures}
+
+\begin{table}[h]
+\caption{A simple table, on making tables}
+\centering
+\begin{tabular}{|c|c|}
+ \hline
+ \verb+l+ & left justified column content\\
+ \hline
+ \verb+r+ & right justified column content\\
+ \hline
+ \verb+c+ & centered column content\\
+ \hline
+ \verb+*{n}{col}+ & produces \verb+n+ columns with the\\
+ & \verb+col+ type of formatting\\
+ \cline{2-2}
+ &\verb+*{3}{c}+ is the same as \verb+{c c c}+ \\
+ \hline
+ \verb+|+ & produces a vertical line\\
+ \hline
+\end{tabular}
+\end{table}
+
+\begin{figure}
+\centering
+\caption[CTAN Lion]{CTAN lion drawing by Duane Bibby; thanks to www.ctan.org}
+\label{fig:lion}
+\includegraphics[scale=0.8, angle=30]{lion_orig.png}
+\end{figure}
+
+List of Tables and List of figures can be autogenerated suigng the \verb+\listoftables+ and \verb+\listoffigures+ commands. Let's insert them after the table of contents.
+
+Cross referencing is one of the best features of \LaTeX. The CTAN lion has the figure number \ref{fig:lion} and is on page number \pageref{fig:lion}
+
+It was drawn by Duane Bibby, a well-known commercial artist. He used this lion in the illustrations for Donald Knuth's original TeXbook\cite{Knuth84}, for Leslie Lamport's LaTeX book\cite{Lamport94}, and for other books having to do with TeX, so his work is familiar to everyone in the community.
+
+%% \begin{thebibliography}{99}
+%% \bibitem{Knuth84} Donald E. Knuth (1984). \emph{The TeXbook} (Computers and Typesetting, Volume A). Reading, Massachusetts: Addison-Wesley. ISBN 0-201-13448-9.
+
+%% \bibitem{Lamport94} Lamport, Leslie (1994). \emph{LaTeX: A document preparation system: User's guide and reference}.
+%% illustrations by Duane Bibby (2nd ed.). Reading, Mass: Addison-Wesley Professional.
+%% \end{thebibliography}
+
+\section{Typesetting Math}
+The equation $F=m \cdot a$ is an equation, that has been set inline.
+Equation \eqref{force} is the same equation typeset in the display style. Note, that it is also numbered.
+\begin{equation}
+\label{force}
+F=m\cdot a
+%%\tag{Fore-acceleration}
+\end{equation}
+More equations --- vertically aligned.
+
+\begin{align}
+\alpha^2 + \beta^2 &= \gamma^2 \\
+\sum_{i=1}^ni &= \frac{n(n+1)}{2}\\
+\sqrt{-1} &= \pm1 \nonumber \\
+y &= \frac{r_1^2-r_3^2-x^2+(x-i)^2+j^2}{2j} \nonumber \\
+ &= \frac{r_1^2-r_3^2+i^2+j^2}{2j}-\frac{i}{j}x \\
+\end{align}
+
+\begin{equation*}
+s(t) = \left\{
+ \begin{array}{rl}
+ 0 & \text{if } t \le 0\\
+ 1 & \text{if } t > 0
+ \end{array} \right.
+\end{equation*}
+
+\begin{equation*}
+\mathbf{X} = \left(
+ \begin{array}{ccc}
+ a_1 & a_2 & \ldots \\
+ b_1 & b_2 & \ldots \\
+ \vdots & \vdots & \ddots
+ \end{array} \right)
+\end{equation*}
+
+\begin{equation}
+ \begin{matrix}
+ 1 & 2 \\
+ 3 & 4
+ \end{matrix} \qquad \& \qquad
+ \begin{bmatrix}
+ 1 & 2 & 3 \\
+ 4 & 5 & 6 \\
+ 7 & 8 & 9
+ \end{bmatrix}
+\end{equation}
+
+\section{Miscellaneous}
+\subsection{Presentations}
+\subsection{Including Code}
+\begin{lstlisting}
+string="Hello, World! "
+for i in range(10):
+ print string*i
+\end{lstlisting}
+\subsection{Including files}
+\input{final-include}
+
+\bibliography{final}
+
+\appendix
+\section{Appendices - How to}
+\label{append}
+Every Part, Chapter or Section that follows the \verb+\appendix+ command is included in the appendix. Appendices have auto numbering too. The numbering begins freshly in the appendices.
+
+\end{document}
Binary file sttp/latex/examples/hello.jpg has changed
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/latex/examples/hello.tex Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,6 @@
+ %hello.tex - First LaTeX document
+ \documentclass{article}
+
+ \begin{document}
+ Hello, World!
+ \end{document}
Binary file sttp/latex/examples/lion_orig.png has changed
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/latex/handout.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,811 @@
+LaTeX
+=====
+
+Introduction
+------------
+LaTeX is a typesetting program used to produce excellently typeset documents. It is extensively used for producing high quality scientific and mathematical documents. It may also be used for producing other kinds of documents, ranging from simple one page articles or letters
+
+
+TeX & LaTeX
+~~~~~~~~~~~
+
+TeX
++++
+
+TeX is a typesetting system designed by Donald Knuth, the renowned Computer Scientist and Emeritus professor at Stanford University. Typesetting is placing text onto a page with all the style formatting defined, so that content looks as intended.
+
+It was designed with two goals in mind-
+
+1. To allow anybody to produce high-quality books using a reasonable amount of effort.
+2. To provide a system that would give the exact same results on all computers, now and in the future
+
+TeX is well known for it's stability and portability.
+
+TeX is pronounced as "tech".
+
+The current version of TeX is 3.1415926 and is converging to π.
+
+LaTeX
++++++
+
+LaTeX was originally written by Leslie Lamport in the early 1980s. It is an extension of TeX, consisting of TeX macros and a program to parse the LaTeX files. It is easier to use than TeX itself, at the same time producing the same quality of output.
+
+LaTeX is pronounced either as "Lah-tech" or "Lay-tech"
+
+WYSIWG vs. WYSIWM
+~~~~~~~~~~~~~~~~~
+
+WYSIWG is an acronym for "What You See Is What You Get". Word processors, are typically WYSIWG tools. LaTeX, TeX or other TeX based tools are not. They are typesetting or text formatting or document description programs. They can be called WYSIWM or "What You See Is What you Mean" systems, since you give a description of how things look, and LaTeX typesets the document for you.
+
+Here are a few reasons, why you should use LaTeX -
+
+ * LaTeX produces documents with excellent visual quality, especially mathematical and scientific documents.
+ * It does the typesetting to you. Typically, when one works with a word-processor, the user is doing the text formatting or typesetting along with typing out the content. LaTeX allows the user to concentrate on the content leaving aside the typesetting to LaTeX.
+ * It is light on your resources as compared to most of the word processors available today.
+ * It is well known for it's stability and for it's virtually bug free code base.
+ * It encourages users to structure documents by meaning rather than appearance, thereby helping produce well structured documents.
+ * It uses plain text files as input, which have a lot of well known advantages over binary files. To state a few, they can be opened with any editor on any operating system, they are smaller in size compared to the binaries, can be version controlled and can be processed using widely used text processing utilities.
+ * The output can be generated in more than one formats.
+ * It is free software (free as in freedom) and gratis too.
+ * It is widely used.
+
+Hello World
+~~~~~~~~~~~
+
+OK, let's get started with our first LaTeX document. Open up your favorite editor and type in the following code.
+
+::
+
+ %hello.tex - First LaTeX document
+ \documentclass{article}
+
+ \begin{document}
+ Hello, World!
+ \end{document}
+
+Save the file as ``hello.tex`` and open up a terminal to compile your ``tex`` file to get the output in a ``pdf`` format.
+
+Compiling & Output
+++++++++++++++++++
+
+::
+
+ $pdflatex hello.tex
+
+ Output written on hello.pdf (1 page, 5733 bytes).
+ Transcript written on hello.log.
+
+Open the ``hello.pdf`` to see the output as shown.
+
+.. image:: examples/hello.jpg
+
+Note: The command ``latex`` is often used to get the ``dvi`` output. But, throughout this course, we shall use pdflatex to compile our documents.
+
+A peek at the source
+++++++++++++++++++++
+
+``%hello.tex - First LaTeX document``
+
+ This line is a comment. LaTeX ignores this line and it is meant only for the human readers. LaTeX ignores anything after a ``%`` symbol to the end of the line.
+
+``\documentclass{article}``
+
+ This line is a command and sets the ``documentclass`` of the document to ``article``. LaTeX has other classes like ``report``, ``book``, ``letter``, etc. The typesetting of the document varies depending on the ``documentclass`` of the document.
+
+
+``\begin{document}``
+
+ This line informs LaTeX that this is the beginning of the content of the document.
+
+``Hello, World!``
+
+ This is the actual text displayed in the document.
+
+``\end{document}``
+
+ This line tells LaTeX that the document is complete and LaTeX will simply ignore anything written after this line.
+
+Where do we want to go
+~~~~~~~~~~~~~~~~~~~~~~
+
+During the course of this session we will learn how to do various things in LaTeX and try to produce the sample document provided.
+
+Some Basics
+~~~~~~~~~~~
+Before we get started with creating the document, let's try to understand a few things that would be useful during the course of this session.
+
+Spaces
+++++++
+
+LaTeX treats multiple empty spaces (or lines) as a single space (or line). An empty line between two lines of text is considered as a change of paragraphs.
+
+Line & Page Breaks
+++++++++++++++++++
+
+LaTeX usually does the job of breaking up your content into lines and pages, and does it well. But under some circumstances, you might want to instruct LaTeX to break line or start a new page at a particular point.
+
+``\\`` or ``\newline`` command is used to create a new line at the point where the command is issued.
+Appending ``*`` to ``\\``, instructs LaTeX to create a new line, without creating a new page at that point.
+
+Paragraphs
+++++++++++
+
+As already mentioned, LaTeX considers an empty line between two lines of text as a new paragraph. ``\par`` command may also be used to start a newline. It is equivalent to the blank line.
+
+By default LaTeX indents new paragraphs. If you do not wish to have the paragraph indented, you can use the ``\nointend`` command at the beginning of the paragraph.
+
+Special Characters
+++++++++++++++++++
+
+LaTeX associates special meaning to the characters ``~ # $ % ^ & _ { } \``.
+
+To have these characters in the text of your document, you need to prefix a backslash to them. ``\~ \# \% \$ \^ \& \_ \{ \} \textbackslash``
+
+
+Commands
+++++++++
+
+* All LaTeX commands start with a backslash ``\``.
+* Like the commands in Linux, they are case sensitive.
+* They usually have a backslash followed by a consisting of letters only. Any character other than letters, like space, numbers or special characters terminate the command.
+* The commands for producing special characters in the text, is an exception. They contain a backslash followed by a single special character.
+* Commands may have parameters, which are supplied to them by enclosing them in curly braces ``{ }``.
+* They may also have a few optional parameters which are added after the name in square brackets ``[ ]``.
+
+
+Environments
+++++++++++++
+
+Environments are very similar to the commands, except that they effect larger parts of the document. For example, we used the ``document`` environment in our first LaTeX document.
+
+* They begin with a ``\begin`` and end with a ``\end``
+* In general environments can be nested within each other.
+
+Some Structural Elements
+------------------------
+
+``\documentclass``
+~~~~~~~~~~~~~~~~~~
+As already stated, the ``documentclass`` command tells LaTeX, the type of the document that you intend to create. Each class has a few differences in how the content of the document is typeset. We presently have it set to the article class. Let us try changing it to the report class.
+
+Note that the top matter of the document appears in a different page for the report class.
+
+Some of the LaTeX classes that you may want to use are, article, proc, report, book, slides, letter.
+
+The ``documentclass`` command also accepts a few optional parameters. For example::
+ \documentclass[12pt,a4paper,oneside,draft]{report}
+
+``12pt`` specifies the size of the main font in the document. The relative sizes of the various fonts is maintained, when the font size is changed. If no size is specified, ``10pt`` is assumed by default.
+
+``a4paper`` specifies the size of the paper to be used for the document.
+
+``oneside`` specifies that the document will be printed only on one side of the paper. The ``article`` and ``report`` classes are ``oneside`` by default and the ``book`` class is ``twoside``.
+
+``draft`` marks the hyphenation and justification problems in the document with a small square in the right hand margin of the document, so that they can be easily spotted.
+
+Note: Everything written in between the ``\documentclass`` command and the ``\begin{document}`` command is called the Preamble.
+
+
+Parts, Chapters and Sections
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Often documents are divided into various parts, chapters, sections and subsections. LaTeX provides an intuitive mechanism to include this in your documents. It has various commands like ``part``, ``chapter``, ``section``, ``subsection``, ``subsubsection``, ``paragraph`` and ``subparagraph``. Note that all these commands are not available in all the document classes. The ``chapter`` command is available only in books and reports. Also, the ``letter`` document class does not have any of these commands.
+
+Let us now give our document some structure, using these commands.
+
+Note that you do not need to provide any numbers to the commands. LaTeX automatically takes care of the numbering.
+Also, you do not need to enclose the text of a block within ``\begin`` and ``\end`` commands. LaTeX starts a new block each time it finds a sectioning command.
+::
+
+ \section[Short Title]{This is a very long title and the Short Title will appear in the Table of Contents.}
+
+
+Section Numbering
++++++++++++++++++
+
+As already, you don't need to explicitly do any numbering in LaTeX. Parts are numbered using roman numerals; Chapters and sections are numbered using decimal numbers. When the table of contents is inserted into a document, all the numbered headings automatically appear in it.
+
+By default LaTeX has numbering up 2 levels, i.e, the parts, chapters, sections and subsections are numbered. You can change this by setting the ``secnumdepth`` counter using the ``\setcounter`` command. The following command removes numbering of the subsections. Only parts, chapters and sections are numbered.
+::
+
+ \setcounter{secnumdepth}{1}
+
+A sectioning command appended with an asterisk gives an unnumbered heading that is not included in the table of contents.
+::
+
+ \section*{Introduction}
+
+Top Matter
+~~~~~~~~~~
+
+The information about the document such as it's title, the date, the author(s) information etc, is collectively known as the topmatter. Though there is no command called ``topmatter``, the term topmatter is frequently used in LaTeX documentation.
+
+Let us input the top matter for our document now.
+::
+
+ \title{LaTeX - A How-to}
+ \author{The FOSSEE Team}
+ \date
+
+The commands ``\title`` and ``\author`` are self explanatory.
+The ``\date`` command automatically puts in today's date into the document. Now let us compile and look at the result.
+
+You would observe that the details do not appear in the document after recompilation. This is because, LaTeX has not been instructed what to do with the top matter information that you have given it. Use the ``\maketitle`` command within the document environment to instruct LaTeX to place the top matter information into the document.
+
+Abstract
+~~~~~~~~
+Lets now place and abstract in the document using the ``abstract`` environment of LaTeX. The abstract appears in the document after the topmatter but before the main body of the document.
+::
+
+ \begin{abstract}
+ The abstract abstract.
+ \end{abstract}
+
+
+Appendices
+~~~~~~~~~~
+
+LaTeX allows for separate numbering for appendices. ``\appendix`` command indicates that the sections following are to be included in the appendix.
+::
+
+ \appendix
+ \chapter{First Appendix}
+
+Table of Contents
+~~~~~~~~~~~~~~~~~
+
+Parts, chapters or sections that have been auto numbered by LaTeX automatically appear in the Table of Contents (ToC). ``\tableofcontents`` command places a the ToC, where the command has been issued.
+
+The counter ``tocdepth`` specifies the depth up to which headings appear in the ToC. It can be set using the ``\setcounter`` command as shown below.
+::
+
+ \setcounter{tocdepth}{3}
+
+Unnumbered sections can be placed in the table of contents using the ``\addcontentsline`` command as shown below.
+::
+
+ \section*{Introduction}
+ \addcontentsline{toc}{section}{Introduction}
+
+Note: To get the correct entries in your table of contents, you will need to run one extra compilation, each time. This is because, the entries of the table of contents are collected during each compilation of the document and utilized during the next compilation.
+
+Elementary Text Typesetting
+---------------------------
+
+Emphasizing
+~~~~~~~~~~~
+
+*Italic* font is generally used to emphasize text. The ``\emph`` command may be used to achieve this effect in LaTeX.
+::
+
+ This is the \emph{emphasized text}.
+
+If the ``\emph`` command is nested within another emphasize command, LaTeX emphasized that text using normal fonts.
+::
+
+ \emph{Did you wonder what happens when we try \emph{emphasizing text} within \emph{emphasized text}}?
+
+*This is emphasized text, and* this is emphasized text with normal font *, within* emphasized text.
+
+Quotation Marks
+~~~~~~~~~~~~~~~
+
+When typing in LaTeX, the double quotation mark ``"`` character shouldn't be used. The grave accent ````` character produces the left quote and the apostrophe ``'`` character produces the right quote. To obtain double quotes they are, each, used twice.
+::
+
+ `` Here is an example of putting `text' in quotes ''
+
+Dashes and Hyphens
+~~~~~~~~~~~~~~~~~~
+
+LaTeX has four dashes of different lengths. Three of them can be produces with different number of consecutive dashes. The short dashes are used for hyphens, slightly longer ones for number ranges and the longest ones for comments. The fourth one is a mathematical symbol, the minus sign.
+::
+
+ The names of these dashes are: `-' hyphen, `--' en-dash, `---' em-dash and `$-$' minus sign.
+
+The names for these dashes are: ‘‐’ hyphen, ‘–’ en-dash, ‘—’ em-dash and ‘−’ minus sign.
+
+Footnotes
+~~~~~~~~~
+
+With the command::
+
+ \footnote{footnote text}
+
+a footnote is printed at the foot of the current page. Footnotes should always be put after the word or sentence they refer to. Footnotes referring to a sentence or part of it should therefore be put after the comma or period.
+
+Note: Look at the ``\marginpar`` command to insert margin notes
+
+Flushleft, Flushright, and Center
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The environments ``flushleft`` and ``flushright`` generate paragraphs that are either left- or right-aligned.
+
+The ``center`` environment generates centered text.
+
+Itemize, Enumerate, and Description
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+LaTeX has three different environments for producing lists. Itemize, Enumerate and Description allow you to produce lists of various types in LaTeX.
+
+Itemize is used to produce unnumbered lists. The bullets of the list can be easily changed to use any character. Enumerate environment allows you to produce auto-numbered lists. The description environment, allows you to produce a list of definitions. These environments can be nested within each other, easily.
+
+::
+
+ \begin{itemize}
+ \item Now we move onto some elementary \emph{Text Typesetting}.
+ \item How do we get \emph{emphasized or italic text}?
+ \item \emph{Did you wonder what happens when we try \emph{emphasizing text} within \emph{emphasized text}}?
+ \item ``Beautiful is better than ugly.''
+ \end{itemize}
+
+ \begin{description}
+ \item[Description] This list is a description list.
+ \item[Enumerate] Numbered lists are often useful.
+ \begin{enumerate}
+ \item First
+ \item Second
+ \item Third
+ \item \ldots
+ \end{enumerate}
+ \item[Itemize] The list above this description list is an itemize list.
+ \end{description}
+
+Quote, Quotation, and Verse
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+LaTeX provides a ``quote`` environment that can be used for quoting, highlighting important material, etc.
+::
+
+ The Zen of Python
+ \begin{quote}
+ The Zen of Python, by Tim Peters
+
+ Beautiful is better than ugly.
+ Explicit is better than implicit.
+ Simple is better than complex.
+ Complex is better than complicated.
+ Flat is better than nested.
+ Sparse is better than dense.
+ Readability counts.
+ Special cases aren't special enough to break the rules.
+ Although practicality beats purity.
+ Errors should never pass silently.
+ Unless explicitly silenced.
+ In the face of ambiguity, refuse the temptation to guess.
+ There should be one-- and preferably only one --obvious way to do it.
+ Although that way may not be obvious at first unless you're Dutch.
+ Now is better than never.
+ Although never is often better than *right* now.
+ If the implementation is hard to explain, it's a bad idea.
+ If the implementation is easy to explain, it may be a good idea.
+ Namespaces are one honking great idea -- let's do more of those!
+ \end{quote}
+
+LaTeX provides two other similar environments, the quotation and the verse environments.
+
+The quotation environment can be used for longer quotes which have several paragraphs, since it indents the first line of each paragraph.
+
+The verse environment may be used to quote verses or poems, since the line breaks are important in quoting them. The lines are separated using ``\\\\`` at the end of a line and an empty line after each verse.
+
+Verbatim
+~~~~~~~~
+The verbatim environment allows us to insert pre-formatted text in a LaTeX document. It is useful for inserting code samples within the document. The verbatim text needs to be enclosed between ``\begin{verbatim}`` and ``\end{verbatim}``.
+::
+
+ \begin{verbatim}
+ from numpy import *
+ a = linspace(0, 5, 50, endpoint = False)
+ \end{verbatim}
+
+ from numpy import *
+ a = linspace(0, 5, 50, endpoint = False)
+
+To insert verbatim text in-line, the ``\verb`` command can be used.
+::
+
+ The verb command allows placing \verb|verbatim text| in-line.
+
+The | is just an example of a delimiter character. You can use any character except letters, * or space.
+
+Tables, Figures and Captions
+----------------------------
+
+The ``\tabular`` environment
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The ``tabular`` environment allows you to typeset tables in LaTeX. ``\begin{tabular}[pos]{col fmt}`` command can be used to specify the parameters of the table and start creating the table.
+
+The ``pos`` argument specifies the vertical position of the table relative to the baseline of the surrounding text. It can take on the values ``t`` for top, ``b`` for bottom, or ``c`` for center.
+
+
+The ``col fmt`` argument specifies the formatting of the columns of the table. You need to explicitly specify the formatting for each of the columns in the table. The ``col fmt`` argument can take on the following values.
+
++---------------+------------------------------------+
+| ``l`` | left justified column content |
++---------------+------------------------------------+
+| ``r`` | right justified column content |
++---------------+------------------------------------+
+| ``c`` | centered column content |
++---------------+------------------------------------+
+| ``*{n}{col}`` | produces ``n`` columns with the |
+| | ``col`` type of formatting |
+| | ``*{3}{c}`` is the same as {c c c} |
++---------------+------------------------------------+
+| ``|`` | produces a vertical line. |
++---------------+------------------------------------+
+
+Now we look at how to input the actual entries of the tables. Each horizontal row in a table is separated by ``\\``. Each column entry of a row is separated by ``&``.
+
+The ``\hline`` command allows you to draw horizontal lines between two rows of the table. But it does not allow you do draw partial lines. ``\cline{a-b}`` draws a horizontal line from column ``a`` to column ``b``.
+::
+
+ \begin{tabular}{|c|c|}
+ \hline
+ \verb+l+ & left justified column content\\
+ \hline
+ \verb+r+ & right justified column content\\
+ \hline
+ \verb+c+ & centered column content\\
+ \hline
+ \verb+*{n}{col}+ & produces \verb+n+ columns with the\\
+ & \verb+col+ type of formatting\\
+ \cline{2-2}
+ &\verb+*{3}{c}+ is the same as \verb+{c c c}+ \\
+ \hline
+ \verb+|+ & produces a vertical line\\
+ \hline
+ \end{tabular}
+
+Importing Graphics
+~~~~~~~~~~~~~~~~~~
+
+To include images in LaTeX, we require to use an additional package known as ``graphicx``. To load a package, we use the ``\usepackage`` directive in the preamble of the document.
+::
+
+ \usepackage{graphicx}
+
+When compiling with ``pdflatex`` command, **jpg**, **png**, **gif** and **pdf** images can be inserted.
+
+::
+
+ \includegraphics[optional arguments]{imagename}
+
+A few ``optional arguments``:
+
+ ``width=x``, ``height=x``
+ If only the height or width is specified, the image is scaled, maintaining the aspect ratio.
+
+ ``keepaspectratio``
+ This parameter can either be set to true or false. When set to true, the image is scaled according to both width and height, without changing the aspect ratio, so that it does not exceed both the width and the height dimensions.
+
+ ``scale=x``
+ Scale the image by a factor of ``x``. For example, ``scale=2``, will double the image size.
+
+ ``angle=x``
+ This option can be used to rotate the image by ``x`` degrees, counter-clockwise.
+
+::
+
+ \includegraphics[scale=0.8, angle=30]{lion_orig.png}
+
+Floats
+~~~~~~
+
+Tables and Figures need to be treated in a special manner, since they cannot be split over pages, and they are referred to as floats in LaTeX.
+
+When there is not enough space on a page, to fit in a table or figure, it is floated over to the next page filling up the current page with text. LaTeX has float environments called table and figure for tables and images, respectively.
+
+Anything enclosed within the table or figure environments will be treated as floats.
+::
+
+ \begin{figure}[pos] or
+ \begin{table}[pos]
+
+The ``pos`` parameter specifies the placement of the float. The possible values it can take are as follows.
+
++-----------+-------------------------------------------------------------------+
+| Specifier | Permission |
++===========+===================================================================+
+| h | at approximately the same place where it occurs in the source |
++-----------+-------------------------------------------------------------------+
+| t | at the top of the page. |
++-----------+-------------------------------------------------------------------+
+| b | at the bottom of the page. |
++-----------+-------------------------------------------------------------------+
+| p | on a special page for floats only. |
++-----------+-------------------------------------------------------------------+
+| ! | Override LaTeX's internal parameters for good positions |
++-----------+-------------------------------------------------------------------+
+| H | nearly equivalent to h! |
++-----------+-------------------------------------------------------------------+
+
+Examples::
+
+ \begin{figure}[h]
+ \centering
+ \includegraphics[scale=0.8, angle=30]{lion_orig.png}
+ \end{figure}
+
+
+Captions
+~~~~~~~~
+
+The ``\caption{text}`` command allows you to add captions to images or tables. LaTeX automatically numbers your tables and figures and you need not include numbers in the captions that you write. The caption appears below or on top of the image (or table), depending on whether you place it after or before the ``importgraphics`` (or ``tabular``) command.
+
+::
+ \begin{figure}[h]
+ \centering
+ \includegraphics[scale=0.8]{lion_orig.png}
+ \caption{CTAN lion drawing by Duane Bibby; thanks to www.ctan.org}
+ \end{figure}
+
+The caption command also, like the section command, has the short caption optional parameter. The short caption will appear in the list of tables or figures.
+
+List of Figures, Tables
+~~~~~~~~~~~~~~~~~~~~~~~
+
+LaTeX can automatically generate a List of Tables or Figures, with the table or figure numbers, the captions and page numbers on which they appear. This can be done using the ``\listoftables`` or ``listoffigures`` commands.
+
+Note: Just like table of contents, these lists also require an extra compilation.
+
+Cross References
+~~~~~~~~~~~~~~~~
+
+LaTeX has a very efficient mechanism of inserting cross-references in documents.
+
+The command ``\label{name}`` is used to label figures, tables or segments of text. ``\ref{name}`` refers to the object marked by the ``name`` by it's numbering (figure, table, section etc.) ``\pageref{name}`` gives the page number of the object which has been labeled with ``name``.
+
+Note: Cross referencing also requires an extra compilation, like table of contents.
+
+Bibliography
+------------
+
+Bibliography or references can be added to LaTeX documents in two ways - using the ``thebibliography`` environment, or using BibTeX. Let's first look at using the ``\thebibliography`` environment and then move on to BibTeX.
+
+``thebibliography`` environment
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Writing bibliographies in LaTeX using the ``thebibliography`` environment is pretty easy. You simply have to list down all the bibliography items within the bibliography environment.
+
+Each entry of the bibliography begins with the command ``\bibitem[label]{name}``. The name is used to cite the bibliography item within the document using ``\cite{name}``. The label option replaces the numbers from the auto enumeration with the labels given.
+::
+
+ He used this lion in the illustrations for D Knuth's original TeXbook\cite{DKnuth}, for L Lamport's LaTeX book\cite{LLamport}
+
+ \begin{thebibliography}{99}
+ \bibitem{DKnuth} Donald E. Knuth (1984). \emph{The TeXbook} (Computers and Typesetting, Volume A). Reading, Massachusetts: Addison-Wesley. ISBN 0-201-13448-9.
+
+ \bibitem{LLamport} Lamport, Leslie (1994). \emph{LaTeX: A document preparation system: User's guide and reference}.
+ illustrations by Duane Bibby (2nd ed.). Reading, Mass: Addison-Wesley Professional.
+ \end{thebibliography}
+
+The ``99`` in the example above indicates the maximum width of the label that the references may get. We here assume that the number of Bibliography items will be less than 100. If your document has less than 10 references, you may want to replace ``99`` with ``9``.
+
+BibTeX
+~~~~~~
+
+The previous section explained the process of listing references at the end of a document and embedding cross references. In this section let us explore the BibTeX environment for keeping track of references.
+
+Using BibTeX is a very convenient method to use, when writing multiple documents in a single area or field. BibTeX allows you to create a database of all your references and use them as and when required.
+
+The BibTeX database is stored in a ``.bib`` file. The structure of the file is quite simple and an example is shown below.
+::
+
+ @book{Lamport94,
+ author = "Leslie Lamport",
+ title = "A Document Preparation System: User's Guide and Reference",
+ publisher = "Addison-Wesley Professional",
+ year = "1994",
+ edition = "second",
+ note = "illustrations by Duane Bibby"
+ }
+
+Each bibliography entry starts with a declaration of the type of the reference being mentioned. The reference is in the above example is of the book type. BibTeX has a wide range of reference types, for example, ``article, book, conference, manual, proceedings, unpublished``.
+
+The type of reference is followed by a left curly brace, and immediately followed by the citation key. The citation key, ``Lamport94`` in the example above is used to cite this reference using the command ``\cite{Lamport94}``.
+
+This is followed by the relevant fields and their values, listed one by one. Each entry must be followed by a comma to delimit one field from the other.
+
+To get your LaTeX document to use the bibliography database, you just add the following lines to your LaTeX document.
+::
+
+ \bibliographystyle{plain}
+ \bibliography{LaTeX}
+
+Bibliography styles are files that tell BibTeX how to format the information stored in the ``.bib`` database file. The style file for this example is ``plain.bst``. Note that you do not need to add the ``.bst`` extension to the filename. If you wish to achieve a particular style of listing the bibliography items and citing them, you should use an appropriate style file.
+
+The ``bibliography`` command specifies the file that should be used as the database for references. The file used in this example is ``LaTeX.bib``
+
+Compiling
++++++++++
+
+Adding BibTeX based references, slightly complicates the process of compiling the document to obtain the desired output. The exact workings of LaTeX and BibTeX will not be explained here. The procedure for obtaining the output (without any explanations) is as follows:
+
+1. Compile the ``.tex`` file using ``pdflatex`` - ``$pdflatex LaTeX(.tex)``
+2. Compile the ``.bib`` file using ``bibtex`` - ``$bibtex LaTeX(.bib)``
+3. Compile the ``.tex`` file again.
+4. Compile the ``.tex`` file for one last time!
+
+Typesetting Math
+----------------
+
+It is advisable to use the AMS-LaTeX bundle to typeset mathematics in LaTeX. It is a collection of packages and classes for mathematical typesetting.
+
+We load ``amsmath`` by issuing the ``\usepackage{amsmath}`` in the preamble. Through out this section, it is assumed that the ``amsmath`` package has been loaded.
+
+
+Math Mode
+~~~~~~~~~
+
+There are a few differences between the *math mode* and the *text mode*:
+
+1. Most spaces and line breaks do not have any significance, as all spaces are either derived logically from the mathematical expressions, or have to be specified with special commands such as ``\``, ``\quad`` or ``\qquad``
+
+2. Empty lines are not allowed.
+
+3. Each letter is considered to be the name of a variable and will be typeset as such. If you want to typeset normal text within a formula, then you have to enter the text using the \text{...} command
+
+Single Equations
+~~~~~~~~~~~~~~~~
+
+Mathematical equations can be inserted in-line within a paragraph (*text style*), or the paragraph can be broken to typeset it separately (*display style*).
+
+A mathematical equation within a paragraph is entered between ``$`` and ``$``. Larger equations are set apart from the paragraph, by enclosing them within ``\begin{equation}`` and ``\end{equation}``. If you don't wish to number a particular equation, the starred version of equation can be used. ``\begin{equation*}`` and ``\end{equation*}``
+
+The equation can also be cross referenced using the ``\label`` and ``\eqref`` commands.
+
+Basic Elements
+~~~~~~~~~~~~~~
+
+Greek Letters can are entered as ``\alpha, \beta, \gamma, \delta, ...`` for lowercase letters and ``\Alpha, \Beta, \Gamma, ...`` for uppercase ones.
+
+Exponents and subscripts can be typeset using the carat ``^`` and the underscore ``_`` respectively. Most of the math mode commands act only on the next character. If you want a command to affect several characters, they need to be enclosed in curly braces.
+
+The ``\sqrt`` command is used to typeset the square root symbol. LaTeX of the root sign is determined automatically. The nth root is generated with ``\sqrt[n]``.
+
+To explicitly show a multiplication a dot may be shown. ``\cdot`` could be used, which typesets the dot to the center. ``\cdots`` is three centered dots while ``\ldots`` sets the dots on the baseline. Besides that ``\vdots`` for vertical and ``\ddots`` can be used for diagonal dots.
+
+A fraction can be typeset with the command ``\frac{..}{..}``
+
+The integral operator is generated with ``\int``, the sum operator with ``\sum``, and the product operator with ``\prod``. The upper and lower limits are specified with ``^`` and ``_`` like subscripts and superscripts.
+
+LaTeX provides all kinds of braces as delimiters. The round and square brackets can be produces using the keys on the keyboard and appending a backslash. Other delimiters can be produced using special commands of LaTeX. Placing ``\left`` in front of an opening delimiter and ``\right`` in front of a closing delimiter, instructs LaTeX to automatically take care of the sizes of the delimiters.
+
+Multiple Equations
+~~~~~~~~~~~~~~~~~~
+
+Long formulae that run over several lines or equation systems, can be typeset using the ``align`` or ``align*`` environments. ``align`` numbers each of the lines in the environment, and ``align*`` as expected, does not number any of them.
+
+The ``&`` is used to align the equations vertically and the ``\\`` command is used to break the lines. Line numbering can be skipped for a particular line in the ``align`` environment by placing a ``\nonumber`` before the line break.
+
+::
+
+ \begin{align}
+ \alpha^2 + \beta^2 &= \gamma^2 \\
+ \sum_{i=1}^ni &= \frac{n(n+1)}{2}\\
+ \sqrt{-1} &= \pm1 \nonumber
+ \end{align}
+
+
+Arrays and Matrices
+~~~~~~~~~~~~~~~~~~~
+
+To typeset arrays, use the ``array`` environment. It works similar to the ``tabular`` environment. The ``\\`` command is used to break the lines.
+::
+
+ \begin{equation*}
+ \mathbf{X} = \left(
+ \begin{array}{ccc}
+ a_1 & a_2 & \ldots \\
+ b_1 & b_2 & \ldots \\
+ \vdots & \vdots & \ddots
+ \end{array} \right)
+ \end{equation*}
+
+The ``array`` environment can also be used to typeset piecewise functions by using a “.” as an invisible ``\right`` delimiter
+::
+
+ \begin{equation*}
+ f(x) = \left\{
+ \begin{array}{rl}
+ 0 & \text{if } x \le 0\\
+ 1 & \text{if } x > 0
+ \end{array} \right.
+ \end{equation*}
+
+Six different types of matrix environments are available in the ``amsmath`` package for typesetting matrices. They essentially have different delimiters: ``matrix`` (none), ``pmatrix`` (, ``bmatrix`` [, ``Bmatrix`` {, ``vmatrix`` | and ``Vmatrix`` ‖. In these matrix environments, the number of columns need not be specified, unlike the ``array`` environment.
+::
+
+ \begin{equation*}
+ \begin{matrix}
+ 1 & 2 \\
+ 3 & 4
+ \end{matrix} \qquad
+
+ \begin{bmatrix}
+ 1 & 2 & 3 \\
+ 4 & 5 & 6 \\
+ 7 & 8 & 9
+ \end{bmatrix}
+ \end{equation*}
+
+Miscellaneous Stuff
+-------------------
+
+Presentations
+~~~~~~~~~~~~~
+
+LaTeX has quite a few options to produce presentation slides. We shall look at the ``beamer`` class, which is well developed and easy to use. We shall only briefly look at some of the features of beamer. For the best documentation, look at the beamer user guide.
+
+To write a ``beamer`` presentation, it is recommended that you use one of the templates that beamer provides. We shall use the ``speaker_introduction`` template to get started with beamer.
+
+As you can see, the document begins with the ``documentclass`` being set to beamer.
+
+The ``\setbeamertemplate`` command sets the template for various parameters. The ``background canvas``, ``headline`` and ``footline`` are being set using the command.
+
+``\usetheme`` command sets the theme to be used in the presentation.
+
+Notice that each slide is enclosed within ``\begin{frame}`` and ``\end{frame}`` commands. The ``\begin{frame}`` command can be passed the Title and Subtitle of the slide as parameters.
+
+To achieve more with beamer, it is highly recommended that you look at the ``beameruserguide``.
+
+Including Code
+~~~~~~~~~~~~~~
+
+The ``listings`` package can be used to embed source code into your LaTeX document. We shall briefly explore inserting python code into our document.
+
+Obviously, you first need to tell LaTeX that you want it to use the ``listings`` package, using the ``\usepackage`` command.
+::
+
+ \usepackage{listings}
+
+Then, we tell LaTeX that we are going to embed Python code into this document. A simple code highlighting for Python code can be achieved using this.
+::
+
+ \lstset{language=Python,
+ showstringspaces=false,
+ }
+
+You might want to customize the code highlighting further using other variables like ``basicstyle``, ``commentstyle``, ``stringstyle``, ``keywordstyle`` etc. For detailed information on all this, you should look at the ``listings`` package documentation.
+
+You include a block of code into your document by enclosing it within the ``lstlisting`` environment.
+::
+
+ \begin{lstlisting}
+ string="Hello, World! "
+ for i in range(10):
+ print string*i
+ \end{lstlisting}
+
+You can also include source code files directly into your latex document, using the ``lstinputlisting`` command.
+::
+
+ \lstinputlisting[lastline=20]{lstexample.py}
+
+This command includes the first 20 lines of the file ``lstexample.py`` into out LaTeX document.
+
+Including files
+~~~~~~~~~~~~~~~
+When working on a large document, it is convenient sometimes, to split the large file into smaller input files and club them together at the time of compiling.
+
+The ``\input`` or ``\include`` commands may be used to embed one LaTeX file into another. The ``\input`` command is equivalent to a copy and paste of the document, just before the compilation. The ``\include`` command is exactly similar, except for the fact that it creates a new page every time it is issued.
+
+``\input{file}`` or ``\include{file}`` commands will include the file ``file1.tex`` with in the file where the command has been issued. Note that you do not need to specify the ``.tex`` extension of the file.
+
+The ``\includeonly`` is useful for debugging or testing the LaTeX document that you are creating, since it restricts the ``\include`` command. Only the files which are given as arguments to the ``\includeonly`` command will be included in the document (wherever a ``\include`` command for those files, has been issued).
+
+A note on filenames
++++++++++++++++++++
+
+Never use filenames or directories that contain spaces. Make filenames as long or short as you would like, but strictly avoid spaces. Stick to upper or lower case letters (without accents), the digits, the hyphen and the full stop or period.
+
+
+
+Recommended Reading
+-------------------
+
+1. *LaTeX Wikibook*
+
+2. *The Not So Short Introduction to LaTeX2e* by Tobias Oetikar et al..
+
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/latex/latex.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,69 @@
+Module 3: LaTeX
+===============
+
+Module Objectives
+-----------------
+
+After completing this module, a participant will be successfully able to:
+
+- Produce professional documents in LaTeX. RBT Ap
+- Typeset Mathematical equations. RBT Ap
+- Include figures, tables and code samples. RBT Ap
+- Add References and write BibTeX files. RBT Ap
+
+Suggested Reading
+-----------------
+
+1. *LaTeX Wikibook*
+
+2. *The Not So Short Introduction to LaTeX2e* by Tobias Oetikar et. al.
+
+
+Session Level Split-up
+----------------------
+
++---------+---------------------------------+---------+
+| Session | Topic | Duration|
++=========+=================================+=========+
+| 1 | Introduction, TeX & LaTeX | 5 min |
+| | WYSIWG vs. WYSIWM | |
+| | | |
+| | Hello World, Compiling, | 10 min |
+| | Where we want to go, Some Basics| |
++---------+---------------------------------+---------+
+| 2 | Some Structural Elements | 15 min |
+| | | |
+| | Top Matter, ``\documentclass``, | |
+| | Abstract, | |
+| | Sections, Chapters & Parts, | |
+| | Appendices, Table of Contents | |
++---------+---------------------------------+---------+
+| 3 | Emphasizing, Quotation marks, | 5 min |
+| | Dashes & Hyphens, Footnotes, | |
+| | Flushleft, Flushright & Center | |
+| | | |
+| | Enumerate, Itemize, Description,| 10 min |
+| | Quote, Quotation and Verse, | |
+| | Verbatim | |
++---------+---------------------------------+---------+
+| 4 | ``\tabular`` environment, | 20 min |
+| | Importing Graphics, Floats, | |
+| | Captions, List of Figures, | |
+| | List of Tables, Cross References| |
++---------+---------------------------------+---------+
+| 5 | ``\thebibliography`` | 10 min |
+| | environment, BibTeX | |
++---------+---------------------------------+---------+
+| 6 | ``\usepackage{amsmath}``, | 5 min |
+| | Single Equations | |
+| | | |
+| | Building blocks of an equation, | 15 min |
+| | Multiple Equations, Arrays and | |
+| | Matrices | |
++---------+---------------------------------+---------+
+| 7 | ``beamer``, ``listing``, | 10 min |
+| | Including files | |
++---------+---------------------------------+---------+
+| 8 | Exercises | 15 min |
++---------+---------------------------------+---------+
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/Section_5.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,703 @@
+Module Objectives:
+==================
+
+After successfully completing this module a participant will be able to: ::
+
+ - Understand
+ * What are archives and zipped files U
+ * What are environment variables U
+ * What are Shell Scripts U
+ - Able to use file comparison commands like Ap
+ diff, cmp, comm
+ - Create and extract archives(.tar files) and zipped files(.gz) Ap
+ - Set/Modify environment as per need Ap
+ - Create shell scripts to automate tasks. Ap
+
+tar:
+====
+
+Introduction:
+-------------
+
+In world of Linux based distribution, *tarballs* is the term which pops up very often. It is part of the GNU project and comes as part of every distribution of GNU/Linux. Tarball is like defacto standard for releasing source code for free software. Some of common use of *tar* archives is to: *Store, backup, and transport*.
+
+GNU tar creates and manipulates archives which are actually collections of many other files; the program provides users with an organized and systematic method for controlling a large amount of data. It is basically form of creating archive by concatenating one or more files.
+
+Getting Started(go go go!):
+---------------------------
+
+As mentioned previously and if not, *The best way to get started with any command line tool of Linux is to use "man".* ::
+
+ $ man tar
+
+or try these commands(the output may vary with different installations): ::
+
+ $ tar --version
+ tar (GNU tar) 1.20
+ Copyright (C) 2008 Free Software Foundation, Inc.
+ License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
+ This is free software: you are free to change and redistribute it.
+ There is NO WARRANTY, to the extent permitted by law.
+
+ Written by John Gilmore and Jay Fenlason.
+
+ $ tar --help
+ Usage: tar [OPTION...] [FILE]...
+ GNU `tar' saves many files together into a single tape or disk archive, and can
+ restore individual files from the archive.
+ Examples:
+ tar -cf archive.tar foo bar # Create archive.tar from files foo and bar.
+ tar -tvf archive.tar # List all files in archive.tar verbosely.
+ tar -xf archive.tar # Extract all files from archive.tar.
+ ____________
+
+Creating a tar archive:
+~~~~~~~~~~~~~~~~~~~~~~~
+
+We will do some off-the road activity for this exercise. We will use an interesting command *fortune* for creating our practice files and then performing archives of those files and directories. Content of the files would vary for users, as fortune works like that. ::
+
+ $ mkdir fortune-files
+ $ cd fortune-files/
+ $ fortune > first.txt
+ $ cat first.txt
+ Expect the worst, it's the least you can do.
+ $ fortune > second.txt
+ $ fortune > third.txt
+ $ ls
+ first.txt second.txt third.txt
+
+By now we have three txt files, with some random fortune content. To create a tar archive of these files we can use any of following commands according to ones convenience: ::
+
+ $ tar --create --verbose --file=allfiles.tar first.txt second.txt third.txt
+ first.txt
+ second.txt
+ third.txt
+ $ ls
+ allfiles.tar first.txt second.txt third.txt
+
+allfiles.tar is our required tar archive of all the rest of files(or archive of files mentioned in command line). Other form of the previous command are: ::
+
+ $ tar -c -v -f allfiles.tar first.txt second.txt third.txt
+
+or ::
+
+ $ tar -cvf allfiles.tar first.txt second.txt third.txt
+
+The general format for creating a tar archive is: ::
+
+ tar [OPTION...] [FILE]...
+
+For our command are using these options:
+
+ * -c to Create the archive.
+ * -v for Verbose mode, to get the names of the files as they are archived.
+ * -f mentioning the file name of the resulting tar archive.
+
+To create archive of folder itself try this: ::
+
+ $ tar -cvf fortune.tar fortune/
+
+To add files to existing tar archive, option *`r`* is used: ::
+
+ $ fortune > fourth.txt
+ $ tar -r fourth.txt -vf allfiles.tar
+ fourth.txt
+
+There are other options too available for explicitly mentioning the position of archive, use *tar --help* for getting all the details.
+
+Similarly to remove file from archive use *--delete* option: ::
+
+ $ tar --delete second.txt -f allfiles.tar
+ $ tar -tf allfiles.tar
+ first.txt
+ third.txt
+ fourth.txt
+
+Listing the files of archive:
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Once files are archived, tar command have the *`t`* option, for Listing all files in the tar file: ::
+
+ $ tar tf allfiles.tar
+ first.txt
+ second.txt
+ third.txt
+
+**//this is not working for me in some cases :(**
+
+To locate a particular file among the archive mention its name after *t* option. ::
+
+ $ tar t second.txt allfiles.tar
+ second.txt
+
+one can also use elementary regex for locating the file, so in previous case even second.* will also return the same result.
+
+Extracting files from archive:
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+To extract the content from a archive, use *`x`* option: ::
+
+ $ mkdir extract
+ $ cp allfiles.tar extract/
+ $ cd extract
+ $ tar -xvf allfiles.tar
+ first.txt
+ second.txt
+ third.txt
+
+To extract any particular file from archive, mention the name of file after *x* option: ::
+
+ $ tar -x second.txt -vf allfiles.tar
+ second.txt
+
+
+Further Reading for this section:
+---------------------------------
+
+ * http://en.wikipedia.org/wiki/Tar_(file_format)
+ * http://www.gnu.org/software/tar/manual/tar.html
+ * http://linuxreviews.org/beginner/
+
+GZip:
+=====
+
+Tar creates archives but it does not compress data by itself unless specified explicitly. Hence all the archive we create using tar command, is simply of the size of total size of all individual files. With Linux there is a compression tool known as *gzip* which is used to reduce the size of files mentioned. Whenever possible, each file is replaced by one with the extension `.gz', so unlike `tar` this command would *replace the existing file*.
+
+Get going:
+----------
+
+As usual first commands to check out with gzip are *man* and *help*, ::
+
+ $ man gzip
+ $ gzip --help
+
+Creating a zip of a bunch of files is fairly trivial, it can be done simply via: ::
+
+ $ gzip [OPTION]... [FILE]...
+
+Creating zip files:
+~~~~~~~~~~~~~~~~~~~
+
+Continuing from previous set of files and setup, we will like to zip them and hence the command would be: ::
+
+ $ gzip first.txt fourth.txt second.txt third.txt
+ $ ls
+ allfiles.tar first.txt.gz fourth.txt.gz second.txt.gz third.txt.gz zipped.tar.gz
+
+Hence, as mentioned above, all original files are replaced by .gz extension. The above task can also be restated and made easy with help of some common regex expression: ::
+
+ $ gzip *.txt
+
+Similar to *tar* command, one can also use *`-v`* option here to see the output in *verbose* form. For the previous example, if we enable this option the result would be something like this: ::
+
+ $ gzip -v *.txt
+ first.txt: 4.4% -- replaced with first.txt.gz
+ fourth.txt: -7.1% -- replaced with fourth.txt.gz
+ second.txt: -4.8% -- replaced with second.txt.gz
+ third.txt: 3.8% -- replaced with third.txt.gz
+
+For files of very small sizes and some other cases, one might end up with a zipped file whose size is greater then original file, but compression is always performed(so don't be disheartened in the above case, as files are larger :P). So unlike tar, here all files are zipped separately by default, to make them part of one single chunk one can use some *pipes* and *redirections* ::
+
+ $ gzip -c *.txt > all.gz
+
+Now in this case, all files would be zipped, concatenated and then the output would be written to a file all.gz leaving back all the original files. In the command above *`-c`* option states to print the output to standard output(stdout) and following *`>`* would redirect the output to file all.gz. So when we decompress this file, we will get a single file named 'all' with all the content of each files concatenated one after the another.
+
+For creating a zip archive of a complete directory, one has to use *`-r`* options which means recursive, it makes gzip to traverse through all directory tree/structure. By default it will create zip files of each file inside the directory, that is even with the -r flag, gzip still compresses one file at a time : ::
+
+ $ gzip -r fortune-files/
+ $ gzip -rv .
+ ./first.txt: 4.4% -- replaced with ./first.txt.gz
+ ./second.txt: -4.8% -- replaced with ./second.txt.gz
+ ./third.txt: 3.8% -- replaced with ./third.txt.gz
+ ./allfiles.tar: 96.6% -- replaced with ./allfiles.tar.gz
+ ./fourth.txt: -7.1% -- replaced with ./fourth.txt.gz
+
+Hence one always sees files like xxxxx.tar.gz, to create a zip of whole directory in a single file, first archive everything inside a folder and then use gzip on that. For zipping the files using tar itself, one has to use the option *`g`*. ::
+
+ $ tar -cvzf zipped.tar.gz *.txt
+ first.txt
+ fourth.txt
+ second.txt
+ third.txt
+
+*Thats why gzip is designed as a complement to tar, not as a replacement.*
+
+gzip command comes with a option *`-l`* to view the compressed file contents: ::
+
+ $ gzip -l zipped.tar.gz
+ compressed uncompressed ratio uncompressed_name
+ 332 10240 97.0% zipped.tar
+
+Other feature of gzip is option for mentioning the kind of compression one wants. There is a option of *`-n`* where *n varies from 0 to 9* which regulate the speed/quality of compression. With *`-1`* or *`--fast`* option it means the fastest compression method (less compression) and *`--best`* or *`-9`* indicates the slowest compression method, default compression level is *`-6`*.
+
+To decompress a already compressed file there are two options, either use *`gunzip`* command or use *`-d`* option with gzip command: ::
+
+ $ gzip -dv *.gz
+ all.gz: -440.4% -- replaced with all
+ first.txt.gz: 4.4% -- replaced with first.txt
+ fourth.txt.gz: -7.1% -- replaced with fourth.txt
+ second.txt.gz: -4.8% -- replaced with second.txt
+ third.txt.gz: 3.8% -- replaced with third.txt
+ zipped.tar.gz: 97.0% -- replaced with zipped.tar
+
+or: ::
+
+ $ gunzip -v *.gz
+
+Both of those commands will give the same result. So here one can notice the content of file "all" which we created earlier, it will have content of all the rest of four files concatenated one after another, but "zipped.tar.gz" is zip of tar of all files, will effectively have zip of archives of all files separately, and hence the usage and importance of *tar*.
+
+Further Reading for this section:
+---------------------------------
+
+ * http://linuxreviews.org/beginner/
+ * http://lowfatlinux.com/linux-gzip-gunzip.html
+ * http://www.gnu.org/software/gzip/manual/gzip.html
+ * http://en.wikipedia.org/wiki/ZIP_(file_format)
+
+
+File Comparisons:
+=================
+
+Linux based distributions also have some utilities for checking the content of files, comparing them very quickly to other files. These operations can be looking for differences/similarities. Some of the commands which prove handy are:
+
+cmp:
+----
+
+If one wants to compare two files whether they are same or not, one can use this handy tool. Let us consider some situation, we run find/locate command to locate some file, and it turns out that we have a file with same name in different location, and in case we want to run a quick check on there content, cmp is the right tool. For my system I perform these tasks to illustrate the use of this command: ::
+
+ $ find . -name quick.c
+ ./Desktop/programs/quick.c
+ ./c-folder/quick.c
+ $ cmp Desktop/programs/quick.c c-folder/quick.c
+ $
+
+For me it returns nothing, hence that means both the files are exact copy of each other, by default, cmp is silent if the files are the same. Make some changes in one of the file and rerun the command. For me it works like this: ::
+
+ $ cmp Desktop/programs/quick.c c-folder/quick.c
+ Desktop/programs/quick.c c-folder/quick.c differ: byte 339, line 24
+
+That is, if files differ, the byte and line number at which the first difference occurred is reported.
+
+diff:
+-----
+
+Now there are situations when one wants to exactly know the differences among two files, for them, GNU diff can show whether files are different without detailing the differences. For simple and basic usage of this programs, consider following example: ::
+
+ $ echo -e "quick\nbrown\nfox\njumped\nover\nthe\nlazy\ndog" > allcharacters.txt
+ $ echo -e "quick\nbrown\nfox\njmuped\nover\nteh\nlzay\ndog" > problem.txt
+ $ diff problem.txt allcharacters.txt
+ 4c4
+ < jmuped
+ ---
+ > jumped
+ 6,7c6,7
+ < teh
+ < lzay
+ ---
+ > the
+ > lazy
+
+Looking at results above mentioned it is very trivial to deduce that, diff if used on two separate text files will result in line by line results for all the lines which are different. So most common use case scenario can be, got some files in various location of system with same name and size, just run diff through them and remove all the redundant files. Other similar command which one can find more effective for this can be *sdiff*, for the same files using sdiff will result in: ::
+
+ $ sdiff problem.txt allcharacters.txt
+ quick quick
+ brown brown
+ fox fox
+ jmuped | jumped
+ over over
+ teh | the
+ lzay | lazy
+ dog dog
+
+Some exercise for a change:
+
+ * Try using diff for any binary file, does it work?
+ * What are other equivalent for diff command based on needs/requirements?
+ * Can we use diff to compare two directories? If yes how?
+
+comm:
+-----
+
+This is one more command which proves handy at times, the short and sweet man page states "compare two sorted files line by line". Or this it compares sorted files and selects or rejects lines common to two files. For ex: ::
+
+ $ sort allcharacters.txt>sortedcharac.txt; sort problem.txt>sortedprob.txt
+ $ comm sortedcharac.txt sortedprob.txt
+ brown
+ dog
+ fox
+ jmuped
+ jumped
+ lazy
+ lzay
+ over
+ quick
+ teh
+ the
+
+Environment Variables:
+======================
+
+These variables like HOME, OSTYPE,Variables are a way of passing information from the shell to programs when you run them. Programs look "in the environment" for particular variables and if they are found will use the values stored. Standard UNIX variables are split into two categories, environment variables and shell variables. In broad terms, shell variables apply only to the current instance of the shell and are used to set short-term working conditions; environment variables have a farther reaching significance, and those set at login are valid for the duration of the session.By convention, environment variables have UPPER CASE and shell variables have lower case names.
+
+Some of examples of Environment variables are(result may vary!): ::
+
+ $ echo $OSTYPE
+ linux-gnu
+ $ echo $HOME
+ /home/baali
+
+To see all the variables and there values use any of following commands: ::
+
+ $ printenv | less
+ $ env
+
+The most commonly used environment variable is "PATH", it defines a list of directories to search through when looking for a command to execute. If you decide to put your own programs in a bin directory under your home directory, you'll have to modify the path to include that directory, or the system will never find your programs (unless you happen to be in that directory when you enter the command). Here's how to change your PATH variable so it includes your personal bin directory: ::
+
+ $ set PATH=$PATH:$HOME/bin
+
+See the difference in value of PATH variable before and after modifying it. One can also create its own variable to make things easier: ::
+
+ $ set repo = $HOME/Desktop/random/code
+ $ cd $repo
+
+*set* command is used to define a variable for the current shell. Try opening a new shell and use the above mentioned command, it wont work as expected. The other child process wont be able to see these variables unless we *export* them. Repeat the above mentioned activity with *export* command. Now with all new shells, *$repo* will work.
+
+Again these changes are limited to current session. To make them permanent or get loaded each time you log in, just add those lines to *.bashrc* file.
+
+Further Reading:
+----------------
+
+ * http://lowfatlinux.com/linux-environment-variables.html
+ * http://www.codecoffee.com/tipsforlinux/articles/030.html
+ * http://www.ee.surrey.ac.uk/Teaching/Unix/unix8.html
+ * http://en.wikipedia.org/wiki/Environment_variable
+
+
+Shell Scripting:
+================
+
+Basics:
+-------
+
+Shell program or shell script,a sequence of commands to a text file and tell the shell to execute the text file instead of entering the commands. The first *"Hello World"* sample for shell scripting is as easy as it sounds: ::
+
+ $ echo '#!/bin/sh' > my-script.sh
+ $ clear >> my-script.sh
+ $ echo 'echo Hello World' >> my-script.sh
+ $ chmod 755 my-script.sh
+ $ ./my-script.sh
+ Hello World
+
+The #! syntax(also known as shebang) is used in scripts to indicate an interpreter for execution under UNIX / Linux operating systems. The chmod is required to make the script executable. This script will just execute two commands, *clear* and *echo* one after another. One can also do the same task using a one liner command *clear; echo 'Hello World';* but as number of lines grows using a script file is helpful.
+
+So lets create a script which gives us all the filenames for given initial alphabet or string in a directory. Let the name of script be *initial.sh*, open it with text editor, and write: ::
+
+ #!/bin/sh
+ ls > temp
+ grep ^$1 < temp
+ rm temp
+ $ chmod a+x initial.sh
+ $ ./initial.sh s
+
+The $1 in the script is pertaining to command line argument. All arguments passed via command line are accessed via *$#* with name of script being first member, that is $0. Now lets write a script for finding a file, and then checking when was it last modified: ::
+
+ #!/bin/sh
+ name=`find . -name $1 -print`
+ echo $name
+ last_modified=`stat -c %y $name| cut -f 1 -d " "`
+ echo "Last modified: $last_modified"
+ $ ./search.sh fname
+
+Try giving some file you want to search in place of fname. Please note in second line *`* its a back-quote(other key mapped with tilda), it is specifically used to get the output of one command into a variable. In this particular case name is a User defined variables (UDV) which stores the value. We access value stored in any variable using *$* symbol before name of variable.
+
+naming conventions for variables?? do we need them??
+
+Shell Arithmetic:
+-----------------
+
+Shell also provides support for basic arithmetic operations. The syntax is: ::
+
+ $ expr op1 math-operator op2
+
+Some of example which can be tried handily: ::
+
+ $ expr -3 + 5
+ 2
+ $ expr 10 % 3
+ 1
+
+These spaces in between operator and operands is important, without them shell interpreter will raise the syntax error. ::
+
+ $ expr 2*3
+ expr: syntax error
+
+One can use back-quotes(`) also to get value of expr. ::
+
+ $ echo `expr 6 + 3`
+ 9
+ $ result=`expr 6 + 3`
+ $ echo $result
+ 9
+
+Shell uses three kinds of quotes. Double quotes("), anything enclosed among them except from variable trailing after $, and characters after \ would be printed as it is. Single quotes('), anything enclosed within them is just same, no formulation/interpretation. Back quotes(`), anything inclosed is considered as command, or is executed. ::
+
+ $ echo "Today is date"
+ Today is date
+ $ echo "Today is `date`"
+ Today is Wed Sep 16 17:32:22 IST 2009
+ $ echo 'Today is `date`'
+ Today is `date`
+ $ echo "Today is \n `date`"
+ Today is \n Wed Sep 16 17:40:13 IST 2009
+ $ echo -e "Today is \n `date`"
+ Today is
+ Wed Sep 16 17:41:13 IST 2009
+
+if else construct:
+------------------
+
+One can have simple *if else if* constructs in shell scripts to check conditions. Lets take simple example of writing a script which returns back whether the argument passed is positive or not: ::
+
+ #!/bin/sh
+ if test $1 -gt 0
+ then
+ echo "number is positive"
+ else
+ echo "number is negative"
+ fi
+ $ ./sign.sh -11
+ number is negative
+
+This script will compare the first value passed as argument with 0 *if test var -gt val*, var being $1 and val being 0, gt meaning greater then. Now this program has some flaw, it will give same result for following input: (-11) and (-1, 5), as we are checking just $1 which is first argument and hence the result. For handling such situation we can include *if-else* clause which will warn user of correct usage of script. ::
+
+ #this is the case when no argument is passed
+ if [ $# -eq 0 ]
+ then
+ echo "$0 : You must give/supply one integers"
+ exit 1
+ else
+ if [ $# -gt 1 ]
+ then
+ echo "$0 : You must give one integer"
+ exit 1
+ fi
+ fi
+
+One important thing to not in shell script is spacing, with many comparison and evaluation operation a wrongly placed space will spoil all the fun. So in previous example the expression *[ $# -eq 0 ]* will work properly, but if we remove those leading or trailing spaces like *[ $# -eq 0]*, it wont work as expected, or rather throw a warning. Both *test* and *[]* do the same task of testing a expression and returning true or false.
+
+Lets create something interesting using these if-else clause. Now we will create a script which will greet the user when he opens the shell. We will create the script, change the permission to make it executable and append the *.bashrc* file with *./greet.sh* line and we are done. The script is: ::
+
+ #!/bin/sh
+ #Script to greet the user according to time of day
+ temph=`date | cut -c12-13`
+ dat=`date +"%A %d in %B of %Y (%r)"`
+ if [ $temph -lt 12 ]
+ then
+ mess="Good Morning $LOGNAME, Have a nice day!"
+ fi
+
+ if [ $temph -gt 12 -a $temph -le 16 ]
+ then
+ mess="Good Afternoon $LOGNAME"
+ fi
+
+ if [ $temph -gt 16 -a $temph -le 18 ]
+ then
+ mess="Good Evening $LOGNAME"
+ fi
+ echo -e "$mess\nThis is $dat"
+
+For me when I open the shell the output is something like: ::
+
+ Good Morning baali, Have a nice day!
+ This is Wednesday 16 in September of 2009 (11:54:47 AM IST)
+
+Loops
+-----
+
+Bash has three different commands for looping -- ``for``, ``while`` and ``until``.
+
+``for`` loop
+~~~~~~~~~~~~
+
+Suppose we have a set of files, that have names beginning with numbers followed by their names - ``08 - Society.mp3``. We would like to rename these files to remove the numbering. How would we go about doing that? It is clear from the problem statement that we could use a ``for`` loop, to loop through the list of files and rename each of the files.
+
+Let's first look at a simple ``for`` loop, to understand how it works.
+::
+
+ for animal in rat cat dog man
+ do
+ echo $animal
+ done
+
+We just wrote a list of animals, each animal's name separated by a space and printed each name on a separate line. The variable ``animal`` is a dummy variable and has no significance. You could use something as lame as ``i`` in place of ``animal``.
+
+Now, we use a simple ``for`` loop to list the files that we are interested in.
+::
+
+ ls *.mp3 > list
+ for i in `cat list`
+ do
+ echo "$i"
+ done
+
+If your filenames contain spaces, ``for`` assumes each space separated word to be a single item in the list and prints it in a separate line. We could change the script slightly to overcome this problem.
+::
+
+ for i in *.mp3
+ do
+ echo "$i"
+ done
+
+Now, we have each file printed on a separate line. Depending on the files that we have we could use grep to get the relevant portion of the filenames and rename the files.
+::
+
+ for i in *.mp3
+ do
+ j=$(echo "$i"|grep -o "[A-Za-z'&. ]*.mp3")
+ echo "$i -> $j"
+ done
+
+Now we just replace the echo command with a ``mv`` or a ``cp`` command.
+::
+
+ for i in *.mp3
+ do
+ j=$(echo "$i"|grep -o "[A-Za-z'&. ]*.mp3")
+ cp "$i" "$j"
+ done
+
+As an exercise, you could try sorting the files in reverse alphabetical order and then prefix numbers to each of the filenames.
+
+``while``
+~~~~~~~~~
+
+The ``while`` command allows us to continuously execute a block of commands until the command that is controlling the loop is executing successfully.
+
+Let's start with the lamest example of a while loop.
+::
+
+ while true
+ do
+ echo "True"
+ done
+
+This, as you can see, is an infinite loop that prints the ``True``.
+
+Say we wish to write a simple program that takes user input and prints it back, until the input is ``quit``, which quits the program.
+::
+
+ while [ "$variable" != "quit" ]
+ do
+ read variable
+ echo "Input - $variable"
+ done
+ exit 0
+
+``until``
+~~~~~~~~~
+
+The ``until`` loop is similar to the ``while`` loop, except that it executes until the conditional command does not execute properly.
+
+The infinite loop changes to the following, when ``until`` is used.
+::
+
+ until false
+ do
+ echo "True"
+ done
+
+Now lets try and use these above mentioned options provided by shell to write a utility. Until now, when we try find or locate it looks through directories and files for result. But they wont search through tar archives and zipped files. Lets create a shell script for especially looking through these files
+::
+
+ #!/bin/sh
+
+ #To check number of arguments being passed.
+ if [ $# -eq 0 ] ; then
+ echo "Correct usage: $0 tar-archive filename \nOr $0 filename"
+ exit 1
+ else
+ if [ $# -eq 1 ] ; then
+ tar_archive=`find $PWD -name "*.tar*"`
+ else
+ tar_archive=`find $PWD -name $1`
+ fi
+ fi
+
+ #Search of particular file inside archives.
+ for archive in $tar_archive
+ do
+ echo $archive
+ variable=`tar -tf $archive`
+ for word in $variable
+ do
+ if [ $# -eq 1 ] ; then
+ echo "$word" | grep -q ".*$1"
+ else
+ echo "$word" | grep -q ".*$2"
+ fi
+ if [ $? -eq 0 ] ; then
+ echo "File present in $archive!"
+ fi
+ done
+ done
+
+
+Functions
+---------
+
+When a group of commands are repeatedly being used within a script, it is convenient to group them as a function. This saves a lot of time and you can avoid retyping the code again and again. Also, it will help you maintain your code easily. Let's see how we can define a simple function, ``hello-world``. Functions can be defined in bash, either using the ``function`` built-in followed by the function name or just the function name followed by a pair of parentheses.
+::
+
+ function hello-world
+ {
+ echo "Hello, World.";
+ }
+
+ hello-world () {
+ echo "Hello, World.";
+ }
+
+ $ hello-world
+ Hello, World.
+
+Passing parameters to functions is similar to passing them to scripts.
+::
+
+ function hello-name
+ {
+ echo "Hello, $1.";
+ }
+
+ $ hello-name 9
+ Hello, 9.
+
+Any variables that you define within a function, will be added to the global namespace. If you wish to define variables that are restricted to the scope of the function, define a variable using the ``local`` built-in command of bash.
+
+We shall now write a function for the word frequency generating script that we had looked at in the previous session.
+
+::
+
+ function word_frequency {
+ if [ $# -ne 1 ]
+ then
+ echo "Usage: $0 file_name"
+ exit 1
+ else
+ if [ -f "$1" ]
+ then
+ grep "[A-Za-z]*" -o "$1" | tr 'A-Z' 'a-z' | sort | uniq -c | sort -nr | less
+ fi
+ fi
+ }
+
+As an exercise, modify the function to accept the input for the number of top frequency words to be shown (if none is given, assume 10).
+
+
+Further Reading:
+----------------
+ * http://www.freeos.com/guides/lsst/
+ * http://bash.cyberciti.biz/guide/Main_Page
+ * http://tldp.org/LDP/abs/html/
+ * http://tldp.org/LDP/Bash-Beginners-Guide/html/Bash-Beginners-Guide.html
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/Using_Linux_Tools.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,1513 @@
+Introducing Linux
+=================
+
+(Attribution : A significant chunk of the content under this section is based on data from Wikipedia and the Linux Documentation Project)
+
+Linux (usually pronounced ˈlɪnəks') is a generic term referring to Unix-like computer operating systems based on the Linux kernel, where a kernel is the intermediate layer between the hardware and the applications. The kernel is, on an abstract level, the core of (most) operating systems, that manages the various system resources. The development of the Linux OS is considered the basis for Free and Open Source Software (FOSS) collaboration since typically the underlying source code can be used, modified freely, and redistributed by anyone under the terms of the GNU (a recursive acronym for "GNU's Not Unix!") Global Public License (GPL) and other free software licences. This freedom to access and reuse various components of a system, is one of the primary reasons for the popularity of Linux.
+
+Linux is installed on a variety of computer hardware, that include mobile phones, embedded devices and supercomputers, but is infamous for its use in servers.
+
+The name "Linux" comes from the Linux kernel, originally written in 1991 by Linus Torvalds. The rest of the system usually comprises components such as the Apache HTTP Server, the X Window System, the GNOME and KDE desktop environments, and utilities and libraries from the GNU Project (announced in 1983 by Richard Stallman). Commonly-used applications with desktop Linux systems include the Mozilla Firefox web-browser and the OpenOffice.org office application suite. The GNU contribution is the basis for the Free Software Foundation's preferred name GNU/Linux. The kernel's mascot is a penguin named "Tux". Mozilla Firefox and OpenOffice.org are open-source projects which can be run on most Operating Systems, including proprietary ones.
+
+Historical Background
+----------------------
+
+Events leading to the creation
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+- The Unix operating system was developed in the 1960s and released for public use in 1970. Its accessibility and portability caused it to be widely adopted, copied and modified by academic institutions and businesses. Its design became influential to authors of other systems. Other free operating systems include the Berkeley Software Distribution (BSD), developed at the University of California at Berkeley, and MINIX which was released by Andrew S. Tanenbaum. The development and adoption of BSD and MINIX were limited due to various reasons, and this lack of a widely-adopted and free kernel triggered Linus Torvalds into starting his project.
+
+- In 1983, Richard Stallman started the GNU project with the goal of creating a free UNIX-like operating system. As part of this work, he wrote the GNU General Public License (GPL). By the early 1990s there was almost enough available software to create a full operating system. However, the GNU kernel, called Hurd, failed to attract enough attention from developers leaving GNU incomplete.
+
+The Creation of Linux
+~~~~~~~~~~~~~~~~~~~~~~
+In 1991, Linus Torvalds began a project at the University of Helsinki that later became the Linux kernel. It was initially a terminal (command-line) emulator, which Torvalds used to access the large UNIX servers of the university. He wrote the program targeting just the hardware he was using and independent of an operating system because he wanted to use the functions of his computer with an 80386 processor. Development was done on Minix using the GNU C compiler. This application is still the main choice for compiling Linux today (although the code can be built with other compilers, such as the Intel C Compiler).
+
+Torvalds continues to direct the development of the kernel. Stallman heads the Free Software Foundation, which in turn supports the GNU components. Finally, individuals and corporations develop third-party non-GNU components, which constitute a vast body of work and including kernel modules, and user applications and libraries. Linux vendors and communities combine and distribute the kernel, GNU components, and non-GNU components, with additional package management software in the form of Linux distributions.
+
+
+Design and Implications
+------------------------
+
+A Linux-based system is a modular Unix-like operating system, deriving much of its basic design from principles established in Unix earlier. Such a system uses a monolithic kernel, called the Linux kernel, which handles process control, networking, and peripheral and file system access. Device drivers are integrated directly with the kernel. Separate projects that interface with the kernel provide much of the system's higher-level functionality. The GNU userland is an important part of most Linux-based systems, providing the most common implementation of the C library, a popular shell, and many of the common Unix tools which carry out many basic operating system tasks. The graphical user interface (or GUI) used by most Linux systems is based on the "X Window System".
+
+User Interface
+~~~~~~~~~~~~~~
+Users can control a Linux-based system through a command line interface (or CLI), a graphical user interface (or GUI), or through controls attached to the associated hardware (this is common for embedded systems). For desktop systems, the default mode is usually the GUI. On desktop machines, "KDE", "GNOME" and "Xfce" are the most popular user interfaces,though a variety of additional user interfaces exist. Most popular user interfaces run on top of the "X Window System" (or X), which enables a graphical application running on one machine to be displayed and controlled from another in a network.
+
+A Linux system also provides a CLI of some sort through a shell, which is the traditional way of interacting with a Unix system. A Linux distribution specialized for servers may use the CLI as its only interface. A “headless system” (system run without even a monitor) can be controlled by the command line via a remote-control protocol such as SSH or telnet. The CLI is particularly suited for automation of repetitive or delayed tasks, and provides very simple inter-process communication. A graphical terminal emulator program is often used to access the CLI from a Linux desktop.
+
+Development
+~~~~~~~~~~~
+The primary difference between Linux and many other popular contemporary operating systems is that the Linux kernel and other components are free and open source software. Linux is not the only such operating system, although it is by far the most widely used. Some free and open source software licenses are based on the principle of "copyleft", a kind of reciprocity: any work derived from a copyleft piece of software must also be copyleft itself. The most common free software license, the GNU GPL, is a form of copyleft, and is used for the Linux kernel and many of the components from the GNU project.
+
+Linux based distributions are intended by developers for interoperability with other operating systems and established computing standards. Linux systems adhere to POSIX, SUS, ISO and ANSI standards where possible, although to date only one Linux distribution has been POSIX.1 certified, Linux-FT.Free software projects, although developed in a collaborative fashion, are often produced independently of each other. The fact that the software licenses explicitly permit redistribution, however, provides a basis for larger scale projects that collect the software produced by stand-alone projects and make it available all at once in the form of a Linux distribution.
+
+A Linux distribution, commonly called a "distro", is a project that manages a remote collection of system software and application software packages available for download and installation through a network connection. This allows the user to adapt the operating system to his/her specific needs. Distributions are maintained by individuals, loose-knit teams, volunteer organizations, and commercial entities. A distribution can be installed using a CD that contains distribution-specific software for initial system installation and configuration. A package manager such as Synaptic or YAST allows later package upgrades and installations. A distribution is responsible for the default configuration of the installed Linux kernel, general system security, and more generally integration of the different software packages into a coherent whole.
+
+Community
+~~~~~~~~~
+A distribution is largely driven by its developer and user communities. Some vendors develop and fund their distributions on a volunteer basis. Examples include Debian and the Debian-based, Ubuntu. Others maintain a community version of their commercial distributions, as Red Hat does with Fedora.
+
+In many cities and regions, local associations known as Linux Users Groups (LUGs) seek to promote their preferred distribution and by extension free software. They hold meetings and provide free demonstrations, training, technical support, and operating system installation to new users. Many Internet communities also provide support to Linux users and developers. Most distributions and free software / open source projects have IRC (Internet Relay Chat) chatrooms or newsgroups. Online forums are another means for support. Linux distributions host mailing lists; commonly there will be a specific topic such as usage or development for a given list. All these can be found simply by running an appropriate search on Google.
+
+Although Linux distributions are generally available without charge, several large corporations sell, support, and contribute to the development of the components of the system and of free software. These include Dell, IBM, HP, Oracle, Sun Microsystems, Novell, Nokia. A number of corporations, notably Red Hat, have built their entire business around Linux distributions.
+
+Can I make a profit out of running a business involving Linux?
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The answer is, "Yes!". The free software licenses, on which the various software packages of a distribution built on the Linux kernel are based, explicitly accommodate and encourage commercialization; the relationship between a Linux distribution as a whole and individual vendors may be seen as symbiotic. One common business model of commercial suppliers is charging for support, especially for business users. A number of companies also offer a specialized business version of their distribution, which adds proprietary support packages and tools to administer higher numbers of installations or to simplify administrative tasks. Another business model is to give away the software in order to sell hardware. Examples of corporations that are extensively (and sometimes exclusively) open-source and Linux-powered , with successful revenue generation models involving these, are Google, SUN, Mozilla, etc.
+
+Programming on Linux
+~~~~~~~~~~~~~~~~~~~~
+Most Linux distributions support dozens of programming languages. The most common collection of utilities for building both Linux applications and operating system programs is found within the GNU toolchain, which includes the GNU Compiler Collection (GCC) and the GNU build system. Amongst others, GCC provides compilers for Ada, C, C++, Java, and Fortran. The Linux kernel itself is written to be compiled with GCC. Proprietary compilers for Linux include the Intel C++ Compiler, Sun Studio, and IBM XL C/C++ Compiler.
+
+Most distributions also include support for PHP, Perl, Ruby, Python and other dynamic languages. Examples of languages that are less common, but still supported, are C# via the Mono project, sponsored by Novell, and Scheme. A number of Java Virtual Machines and development kits run on Linux, including the original Sun Microsystems JVM (HotSpot), and IBM's J2SE RE, as well as many open-source projects like Kaffe.
+
+The two main frameworks for developing graphical applications are those of GNOME and KDE. These projects are based on the GTK+ and Qt widget toolkits, respectively, which can also be used independently of the larger framework. Both support a wide variety of languages. There are a number of Integrated Development Environments (IDEs) available including Anjuta, Code::Blocks, Eclipse, KDevelop, Lazarus, MonoDevelop, NetBeans, and Omnis Studio while the long-established editors Vim and Emacs remain popular.
+
+Reasons for Using Linux
+-----------------------
+- Linux is free:
+
+As in "free beer". Linux can be downloaded in its entirety from the Internet completely for free. No registration fees, no costs per user, free updates, and freely available source code in case you want to change the behavior of your system.
+Most of all, Linux is free as in "free speech":
+The license commonly used is the GNU Public License (GPL). The license says that anybody who may want to do so, has the right to change Linux and eventually to redistribute a changed version, on the one condition that the code is still available after redistribution. In practice, you are free to grab a kernel image and sell the new code, as long as your customers can still have a copy of that code.
+
+- Linux is portable to any hardware platform:
+
+A vendor, who wants to sell a new type of computer and who does not know what kind of OS his/her new machine will run, can take a Linux kernel and make it work on his/her hardware, because documentation related to this activity is freely available.
+
+- Linux was made to keep on running:
+
+As with UNIX, a Linux system expects to run without rebooting all the time. That is why a lot of tasks are being executed at night or scheduled automatically for other times, resulting in higher availability during busier periods and a more balanced use of the hardware. This property allows for Linux to be applicable to environments where people do not have the time or the possibility to control their systems constantly.
+
+- Linux is secure and versatile:
+
+The security model used in Linux is based on the UNIX idea of security, which is known to be robust and of proven quality. But Linux is not only safe from attacks from the Internet: it will adapt equally to other situations, utilizing the same high standards for security.
+
+- Linux is scalable:
+
+From a Palmtop with 2 MB of memory to a petabyte storage cluster with hundreds of nodes: add or remove the appropriate packages and Linux fits all. One does not need a supercomputer anymore,because you can use Linux to do big things using the building blocks provided with the system. If one wants to do little things, such as making an operating system for an embedded processor or just recycling your old 486, Linux will do that as well.
+
+- The Linux OS and Linux applications have very short debug−times:
+
+Because Linux has been developed and tested by thousands of people, both errors and people to fix them are found very quickly. It often happens that there are only a couple of hours between discovery and fixing of a bug.
+
+Getting Started
+================
+
+Logging in, activating the user interface and logging out
+----------------------------------------------------------
+In order to work on a Linux system directly, one needs to provide a user name and password. You always need to authenticate to the system. Most PC−based Linux systems have two basic modes for a system to run in: either quick and clean in text console mode,which includes with mouse, multitasking and multi−user features, or in graphical console mode, which looks better but eats more system resources.
+
+Graphical Mode
+~~~~~~~~~~~~~~
+This is the default nowadays on most desktop computers. You know you will be connecting to the system using graphical mode when you are first asked for your user name, and then to type your password.
+
+To log in, make sure the mouse pointer is in the login window, provide your user name and password to the system and click *OK* or press *Enter*.
+It is generally considered a bad idea to connect (graphically) using the root user name, the system adminstrator's account, since the use of graphics includes running a lot of extra programs, in root's case with a lot of extra permissions. To keep all risks as low as possible, use a normal user account to connect graphically. But there are enough risks to keep this in mind as a general advice, for all use of the root account: only log in as root when extra privileges are required.
+
+After entering your user name/password combination, it can take a little while before the graphical environment is started, depending on the CPU speed of your computer, on the software you use and on your personal settings.
+
+To continue, you will need to open a *terminal window* or *xterm* for short (X being the name for the underlying software supporting the graphical environment). This program can be found in the *Applications−>Utilities->System Tools* or *Internet menu*, depending on what window manager you are using. There might be icons that you can use as a shortcut to get an *xterm* window as well, and clicking the right mouse button on the desktop background will usually present you with a menu containing a terminal window application.
+
+While browsing the menus, you will notice that a lot of things can be done without entering commands via the keyboard. For most users, the good old point−n−click method of dealing with the computer will do. But for those who want to enter the "heart" of the system, a tool stronger than a mouse will be required to handle the various tasks. This tool is the shell, and when in graphical mode, we activate our shell by opening a terminal window.
+
+A terminal window should always show a command prompt when you open one. This terminal shows a standard prompt, which displays the user's login name, and the current working directory, represented by the twiddle (~)
+
+Another common form for a prompt is this one:
+[user@host dir]
+
+In the above example, *user* will be your login name, *hosts* the name of the machine you are working on, and *dir* an indication of your current location in the file system. Prompts can display all kinds of information, but they are not part of the commands you are giving to your system. To disconnect from the system in graphical mode, you need to close all terminal windows and other applications. After that, hit the *logout* icon or find *Log Out* in the menu. Closing everything is not really necessary, and the system can do this for you, but session management might put all currently open applications back on your screen when you connect again, which takes longer and is not always the desired effect. However, this behavior is configurable.
+
+When you see the login screen again, asking to enter user name and password, logout was successful.
+
+Text Mode
+~~~~~~~~~
+One is in text mode when the whole screen is black, showing (in most cases white) characters. A text mode login screen typically shows some information about the machine you are working on, the name of the machine and a prompt waiting for you to log in.
+
+The login is different from a graphical login, in that you have to hit the *Enter* key after providing your user name, because there are no buttons on the screen that you can click with the mouse. Then you should type your password, followed by another *Enter*. You will not see any indication that you are entering something, not even an asterisk, and you won't see the cursor move. But this is normal on Linux and is done for security
+reasons.
+
+When the system has accepted you as a valid user, you may get some more information, called the *message of the day*, which can be anything. Additionally, it is popular on UNIX systems to display a fortune cookie, which contains some general wise or unwise (this is up to you) thoughts. After that, you will be given a shell, indicated with the same prompt that you would get in graphical mode.
+
+Also in text mode: log in as root only to do setup and configuration that absolutely requires administrator privileges, such as adding users, installing software packages, and performing network and other system configuration. Once you are finished, immediately leave the special account and resume your work as a non−privileged user.
+
+Logging out is done by entering the *logout* command, followed by Enter. You are successfully disconnected from the system when you see the login screen again.Don't power−off the computer after logging out. It is not meant to be shut off without application of the proper procedures for halting the system. Powering it off without going through the halting process might cause severe damage!
+
+Basic Commands
+===============
+
+ls
+---
+
+When invoked without any arguments, *ls* lists the files in the current working directory. A directory that is not the current working directory can be specified and ls will list the files there. The user also may specify any list of files and directories. In this case, all files and all contents of specified directories will be listed. The name *ls* is derived from *list segments* which was used in earlier systems.
+
+Files whose names start with "." are not listed, unless the *-a* flag is specified or the files are specified explicitly.
+
+Without options, *ls* displays files in a bare format. This bare format however makes it difficult to establish the type, permissions, and size of the files. The most common options to reveal this information or change the list of files are:
+
+ * *-l* long format, displaying Unix file types, permissions, number of hard links, owner, group, size, date, and filename
+ * *-F* appends a character revealing the nature of a file, for example, * for an executable, or / for a directory. Regular files have no suffix.
+ * *-a* lists all files in the given directory, including those whose names start with "." (which are hidden files in Unix). By default, these files are excluded from the list.
+ * *-R* recursively lists subdirectories. The command ls -R / would therefore list all files.
+ * *-d* shows information about a symbolic link or directory, rather than about the link's target or listing the contents of a directory.
+ * *-t* sort the list of files by modification time.
+ * *-h* print sizes in human readable format. (e.g., 1K, 234M, 2G, etc.)
+
+In some environments, providing the option *--color* (for GNU ls) or *-G* (FreeBSD ls) causes ls to highlight different types of files with different colors, instead of with characters as *-F* would. To determine what color to use for a file, GNU *ls* checks the Unix file type, the file permissions, and the file extension, while FreeBSD *ls* checks only the Unix file type and file permissions.::
+
+ $ ls
+ jeeves.rst psmith.html blandings.html
+ $ ls -l
+ drwxr--r-- 1 plum editors 4096 jeeves
+ -rw-r--r-- 1 plum editors 30405 psmith
+ -r-xr-xr-x 1 plum plum 8460 blandings
+
+Here "$" actually is the beginning of the prompt. This is typical in most Unix-based systems.
+
+date
+-----
+
+The Unix date command displays the time and date. The super-user can use it to set the system clock.
+
+With no options, the date command displays the current date and time, including the abbreviated day name, abbreviated month name, day of the month, the time separated by colons, the timezone name, and the year. For example::
+
+ $date
+ Tue Sep 8 12:01:45 IST 2009
+
+On some systems to set the current date and time to September 8, 2004 01:22 you type::
+
+ $date --set="20040908 01:22"
+
+In order to view the various options for the *date* command, type::
+
+ $man date
+
+This will take you to the "Manual" page comprising of all the details on the *date* command. You can return to the terminal from the "man" page by pressing the *Esc* key in the keyboard and typing ":q" in that order.
+
+cd
+---
+
+This stands for "change directory". When one wants to go up to the parent directory, bypassing the tree of directories one has entered, “ cd ..” can be used.
+
+One dot '.' represents the current directory while two dots '..' represent the parent directory.
+
+“ cd -” will return you to the previous directory (a bit like an “undo”).
+
+You can also use cd absolute path or cd relative path (see below):
+
+Absolute paths:
+
+ An “ absolute path” is easily recognised from the leading forward slash, /. The / means that you start at the top level directory and continue down.
+
+For example to get to /boot/grub you would type::
+
+ $cd /boot/grub
+
+This is an absolute path because you start at the top of the hierarchy and go downwards from there (it doesn't matter where in the filesystem you were when you typed the command).
+
+Relative paths:
+
+ A “ relative path” doesn't have a preceding slash. Use a relative path when you start from a directory below the top level directory structure. This is dependent on where you are in the filesystem.
+
+ For example if you are in root's home directory and want to get to /root/music, you type::
+
+ $ cd music
+
+Please note that there is no / using the above cd command. Using a / would cause this to be an absolute path, working from the top of the hierarchy downward.
+
+who
+----
+
+The standard Unix command *who* displays a list of users who are currently logged into a computer.
+
+The *who* command is related to the command *w*, which provides the same information but also displays additional data and statistics.::
+
+ $who
+ beeblebrox tty7 2009-09-08 10:50 (:0)
+ beeblebrox pts/0 2009-09-08 11:25 (:0.0)
+ dumbledore pts/1 2009-09-08 18:11 (potter.xyz.in)
+ beeblebrox pts/2 2009-09-08 18:53 (:0.0)
+
+
+The command can be invoked with the arguments *am i* or *am I* (so it is invoked as *who am i* or * who am I*), showing information about the current terminal only (see the *-m* option below, of which this invocation is equivalent).
+
+In order to find out the various options that can be appended to the *who* command, check the *man* page by typing out the following in the terminal::
+
+ $man who
+
+This will take you to the "Manual" page containing details about the *who* command
+
+mkdir
+-----
+
+This command is used to make a new directory. Normal usage is as straightforward as follows::
+
+ $mkdir name_of_directory
+
+Where *name_of_directory* is the name of the directory one wants to create. When typed as above (ie. normal usage), the new directory would be created within the current directory. On Unix, multiple directories can be specified, and *mkdir* will try to create all of them.
+
+Options
+~~~~~~~
+
+On Unix-like operating systems, *mkdir* takes options. Three of the most common options are:
+
+ * *-p*: will also create all directories leading up to the given directory that do not exist already. If the given directory already exists, ignore the error.
+ * *-v*: display each directory that mkdir creates. Most often used with -p.
+ * *-m*: specify the octal permissions of directories created by mkdir.
+
+*-p* is most often used when using mkdir to build up complex directory hierarchies, in case a necessary directory is missing or already there. -m is commonly used to lock down temporary directories used by shell scripts.
+
+Examples
+~~~~~~~~
+
+An example of *-p* in action is::
+
+ $mkdir -p /tmp/a/b/c
+
+If */tmp/a* exists but */tmp/a/b* does not, mkdir will create */tmp/a/b* before creating */tmp/a/b/c*.
+
+And an even more powerful command, creating a full tree at once (this however is a Shell extension, nothing mkdir does itself)::
+
+ $mkdir -p tmpdir/{trunk/sources/{includes,docs},branches,tags}
+
+This will create:
+
+tmpdir - branches
+ - tag
+ - trunk - sources - includes
+ - docs
+
+Getting Help
+============
+
+apropos and whatis
+-------------------
+
+This is a command to search the manual pages files in Unix and Unix-like operating systems. ::
+
+ $ apropos grep
+ egrep egrep (1) Search a file for a pattern using full regular expressions
+ fgrep fgrep (1) Search a file for a fixed-character string
+ fmlgrep fmlgrep (1) Search a file for a pattern
+ grep grep (1) Search a file for a pattern
+ gzgrep gzgrep (1) Search a possibly compressed file for a regular expression
+ nisgrep nismatch (1) Utilities for searching NIS+ tables
+ pgrep pgrep (1) Find or signal a process by name or other attribute
+ zgrep zgrep (1) Search a possibly compressed file for a regular expression
+ ...
+
+In this example, the user uses *apropos* to search for the string "grep", and apropos returns the indicated *man* pages that include the term "grep".
+
+A short index of explanations for commands is available using the *whatis* command, like in the examples below::
+
+ $whatis ls
+ ls (1) - list directory contents
+
+This displays short information about a command, and the first section in the collection of man pages that contains an appropriate page.
+
+If you don't know where to get started and which man page to read, *apropos* gives more information. Say that you do not know how to start a browser, then you could enter the following command::
+
+ $apropos browser
+ gmusicbrowser (1) - Jukebox for large collections of audio files
+ infobrowser (1) - read Info documents
+ libsmbclient (7) - An extension library for browsers and that can be used...
+ opera (1) - a standards-compliant graphical Web browser
+ sensible-browser (1) - sensible editing, paging, and web browsing
+ smbtree (1) - A text based smb network browser
+ tvtk_doc (1) - A GUI based TVTK documentation search browser.
+ viewres (1) - graphical class browser for Xt
+ w3m (1) - a text based Web browser and pager
+ www-browser (1) - a text based Web browser and pager
+ ...
+
+man
+----
+
+Man pages (short for "manual pages") are the extensive documentation that comes preinstalled with almost all substantial Unix and Unix-like operating systems. The Unix command used to display them is *man*. Each page is a self-contained document.
+
+To read a manual page for a Unix command, one can use::
+
+ $ man <command_name>
+
+at a shell prompt; for example, "man ftp". In order to simplify navigation through the output, *man* generally uses the less terminal pager.
+
+Pages are traditionally referred to using the notation "name(section)"; for example, ftp(1). The same page name may appear in more than one section of the manual, this can occur when the names of system calls, user commands, or macro packages coincide. Two examples are *man(1)* and *man(7)*, or *exit(2)* and *exit(3)*. The syntax for accessing the non-default manual section varies between different man implementations. On Linux and *BSD, for example, the syntax for reading *printf(3)* is::
+
+ $man 3 printf
+
+Another example::
+
+ $man man
+
+The previous example will take you to the "Manual" page entry about manual pages!
+
+Layout
+~~~~~~
+
+All man pages follow a common layout that is optimized for presentation on a simple ASCII text display, possibly without any form of highlighting or font control. Sections present may include:
+
+NAME
+ The name of the command or function, followed by a one-line description of what it does.
+SYNOPSIS
+ In the case of a command, you get a formal description of how to run it and what command line options it takes. For program functions, a list of the parameters the function takes and which header file contains its definition. For experienced users, this may be all the documentation they need.
+DESCRIPTION
+ A textual description of the functioning of the command or function.
+EXAMPLES
+ Some examples of common usage.
+SEE ALSO
+ A list of related commands or functions.
+
+Other sections may be present, but these are not well standardized across man pages. Common examples include: OPTIONS, EXIT STATUS, ENVIRONMENT, KNOWN BUGS, FILES, AUTHOR, REPORTING BUGS, HISTORY and COPYRIGHT.
+
+These days virtually every Unix command line application comes with its man page, and many Unix users perceive a lack of man pages as a sign of low quality; indeed, some projects, such as Debian, go out of their way to write man pages for programs lacking one. Few alternatives to *man* have enjoyed much popularity, with the possible exception of the GNU project's "info" system, an early and simple hypertext system.
+
+However, the format of a single page for each application, the lack of classification within the sections and the relatively unsophisticated formatting facilities have motivated the development of alternative documentation systems, such as the previously mentioned "info" system.
+
+Most Unix GUI applications (particularly those built using the GNOME and KDE development environments) now provide end-user documentation in HTML and include embedded HTML viewers such as yelp for reading the help within the application.
+
+Usually the man pages are written in English. Translations into other languages can be also available on the system.
+
+The default format of the man pages is troff, with either the macro package man (appearance oriented) or on some systems mdoc (semantic oriented). This makes it possible to typeset a man page to PostScript, PDF and various other formats for viewing or printing.
+
+info
+-----
+
+*info* is a software utility which forms a hypertextual, multipage documentation and help viewer working on a command line interface, useful when there is no GUI available.
+
+The syntax is ::
+
+ $ info <command_name>
+
+*info* processes info files, which are Texinfo formatted files, and presents the documentation as a tree, with simple commands to traverse the tree and to follow cross references. For instance
+
+ - *n* goes to the next page.
+ - *p* goes to the previous page.
+ - *u* goes to the upper page.
+ - *l* goes to the last(visited) node
+ - To follow a cross reference, the cursor can be moved over a link (a word preceded by a `*`) and enter pressed.
+
+info was initially written for use with GNU/Linux and then ported to other Unix-like operating systems.
+
+--help
+-------
+
+Most GNU commands support the --help, which gives a short explanation about how to use the command and a list of available options. Below is the output of this option with the *cat* command::
+
+ $ userprompt@host: cat --help
+ Usage: cat [OPTION] [FILE]...
+ Concatenate FILE(s), or standard input, to standard output.
+
+ -A, --show-all equivalent to -vET
+ -b, --number-nonblank number nonempty output lines
+ -e equivalent to -vE
+ -E, --show-ends display $ at end of each line
+ -n, --number number all output lines
+ -s, --squeeze-blank suppress repeated empty output lines
+ -t equivalent to -vT
+ -T, --show-tabs display TAB characters as ^I
+ -u (ignored)
+ -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
+ --help display this help and exit
+ --version output version information and exit
+
+ With no FILE, or when FILE is -, read standard input.
+
+ Examples:
+ cat f - g Output f's contents, then standard input, then g's contents.
+ cat Copy standard input to standard output.
+
+ Report bugs to <bug-coreutils@gnu.org>.
+
+
+Basic file handling
+===================
+
+cp
+---
+
+*cp* is the command entered in a Unix shell to copy a file from one place to another, possibly on a different filesystem. The original file remains unchanged, and the new file may have the same or a different name.
+
+Usage
+~~~~~
+
+To copy a file to another file::
+
+ $ cp [ -f ] [ -H ] [ -i ] [ -p ][ -- ] SourceFile TargetFile
+
+To copy a file to a directory::
+
+ $ cp [ -f ] [ -H ] [ -i ] [ -p ] [ -r | -R ] [ -- ] SourceFile ... TargetDirectory
+
+To copy a directory to a directory::
+
+ $ cp [ -f ] [ -H ] [ -i ] [ -p ] [ -- ] { -r | -R }
+ SourceDirectory ... TargetDirectory
+
+Flags
+~~~~~
+
+*-f* (force) – specifies removal of the target file if it cannot be opened for write operations. The removal precedes any copying performed by the cp command.
+
+*-P* – makes the cp command copy symbolic links. The default is to follow symbolic links, that is, to copy files to which symbolic links point.
+
+*-i* (interactive) – prompts you with the name of a file to be overwritten. This occurs if the TargetDirectory or TargetFile parameter contains a file with the same name as a file specified in the SourceFile or SourceDirectory parameter. If you enter y or the locale's equivalent of y, the cp command continues. Any other answer prevents the cp command from overwriting the file.
+
+*-p* (preserve) – duplicates the following characteristics of each SourceFile/SourceDirectory in the corresponding TargetFile and/or TargetDirectory:
+
+ * The time of the last data modification and the time of the last access.
+ * The user ID and group ID (only if it has permissions to do this)
+ * The file permission bits and the SUID and SGID bits.
+
+*-R* (recursive) – copy directories (recursively copying all the contents)
+
+Examples
+~~~~~~~~
+
+To make a copy of a file in the current directory, enter::
+
+ $ cp prog.c prog.bak
+
+This copies prog.c to prog.bak. If the prog.bak file does not already exist, the cp command creates it. If it does exist, the cp command replaces it with a copy of the prog.c file.
+
+To copy a file in your current directory into another directory, enter::
+
+ $ cp zaphod /home/books/hhgg
+
+This copies the jones file to /home/books/hhgg/zaphod.
+
+To copy a file to a new file and preserve the modification date, time, and access control list associated with the source file, enter::
+
+ $ cp -p martin_luther_king martin_luther_king.jr
+
+This copies the *martin_luther_king* file to the *martin_luther_king.jr* file. Instead of creating the file with the current date and time stamp, the system gives the *martin_luther_king.jr* file the same date and time as the *martin_luther_king* file. The *martin_luther_king.jr* file also inherits the *martin_luther_king* file's access control protection.
+
+To copy all the files in a directory to a new directory, enter::
+
+ $ cp /home/galactica/clients/* /home/hhgg/customers
+
+This copies only the files in the clients directory to the customers directory.
+
+To copy a directory, including all its files and subdirectories, to another directory, enter:
+
+ $ cp -R /home/hhgg/clients /home/hhgg/customers
+
+This copies the clients directory, including all its files, subdirectories, and the files in those subdirectories, to the customers/clients directory.
+
+To copy a specific set of files of any extension to another directory, enter::
+
+ $ cp zaphod arthur ford /home/hhgg/clients
+
+This copies the *zaphod*, *arthur*, and *ford* files in your current working directory to the /home/hhgg/clients directory.
+
+To use pattern-matching characters to copy files, enter::
+
+ $ cp programs/*.py .
+
+This copies the files in the programs directory that end with *.py* to the current directory, signified by the single "." (dot). You must type a space between the *py* and the final dot.
+
+mv
+---
+
+*mv* (short for move) is a Unix command that moves one or more files or directories from one place to another. The original file is deleted, and the new file may have the same or a different name. If possible (i.e. when the original and new files are on the same file system), *mv* will rename the file instead. Write permission is required on all directories being modified.
+
+Conflicting existing file
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+In all cases, when a file is moved to have the name of an existing file (in the same directory), the existing file is deleted. If the existing file is not writable but is in a directory that is writable, then the mv command asks for confirmation if possible (i.e. if run from a terminal) before proceeding, unless the -f (force) option is used.
+
+Differences with copy and delete
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Note that, usually, when moving files within the same volume, moving (and/or renaming) is not the same as simply copying and then deleting the original. When moving a file, the link is simply removed from the old parent directory and added to the new parent directory. However, the file itself is untouched (i.e. it has the same inodes and resides at the same place on the disk). For example, you cannot copy a file you cannot read, but you can move (and/or rename) it (provided you have write permission to its old and new parent directories). Also, suppose there is a non-empty directory you do not have write permission to. You cannot delete this directory (since you cannot delete its contents); but you can move (and/or rename) it. Also, since moving between filenames on a single volume does not involve copying, it is faster and does not place strain of lots of reads and writes on the disk. Moving files across different volumes, however, does necessitate copying and deleting.
+
+Examples
+~~~~~~~~
+::
+
+ $ mv myfile mynewfilename renames a file
+ $ mv myfile otherfilename renames a file and deletes the existing file "myfile"
+ $ mv myfile /myfile moves 'myfile' from the current directory to the root directory
+ $ mv myfile dir/myfile moves 'myfile' to 'dir/myfile' relative to the current directory
+ $ mv myfile dir same as the previous command (the filename is implied to be the same)
+ $ mv myfile dir/myfile2 moves 'myfile' to dir and renames it to 'myfile2'
+ $ mv foo bar baz dir moves multiple files to directory dir
+ $ mv --help shows a very concise help about the syntax of the command
+ $ man mv prints an extensive user manual for 'mv' in the terminal
+
+In all cases, the file or files being moved or renamed can be a directory.
+
+Note that when the command is called with two arguments (as *mv name1 name2* or *mv name1 /dir/name2*), it can have three different effects, depending on whether *name2* does not exist, is an existing file, or is an existing directory. If the user intends to refer to an existing directory, */.* (or in some Unix versions */* is sufficient) may be appended to the name to force the system to check this. To move a file to a new directory, the directory must be created first.
+
+rm
+---
+
+*rm* (short for "remove") is one of several basic Unix command lines that operates on files. It is used to delete files from a filesystem. The data is not actually destroyed. Only the index listing where the file is stored is destroyed, and the storage is made available for reuse. There are undelete utilities that will attempt to reconstruct the index and can bring the file back if the parts were not reused.
+
+Here's example to remove a file named "foo" from a directory, here shown with the -i option::
+
+ $ rm -i foo
+ remove foo? y
+
+Options
+~~~~~~~
+
+Common options that rm accepts include:
+
+ * *-r*, which removes directories, removing the contents recursively beforehand (so as not to leave files without a directory to reside in) ("recursive")
+ * *-i*, which asks for every deletion to be confirmed ("interactive")
+ * *-f*, which ignores non-existent files and overrides any confirmation prompts ("force")
+ * *-v*, which shows what is being removed as it happens ("verbose")
+
+*rm* is often aliased to "rm -i" so as to avoid accidental deletion of files. If a user still wishes to delete a large number of files without confirmation, they can manually cancel out the -i argument by adding the -f option (as the option specified later on the expanded command line "rm -i -f" takes precedence).
+
+*rm -rf* (variously, rm -rf /, rm -rf `*`, and others) is frequently used in jokes and anecdotes about Unix disasters. The rm -rf variant of the command, if run by a superuser on the root directory, would cause the contents of every writable mounted filesystem on the computer to be deleted.
+
+*rm* is often used in conjunction with xargs to supply a list of files to delete::
+
+ xargs rm < filelist
+
+When *rm* is used on a symbolic link, it deletes the link, but does not affect the target of the link.
+
+Permissions
+~~~~~~~~~~~
+
+Usually, on most filesystems, deleting a file requires write permission on the parent directory (and execute permission, in order to enter the directory in the first place). (Note that, confusingly for beginners, permissions on the file itself are irrelevant. However, GNU rm asks for confirmation if a write-protected file is to be deleted, unless the -f option is used.)
+
+To delete a directory (with rm -r), one must delete all of its contents recursively. This requires that one must have read and write and execute permission to that directory (if it's not empty) and all non-empty subdirectories recursively (if there are any). The read permissions are needed to list the contents of the directory in order to delete them. This sometimes leads to an odd situation where a non-empty directory cannot be deleted because one doesn't have write permission to it and so cannot delete its contents; but if the same directory were empty, one would be able to delete it.
+
+If a file resides in a directory with the sticky bit set, then deleting the file requires one to be the owner of the file.
+
+
+Command Line Arguments
+=======================
+
+In computer command line interfaces, a command line argument is an argument sent to a program being called. In general, a program can take any number of command line arguments, which may be necessary for the program to run, or may even be ignored, depending on the function of that program.
+
+For example, in Unix and Unix-like environments, an example of a command-line argument is::
+
+ rm file.s
+
+"file.s" is a command line argument which tells the program rm to remove the file "file.s".
+
+Programming languages such as C, C++ and Java allow a program to interpret the command line arguments by handling them as string parameters in the main function.
+
+A command line option or simply *option* (also known as a command line parameter, flag, or a switch) is an indication by a user that a computer program should change its default output.
+
+Long options are introduced via "--", and are typically whole words. For example, *ls --long --classify --all*. Arguments to long options are provided with "=", as *ls --block-size=1024*. Some Unix programs use long options with single dashes, for example MPlayer as in *mplayer -nosound*.
+
+Linux also uses "--" to terminate option lists. For example, an attempt to delete a file called *-file1* by using *rm -file1* may produce an error, since rm may interpret *-file1* as a command line switch. Using *rm -- -file1* removes ambiguity.
+
+Basic Text Processing
+======================
+
+head
+-----
+
+*head* is a program on Unix and Unix-like systems used to display the first few lines of a text file or piped data. The command syntax is::
+
+ $ head [options] <file_name>
+
+By default, *head* will print the first 10 lines of its input to the standard output. The number of lines printed may be changed with a command line option. The following example shows the first 20 lines of filename::
+
+ $ head -n 20 filename
+
+This displays the first 5 lines of all files starting with *foo*::
+
+ $ head -n 5 foo*
+
+Some versions omit the n and just let you say -5.
+
+Flags
+~~~~~
+::
+
+ -c <x number of bytes> Copy first x number of bytes.
+
+Other options: *sed*
+
+Many early versions of Unix did not have this command, and so documentation and books had *sed* do this job::
+
+ sed 5q foo
+
+This says to print every line (implicit), and quit after the fifth.
+
+
+tail
+----
+
+*tail* is a program on Unix and Unix-like systems used to display the last few lines of a text file or piped data.
+
+The command-syntax is::
+
+ $ tail [options] <file_name>
+
+By default, *tail* will print the last 10 lines of its input to the standard output. With command line options the number of lines printed and the printing units (lines, blocks or bytes) may be changed. The following example shows the last 20 lines of filename::
+
+ $ tail -n 20 filename
+
+This example shows the last 15 bytes of all files starting with *foo*::
+
+ $ tail -c 15 foo*
+
+This example shows all lines of filename from the second line onwards::
+
+ $ tail -n +2 filename
+
+Using an older syntax (still used in Sun Solaris as the -n option is not supported), the last 20 lines and the last 50 bytes of filename can be shown with the following command::
+
+ $ tail -20 filename
+ $ tail -50c filename
+
+However this syntax is now obsolete and does not conform with the POSIX 1003.1-2001 standard. Even if still supported in current versions, when used with other options (like -f, see below), these switches could not work at all.
+
+File monitoring
+~~~~~~~~~~~~~~~
+
+*tail* has a special command line option *-f* (follow) that allows a file to be monitored. Instead of displaying the last few lines and exiting, tail displays the lines and then monitors the file. As new lines are added to the file by another process, tail updates the display. This is particularly useful for monitoring log files. The following command will display the last 10 lines of messages and append new lines to the display as new lines are added to messages::
+
+ $ tail -f /var/adm/messages
+
+To interrupt tail while it is monitoring, break-in with *Ctrl+C*. This command can be run "in the background" with &, see job control.
+
+If you have a command's result to monitor, you can use the *watch* command.
+
+
+cut
+----
+
+In computing, *cut* is a Unix command line utility which is used to extract sections from each line of input — usually from a file.
+
+Extraction of line segments can typically be done by *bytes (-b), characters (-c)*, or *fields (-f)* separated by a *delimiter (-d — the tab character by default)*. A range must be provided in each case which consists of one of N, N-M, N- (N to the end of the line), or -M (beginning of the line to M), where N and M are counted from 1 (there is no zeroth value). Since version 6, an error is thrown if you include a zeroth value. Prior to this the value was ignored and assumed to be 1.
+
+Assuming a file named file containing the lines::
+
+ foo:bar:baz:qux:quux
+ one:two:three:four:five:six:seven
+ alpha:beta:gamma:delta:epsilon:zeta:eta:teta:iota:kappa:lambda:mu
+
+To output the fourth through tenth characters of each line::
+
+ $ cut -c 4-10 file
+
+This gives the output::
+
+ :bar:ba
+ :two:th
+ ha:beta
+
+To output the fifth field through the end of the line of each line using the colon character as the field delimiter::
+
+ $ cut -d : -f 5- file
+
+This gives the output::
+
+ quux
+ five:six:seven
+ epsilon:zeta:eta:teta:iota:kappa:lambda:mu
+
+paste
+------
+
+*paste* is a Unix command line utility which is used to join files horizontally (parallel merging) by outputting lines consisting of the sequentially corresponding lines of each file specified, separated by tabs, to the standard output. It is effectively the horizontal equivalent to the utility *cat* command which operates on the vertical plane of two or more files.
+
+To paste several columns of data together into the file *www* from files *who*, *where*, and *when*::
+
+ $ paste who where when > www
+
+If the files contain:
+
++-----------+------------+------------+
+| who | where | when |
++===========+============+============+
+| Batman | GothamCity | January 3 |
++-----------+------------+------------+
+| Trillian | Andromeda | February 4 |
++-----------+------------+------------+
+| Jeeves | London | March 19 |
++-----------+------------+------------+
+
+This creates the file named *www* containing::
+
+ Batman GothamCity January 3
+ Trillian Andromeda February 4
+ Jeeves London March 19
+
+Shell Meta Characters
+======================
+
+Unix recognizes certain special characters, called "meta characters," as command directives. The shell meta characters are recognized anywhere they appear in the command line, even if they are not surrounded by blank space. For that reason, it is safest to only use the characters A-Z, a-z, 0-9, and the period, dash, and underscore characters when naming files and directories on Unix. If your file or directory has a shell meta character in the name, you will find it difficult to use the name in a shell command.
+
+The shell meta characters include:
+
+\ / < > ! $ % ^ & * | { } [ ] " ' ` ~ ;
+
+Different shells may differ in the meta characters recognized.
+
+As an example,
+::
+
+ $ ls file.*
+
+run on a directory containing the files file, file.c, file.lst, and myfile would list the files file.c and file.lst. However,::
+
+ $ ls file.?
+
+run on the same directory would only list file.c because the ? only matches one character, no more, no less. This can save you a great deal of typing time. For example, if there is a file called california_cornish_hens_with_wild_rice and no other files whose names begin with 'c', you could view the file without typing the whole name by typing this::
+
+ $ more c*
+
+because the c* matches that long file name.
+
+Filenames containing metacharacters can pose many problems and should never be intentionally created. If you do find that you've created a file with metacharacters, and you would like to remove it, you have three options. You may use wildcards to match metacharacter, use the \ to directly enter the filename, or put the command in double quotes (except in the case of double quotes within the file name, these must be captured with one of the first two methods). For example, deleting a file named `"``*`|more`"` can be accomplished with::
+
+ $ rm ??more
+
+or::
+
+ $ rm $\backslash$*$\backslash$|more
+
+or::
+
+ $ rm ''*|more''
+
+
+Looking At Files
+================
+
+cat
+---
+
+The *cat* command is a standard Unix program used to concatenate and display files. The name is from "catenate", a synonym of *concatenate*.
+
+The Single Unix Specification specifies the behavior that the contents of each of the files given in sequence as arguments will be written to the standard output in the same sequence, and mandates one option, -u, where each byte is printed as it is read.
+
+If the filename is specified as -, then *cat* will read from standard input at that point in the sequence. If no files are specified, *cat* will read from standard input entered.
+
+Jargon File Definition
+~~~~~~~~~~~~~~~~~~~~~~
+
+The Jargon File version 4.4.7 lists this as the definition of *cat*::
+
+ 1. To spew an entire file to the screen or some other output sink without
+ pause (syn. blast).
+
+ 2. By extension, to dump large amounts of data at an unprepared target or
+ with no intention of browsing it carefully. Usage: considered silly.
+ Rare outside Unix sites. See also dd, BLT.
+
+ Among Unix fans, *cat(1)* is considered an excellent example of
+ user-interface design, because it delivers the file contents without
+ such verbosity as spacing or headers between the files, and because
+ it does not require the files to consist of lines of text, but works
+ with any sort of data.
+
+ Among Unix critics, *cat(1)* is considered the canonical example of
+ bad user-interface design, because of its woefully unobvious name.
+ It is far more often used to blast a single file to standard output
+ than to concatenate two or more files. The name cat for the former
+ operation is just as unintuitive as, say, LISP's cdr.
+
+ Of such oppositions are holy wars made...
+
+Useless Use of 'cat'
+~~~~~~~~~~~~~~~~~~~~
+
+UUOC (from comp.unix.shell on Usenet) stands for “Useless Use of cat”. As it is observed on *comp.unix.shell*, “The purpose of cat is to concatenate (or 'catenate') files. If it's only one file, concatenating it with nothing at all is a waste of time, and costs you a process.”
+
+Nevertheless one sees people doing::
+
+ $ cat file | some_command and its args ...
+
+instead of the equivalent and cheaper::
+
+ <file some_command and its args ...
+
+or (equivalently and more classically)::
+
+ some_command and its args ... <file
+
+Since 1995, occasional awards for UUOC have been given out. The activity of fixing instances of UUOC is sometimes called 'demoggification'.
+
+Amongst many, it is still considered safer to use *cat* for such cases given that the < and > keys are next to each other in many popular keyboard mappings. While the risk might be low, the impact of using > instead of < can be high and prohibitive.
+
+zcat
+~~~~~
+
+*zcat* is a Unix program similar to *cat*, that decompresses individual files and concatenates them to standard output. Traditionally *zcat* operated on files compressed by compress but today it is usually able to operate on *gzip* or even *bzip2* archives. On such systems, it is equivalent to *gunzip -c*
+
+more
+-----
+
+In computing, *more* is a command to view (but not modify) the contents of a text file one screen at a time (terminal pager). It is available on Unix and Unix-like systems, DOS, OS/2 and Microsoft Windows. Programs of this sort are called pagers.
+
+Usage
+~~~~~
+
+The command-syntax is::
+
+ $ more [options] [file_name]
+
+If no file name is provided, *more* looks for input from stdin.
+
+Once *more* has obtained input, it displays as much as can fit on the current screen and waits for user input to advance, with the exception that a form feed (^L) will also cause *more* to wait at that line, regardless of the amount of text on the screen. In the lower-left corner of the screen is displayed the text "--More--" and a percentage, representing the percent of the file that *more* has paged through. (This percentage includes the text displayed on the current screen.) When *more* reaches the end of a file (100%) it exits. The most common methods of navigating through a file are *Enter*, which advances the output by one line, and *Space*, which advances the output by one screen.
+
+There are also other commands that can be used while navigating through the document; consult *more*'s *man* page for more details.
+
+*Options* are typically entered before the file name, but can also be entered in the environment variable *$MORE*. Options entered in the actual command line will override those entered in the *$MORE* environment variable. Available options may vary between Unix systems.
+
+less
+-----
+
+*less* is a terminal pager program on Unix, Windows and Unix-like systems used to view (but not change) the contents of a text file one screen at a time. It is similar to *more*, but has the extended capability of allowing both forward and backward navigation through the file. Unlike most Unix text editors/viewers, *less* does not need to read the entire file before starting, resulting in faster load times with large files.
+
+Usage
+~~~~~~
+
+*less* can be invoked with options to change its behaviour, for example, the number of lines to display on the screen. A few options vary depending on the operating system. While *less* is displaying the file, various commands can be used to navigate through the file. These commands are based on those used by both *more* and *vi*. It is also possible to search for character patterns in the file.
+
+By default, *less* displays the contents of the file to the standard output (one screen at a time). If the file name argument is omitted, it displays the contents from standard input (usually the output of another command through a pipe). If the output is redirected to anything other than a terminal, for example a pipe to another command, less behaves like cat.
+
+The command-syntax is::
+
+ $ less [options] file_name
+
+Frequently Used Options
+~~~~~~~~~~~~~~~~~~~~~~~
+
+ * -g: Highlights just the current match of any searched string.
+
+ * -I: Case-insensitive searches.
+
+ * -M: Shows more detailed prompt, including file position.
+
+ * -N: Shows line numbers (useful for source code viewing).
+
+ * -S: Disables line wrap ("chop long lines"). Long lines can be seen by side scrolling.
+
+ * -?: Shows help.
+
+Frequently Used Commands
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+ * [Arrows]/[Page Up]/[Page Down]/[Home]/[End]: Navigation.
+
+ * [Space bar]: Next page.
+
+ * b: Previous page.
+
+ * ng: Jump to line number n. Default is the start of the file.
+
+ * nG: Jump to line number n. Default is the end of the file.
+
+ * /pattern: Search for pattern. Regular expressions can be used.
+
+ * '^ or g: Go to start of file.
+
+ * '$ or G: Go to end of file.
+
+ * s: Save current content (got from another program like grep) in a file.
+
+ * =: File information.
+
+ * h: Help.
+
+ * q: Quit.
+
+Examples
+~~~~~~~~~
+::
+
+ $ less -M readme.txt #Read "readme.txt."
+ $ less +F /var/log/mail.log #Follow mode for log
+ $ file * | less #Easier file analysis.
+ $ grep -i void *.c | less -I -p void #Case insensitive search for "void" in all .c files
+
+Directory Structure
+====================
+
+In the File Hierarchy Standard (FHS) all files and directories appear under the root directory "/", even if they are stored on different physical devices. Note however that some of these directories may or may not be present on a Unix system depending on whether certain subsystems, such as the X Window System, are installed.
+
+The majority of these directories exist in all UNIX operating systems and are generally used in much the same way; however, the descriptions here are those used specifically for the FHS, and are not considered authoritative for platforms other than Linux.
+
++---------------+------------------------------------------------+
+| Directory | Description |
++===============+================================================+
+| / | Primary hierarchy root and root directory of |
+| | the entire file system hierarchy. |
++---------------+------------------------------------------------+
+| /bin/ | Essential command binaries that need to be |
+| | available in single user mode; for all users, |
+| | e.g., *cat*, *ls*, *cp*. |
++---------------+------------------------------------------------+
+| /boot/ | Boot loader files, e.g., *kernels*, *initrd*; |
+| | often a separate partition. |
++---------------+------------------------------------------------+
+| /dev/ | Essential devices, e.g., /dev/null |
++---------------+------------------------------------------------+
+| /etc/ | Host-specific system-wide configuration files |
+| | (the name comes from *et cetera*) |
++---------------+------------------------------------------------+
+| /home/ | User's home directories, containing saved |
+| | files, personal settings, etc.; often a |
+| | separate partition. |
++---------------+------------------------------------------------+
+| /lib/ | Libraries essential for the binaries in |
+| | */bin/* and */sbin/* |
++---------------+------------------------------------------------+
+| /media/ | Mount points for removable media such as |
+| | CD-ROMs, external hard disks, USB sticks, etc. |
++---------------+------------------------------------------------+
+| /mnt/ | Temporarily mounted file systems |
++---------------+------------------------------------------------+
+| /opt/ | Optional application software packages |
++---------------+------------------------------------------------+
+| /proc/ | Virtual filesystem documenting kernel and |
+| | process status as text files; e.g., uptime, |
+| | network. In Linux, corresponds to a *Procfs* |
+| | mount. |
++---------------+------------------------------------------------+
+| /root/ | Home directory for the root user |
++---------------+------------------------------------------------+
+| /sbin/ | Essential system binaries; e.g., *init*, |
+| | *route*, *mount*. |
++---------------+------------------------------------------------+
+| /srv/ | Site-specific data which is served by the |
+| | system. |
++---------------+------------------------------------------------+
+| /tmp/ | Temporary files. Often not preserved between |
+| | system reboots. |
++---------------+------------------------------------------------+
+| /usr/ | Secondary hierarchy for read-only user data; |
+| | contains the majority of (multi-)user |
+| | utilities and applications. |
++---------------+------------------------------------------------+
+| /var/ | Variable files - files whose content is |
+| | expected to continually change during normal |
+| | operation of the system - such as logs, spool |
+| | files, and temporary e-mail files. |
+| | Sometimes a separate partition. |
++---------------+------------------------------------------------+
+
+
+man hier
+---------
+
+This is the manual page on the UNIX filesystem. The syntax for this is::
+
+ $ man hier
+
+ls -l
+-----
+
+Shows you huge amounts of information (permissions, owners, size, and when last modified) for folders and files. The syntax is ::
+
+ $ ls -l
+
+This can be done after entering the required directory.
+
+Permissions and Ownership
+=========================
+
+chmod
+------
+
+The *chmod* command (abbreviated from 'change mode') is a shell command and C language function in Unix and Unix-like environments. When executed, it can change file system modes of files and directories. The modes include permissions and special modes.A chmod command first appeared in AT&T Unix version 1, and is still used today on Unix-like machines.
+
+Usage
+~~~~~
+
+The *chmod* command options are specified like this:
+::
+
+ $ chmod [options] mode[,mode] file1 [file2 ...]
+
+To view what the permissions currently are, type:
+::
+
+ $ ls -l file
+
+Command line options
+~~~~~~~~~~~~~~~~~~~~
+
+The *chmod* command has a number of command line options that affect its behavior. The most common options are:
+
+ * -R: Changes the modes of directories and files recursively
+
+ * -v: Verbose mode; lists all files as they are being processed
+
+Symbolic modes
++++++++++++++++
+
+To the *chmod* utility, all permissions and special modes are represented by its mode parameter. One way to adjust the mode of files or directories is to specify a symbolic mode. The symbolic mode is composed of three components, which are combined to form a single string of text:
+::
+
+ $ chmod [references][operator][modes] file1 ...
+
+The references (or classes) are used to distinguish the users to whom the permissions apply. If no references are specified it defaults to “all” but modifies only the permissions allowed by the umask. The references are represented by one or more of the following letters:
+
++--------------+--------+---------------------------------------------+
+| Reference | Class | Description |
++==============+========+=============================================+
+| u | user | the owner of the file |
++--------------+--------+---------------------------------------------+
+| g | group | users who are members of the file's group |
++--------------+--------+---------------------------------------------+
+| o | others | users who are not hte owner of the file or |
+| | | members of the group |
++--------------+--------+---------------------------------------------+
+| a | all | all three of the above; is the same as *ugo*|
++--------------+--------+---------------------------------------------+
+
+The *chmod* program uses an operator to specify how the modes of a file should be adjusted. The following operators are accepted:
+
++--------------+------------------------------------------------------+
+| Operator | Description |
++==============+======================================================+
+| + | adds the specified modes to the specified classes |
++--------------+------------------------------------------------------+
+| - | removes the specified modes from the specified |
+| | classes |
++--------------+------------------------------------------------------+
+| = | the modes specified are to be made the exact modes |
+| | for the specified classes |
++--------------+------------------------------------------------------+
+
+The modes indicate which permissions are to be granted or taken away from the specified classes. There are three basic modes which correspond to the basic permissions:
+
++-----+--------------+------------------------------------------------+
+|Mode | Name | Description |
++=====+==============+================================================+
+| r | read | read a file or list a directory's contents |
++-----+--------------+------------------------------------------------+
+| w | write | write to a file or directory |
++-----+--------------+------------------------------------------------+
+| x | execute | execute a file or recurse a directory tree |
++-----+--------------+------------------------------------------------+
+| X | special | which is not a permission in itself but rather |
+| | execute | can be used instead of 'x'. It applies execute |
+| | | permissions to directories regardless of their |
+| | | current permissions and applies execute |
+| | | permissions to a file which already has at |
+| | | least 1 execute permission bit already set |
+| | | (either user, group or other). It is only |
+| | | really useful when used with '+' and usually |
+| | | in combination with the *-R* option for giving |
+| | | group or other access to a big directory tree |
+| | | without setting execute permission on normal |
+| | | files (such as text files), which would |
+| | | normally happen if one just used 'chmod -R |
+| | | a+rx .', whereas with 'X' one can do 'chmod -R |
+| | | a+rX .' instead. |
++-----+--------------+------------------------------------------------+
+| s | setuid/gid | are Unix access rights flags that allow users |
+| | | to run an executable with the permissions of |
+| | | the executable's owner or group.They are often |
+| | | used to allow users on a computer system to run|
+| | | programs with temporarily elevated privileges |
+| | | in order to perform a specific task. While the |
+| | | assumed user id or group id privileges provided|
+| | | are not always elevated, at a minimum they are |
+| | | specific.They are needed for tasks that require|
+| | | higher privileges than those which a common |
+| | | user has, such as changing his or her login |
+| | | password. |
++-----+--------------+------------------------------------------------+
+| t | sticky | The most common use of the sticky bit today is |
+| | | on directories, where, when set, items inside |
+| | | the directory can be renamed or deleted only by|
+| | | the item's owner, the directory's owner, or the|
+| | | superuser; without the sticky bit set, any user|
+| | | with write and execute permissions for the |
+| | | directory can rename or delete contained files,|
+| | | regardless of owner. |
++-----+--------------+------------------------------------------------+
+
+The combination of these three components produces a string that is understood by the chmod command. Multiple changes can be specified by separating multiple symbolic modes with commas.
+
+Symbolic examples
++++++++++++++++++
+
+Add the 'read' and 'write' permissions to the 'user' and 'group' classes of a directory:
+::
+
+ $ chmod ug+rw mydir
+ $ ls -ld mydir
+ drw-rw---- 2 starwars yoda 96 Dec 8 12:53 mydir
+
+For a file, remove *write* permissions for all classes:
+::
+
+ $ chmod a-w myfile
+ $ ls -l myfile
+ -r-xr-xr-x 2 starwars yoda 96 Dec 8 12:53 myfile
+
+Set the permissions for the *u*ser and the *g*roup to read and execute only (no write permission) on *mydir*.
+::
+
+ $ chmod ug=rx mydir
+ $ ls -ld mydir
+ dr-xr-x--- 2 starwars yoda 96 Dec 8 12:53 mydir
+
+Octal numbers
++++++++++++++
+
+The *chmod* command also accepts three and four-digit octal numbers representing modes. Using a three-digit octal number to set the modes of a file named myfile :
+::
+
+ $ chmod 664 myfile
+ $ ls -l myfile
+ -rw-rw-r-- 1 57 Jul 3 10:13 myfile
+
+Since the *setuid*, *setgid* and *sticky* bits are not set, this is equivalent to:
+::
+
+ $ chmod 0664 myfile
+
+Special modes
++++++++++++++
+
+The *chmod* command is also capable of changing the additional permissions or special modes of a file or directory. The symbolic modes use **s** to represent the *setuid* and *setgid* modes, and **t** to represent the sticky mode. The modes are only applied to the appropriate classes, regardless of whether or not other classes are specified.
+
+Most operating systems support the specification of special modes using octal modes, but some do not. On these systems, only the symbolic modes can be used.
+
+Redirection and Piping
+=======================
+
+In computing, *redirection* is a function common to most command-line interpreters, including the various Unix shells that can redirect standard streams to user-specified locations.
+
+Programs do redirection with the *dup2(2)* system call, or its less-flexible but higher-level stdio analogues, *freopen(3)* and *popen(3)*.
+
+Redirecting standard input and standard output
+-----------------------------------------------
+
+Redirection is usually implemented by placing certain characters between commands. Typically, the syntax of these characters is as follows::
+
+ $ command1 > file1
+
+executes *command1*, placing the output in file1. Note that this will truncate any existing data in *file1*. To append output to the end of the file, use the >> operator.::
+
+ $ command1 < file1
+
+executes *command1*, using *file1* as the source of input (as opposed to the keyboard).::
+
+ $ command1 < infile > outfile
+
+combines the two capabilities: *command1* reads from *infile* and writes to *outfile*
+
+Piping
+-------
+
+Programs can be run together such that one program reads the output from another with no need for an explicit intermediate file:
+A pipeline of three programs run on a text terminal::
+
+ $ command1 | command2
+
+executes *command1*, using its output as the input for *command2* (commonly called piping, since the "|" character is known as a "pipe").
+
+This is equivalent to using two redirects and a temporary file::
+
+ $ command1 > tempfile
+ $ command2 < tempfile
+ $ rm tempfile
+
+A good example for command piping is combining *echo* with another command to achieve something interactive in a non-interactive shell, e.g.::
+
+ $ echo -e "user\npass" | ftp localhost
+
+This runs the ftp client with input user, press return, then pass.
+
+Redirecting to and from the standard file handles
+--------------------------------------------------
+
+In Unix shells derived from the original Bourne shell, the first two actions can be further modified by placing a number (the file descriptor) immediately before the character; this will affect which stream is used for the redirection. The Unix standard I/O streams are:
+
++------------+-------------+------------------------+
+| Handle | Name | Description |
++============+=============+========================+
+| 0 | stdin | Standard input |
++------------+-------------+------------------------+
+| 1 | stdout | Standard output |
++------------+-------------+------------------------+
+| 2 | stderr | Standard error |
++------------+-------------+------------------------+
+
+For example:
+::
+
+ $ command1 2> file1
+
+executes *command1*, directing the standard error stream to *file1*.
+
+In shells derived from *csh* (the C shell), the syntax instead appends the & character to the redirect characters, thus achieving a similar result.
+
+Another useful capability is to redirect one standard file handle to another. The most popular variation is to merge standard error into standard output so error messages can be processed together with (or alternately to) the usual output. Example:
+::
+
+ $ find / -name .profile > results 2>&1
+
+will try to find all files named *.profile*. Executed without redirection, it will output hits to *stdout* and errors (e.g. for lack of privilege to traverse protected directories) to *stderr*. If standard output is directed to file results, error messages appear on the console. To see both hits and error messages in file results, merge *stderr* (handle 2) into *stdout* (handle 1) using 2>&1 .
+
+It's possible use 2>&1 before ">" but it doesn't work. In fact, when the interpreter reads 2>&1, it doesn't know yet where standard output is redirected and then standard error isn't merged.
+
+If the merged output is to be piped into another program, the file merge sequence 2>&1 must precede the pipe symbol, thus:
+::
+
+ $ find / -name .profile 2>&1 | less
+
+A simplified form of the command:
+::
+
+ $ command > file 2>&1
+
+is:
+::
+
+ $ command &>file
+
+or:
+::
+
+ $command >&file
+
+Chained pipelines
+------------------
+
+The redirection and piping tokens can be chained together to create complex commands. For example:
+::
+
+ $ ls | grep '\.sh' | sort > shlist
+
+lists the contents of the current directory, where this output is filtered to only contain lines which contain *.sh*, sort this resultant output lexicographically, and place the final output in *shlist*. This type of construction is used very commonly in shell scripts and batch files.
+
+Redirect to multiple outputs
+-----------------------------
+
+The standard command *tee* can redirect output from a command to several destinations.
+::
+
+ $ ls -lrt | tee xyz
+
+This directs the file list output to both standard output as well as to the file *xyz*.
+
+More Text Processing
+====================
+
+grep
+-----
+
+*grep* is a command line text search utility originally written for Unix. The name is taken from the first letters in *global / regular expression / print*, a series of instructions for the *ed* text editor. The *grep* command searches files or standard input globally for lines matching a given regular expression, and prints them to the program's standard output.
+
+Usage
+~~~~~~
+
+This is an example of a common *grep* usage:
+::
+
+ $ grep apple fruitlist.txt
+
+In this case, *grep* prints all lines containing 'apple' from the file *fruitlist.txt*, regardless of word boundaries; therefore lines containing 'pineapple' or 'apples' are also printed. The *grep* command is case sensitive by default, so this example's output does not include lines containing 'Apple' (with a capital A) unless they also contain 'apple'.
+
+Like most Unix commands, *grep* accepts command line arguments to change this and many other behaviors. For example:
+::
+
+ $ grep -i apple fruitlist.txt
+
+This prints all lines containing 'apple' regardless of capitalization. The '-i' argument tells *grep* to be case insensitive, or to ignore case.
+
+To print all lines containing 'apple' as a word ('pineapple' and 'apples' will not match):
+::
+
+ $ grep -w apple fruitlist.txt
+
+Regular expressions can be used to match more complicated queries.
+
+Variations
++++++++++++
+
+There are countless implementations and derivatives of *grep* available for many operating systems. Early variants of *grep* included *egrep* and *fgrep*. The former applies an extended regular expression syntax that was added to Unix after Ken Thompson's original regular expression implementation. The latter searches for any of a list of 'fixed' strings using the Aho-Corasick algorithm. These variants are embodied in most modern *grep* implementations as command-line switches (and standardized as -E and -F in POSIX). In such combined implementations, *grep* may also behave differently depending on the name by which it is invoked, allowing *fgrep*, *egrep*, and *grep* to be links to the same program.
+
+*pcregrep* is an implementation of *grep* that uses Perl regular expression syntax.
+
+Other commands contain the word 'grep' to indicate that they search (usually for regular expression matches). The *pgrep* utility, for instance, displays the processes whose names match a given regular expression.
+
+tr
+--
+
+*tr* (abbreviated from *translate* or *transliterate*) is a command in Unix-like operating systems.
+
+When executed, the program reads from the standard input and writes to the standard output. It takes as parameters two sets of characters, and replaces occurrences of the characters in the first set with the corresponding elements from the other set. For example,
+::
+
+ $ tr 'abcd' 'jkmn'
+
+maps 'a' to 'j', 'b' to 'k', 'c' to 'm', and 'd' to 'n'.
+
+Sets of characters may be abbreviated by using character ranges. The previous example could be written:
+::
+
+ $ tr 'a-d' 'jkmn'
+
+In POSIX compliant versions of *tr* the set represented by a character range depends on the locale's collating order, so it is safer to avoid character ranges in scripts that might be executed in a locale different from that in which they were written. Ranges can often be replaced with POSIX character sets such as [:alpha:].
+
+The *-c* flag complements the first set of characters.
+::
+
+ $ tr -cd '[:alnum:]'
+
+therefore removes all non-alphanumeric characters.
+
+The *-s* flag causes tr to compress sequences of identical adjacent characters in its output to a single token. For example,
+::
+
+ $ tr -s '\n' '\n'
+
+replaces sequences of one or more newline characters with a single newline.
+
+The *-d* flag causes tr to delete all tokens of the specified set of characters from its input. In this case, only a single character set argument is used. The following command removes carriage return characters, thereby converting a file in DOS/Windows format to one in Unix format.
+::
+
+ $ tr -d '\r'
+
+Most versions of *tr*, including GNU *tr* and classic Unix *tr*, operate on single byte characters and are not Unicode compliant. An exception is the Heirloom Toolchest implementation, which provides basic Unicode support.
+
+Ruby and Perl also have an internal *tr* operator, which operates analogously. Tcl's *string map* command is more general in that it maps strings to strings while *tr* maps characters to characters.
+
+Elementary Regex
+=================
+
+In computing, regular expressions provide a concise and flexible means for identifying strings of text of interest, such as particular characters, words, or patterns of characters. A regular expression (often shortened to regex or regexp) is written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.
+
+Regular expressions are used by many text editors, utilities, and programming languages to search and manipulate text based on patterns. For example, Perl, Ruby and Tcl have a powerful regular expression engine built directly into their syntax. Several utilities provided by Unix distributions—including the editor *ed* and the filter *grep* — were the first to popularize the concept of regular expressions.
+
+Traditional Unix regular expression syntax followed common conventions but often differed from tool to tool. The IEEE POSIX *Basic Regular Expressions* (BRE) standard (released alongside an alternative flavor called Extended Regular Expressions or ERE) was designed mostly for backward compatibility with the traditional (Simple Regular Expression) syntax but provided a common standard which has since been adopted as the default syntax of many Unix regular expression tools, though there is often some variation or additional features. Many such tools also provide support for ERE syntax with command line arguments.
+
+In the BRE syntax, most characters are treated as literals — they match only themselves (i.e., a matches "a"). The exceptions, listed below, are called metacharacters or metasequences.
+
++-------------+------------------------------------------------------------+
+|Metacharacter| Description |
++=============+============================================================+
+| . | Matches any single character (many applications exclude |
+| | newlines, and exactly which characters are considered |
+| | newlines is flavor, character encoding, and platform |
+| | specific, but it is safe to assume that the line feed |
+| | character is included). Within POSIX bracket expressions, |
+| | the dot character matches a literal dot. For example, a.c |
+| | matches abc, etc., but [a.c] matches only a, ., or |
+| | c. |
++-------------+------------------------------------------------------------+
+| [ ] | A bracket expression. Matches a single character that is |
+| | contained within the brackets. For example, [abc] matches |
+| | a, b, or c. [a-z] specifies a range which matches any |
+| | lowercase letter from a to z. These forms can be mixed: |
+| | [abcx-z] matches a, b, c, x, y, or z, as does |
+| | [a-cx-z]. The - character is treated as a literal character|
+| | if it is the last or the first character within the |
+| | brackets, or if it is escaped with a backslash: [abc-], |
+| | [-abc], or [a\-bc]. |
++-------------+------------------------------------------------------------+
+| [^ ] | Matches a single character that is not contained within the|
+| | brackets. For example, [^abc] matches any character other |
+| | than a, b, or c. [^a-z] matches any single character |
+| | that is not a lowercase letter from a to z. As above, |
+| | literal characters and ranges can be mixed. |
++-------------+------------------------------------------------------------+
+| ^ | Matches the starting position within the string. In |
+| | line-based tools, it matches the starting position of any |
+| | line. |
++-------------+------------------------------------------------------------+
+| $ | Matches the ending position of the string or the position |
+| | just before a string-ending newline. In line-based tools, |
+| | it matches the ending position of any line. |
++-------------+------------------------------------------------------------+
+| `*` | Matches the preceding element zero or more times. For |
+| | example, ab*c matches "ac", "abc", "abbbc", etc. [xyz]* |
+| | matches "", "x", "y", "z", "zx", "zyx", "xyzzy", and so on.|
+| | \(ab\)* matches "", "ab", "abab", "ababab", and so on. |
++-------------+------------------------------------------------------------+
+| ? | Matches the preceding element zero or one time. For |
+| | example, ba? matches "b" or "ba". |
++-------------+------------------------------------------------------------+
+| `+` | Matches the preceding element one or more times. For |
+| | example, ba+ matches "ba", "baa", "baaa", and so on. |
++-------------+------------------------------------------------------------+
+| `|` | The choice (aka alternation or set union) operator matches |
+| | either the expression before or the expression after the |
+| | operator. For example, abc|def matches "abc" or "def". |
++-------------+------------------------------------------------------------+
+
+Lazy quantification
+--------------------
+
+The standard quantifiers in regular expressions are greedy, meaning they match as much as they can, only giving back as necessary to match the remainder of the regex. For example, someone new to regexes wishing to find the first instance of an item between < and > symbols in this example:
+::
+
+ Another whale explosion occurred on <January 26>, <2004>.
+
+...would likely come up with the pattern <.*>, or similar. However, this pattern will actually return "<January 26>, <2004>" instead of the "<January 26>" which might be expected, because the `*` quantifier is greedy — it will consume as many characters as possible from the input, and "January 26>, <2004" has more characters than "January 26".
+
+Though this problem can be avoided in a number of ways (e.g., by specifying the text that is not to be matched: <[^>]*>), modern regular expression tools allow a quantifier to be specified as *lazy* (also known as non-greedy, reluctant, minimal, or ungreedy) by putting a question mark after the quantifier (e.g., <.*?>), or by using a modifier which reverses the greediness of quantifiers (though changing the meaning of the standard quantifiers can be confusing). By using a lazy quantifier, the expression tries the minimal match first. Though in the previous example lazy matching is used to select one of many matching results, in some cases it can also be used to improve performance when greedy matching would require more backtracking.
+
+One Liners
+===========
+
+A *one-liner* is textual input to the command-line of an operating system shell that performs some function in just one line of input.
+
+The one liner can be
+
+ 1. An expression written in the language of the shell.
+ 2. The invocation of an interpreter together with program source for the interpreter to run.
+ 3. The invocation of a compiler together with source to compile and
+ instructions for executing the compiled program.
+
+Certain dynamic scripting languages such as AWK, sed, and perl have traditionally been adept at expressing one-liners. Specialist shell interpreters such as these Unix shells or the Windows PowerShell, allow for the construction of powerful one-liners.
+
+The use of the phrase one-liner has been widened to also include program-source for any language that does something useful in one line.
+
+The word *One-liner* has two references in the index of the book *The AWK Programming Language* (the book is often referred to by the abbreviation TAPL). It explains the programming language AWK, which is part of the Unix operating system. The authors explain the birth of the One-liner paradigm with their daily work on early Unix machines:
+::
+
+ “The 1977 version had only a few built-in variables and predefined functions. It was designed for writing short programs [...] Our model was that an invocation would be one or two lines long, typed in and used immediately. Defaults were chosen to match this style [...] We, being the authors, knew how the language was supposed to be used, and so we only wrote one-liners.”
+
+Notice that this original definition of a One-liner implies immediate execution of the program without any compilation. So, in a strict sense, only source code for interpreted languages qualifies as a One-liner. But this strict understanding of a One-liner was broadened in 1985 when the IOCCC introduced the category of Best One Liner for C, which is a compiled language.
+
+The TAPL book contains 20 examples of One-liners (A Handful of Useful awk One-Liners) at the end of the book's first chapter.
+
+Here are the first few of them:
+
+ 1. Print the total number of input lines:
+
+ END { print NR }
+
+ 2. Print the tenth input line:
+
+ NR == 10
+
+ 3. Print the last field of every input line:
+
+ { print $NF }
+
+One-liners are also used to show off the differential expressive power of programming languages. Frequently, one-liners are used to demonstrate programming ability. Contests are often held to see who can create the most exceptional one-liner.
+
+The following example is a C program (a winning entry in the "Best one-liner" category of the IOCCC, here split to two lines for presentation).::
+
+ main(int c,char**v){return!m(v[1],v[2]);}m(char*s,char*t){return
+ *t-42?*s?63==*t|*s==*t&&m(s+1,t+1):!*t:m(s,t+1)||*s&&m(s+1,t);}
+
+This one-liner program is a *glob pattern matcher*. It understands the glob characters '*' meaning 'zero or more characters' and '?' meaning exactly one character, just like most Unix shells.
+
+Run it with two args, the string and the glob pattern. The exit status is 0 (shell true) when the pattern matches, 1 otherwise. The glob pattern must match the whole string, so you may want to use * at the beginning and end of the pattern if you are looking for something in the middle. Examples::
+
+ $ prog foo 'f??'; echo $?
+
+ $ prog 'best short program' '??st*o**p?*'; echo $?
+
+Here is a one line shell script to show directories:
+
+::
+
+ $ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
+
+
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/examples/alice-in-wonderland.txt Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,4047 @@
+Project Gutenberg's Alice's Adventures in Wonderland, by Lewis Carroll
+
+This eBook is for the use of anyone anywhere at no cost and with
+almost no restrictions whatsoever. You may copy it, give it away or
+re-use it under the terms of the Project Gutenberg License included
+with this eBook or online at www.gutenberg.net
+
+
+Title: Alice's Adventures in Wonderland
+ Illustrated by Arthur Rackham. With a Proem by Austin Dobson
+
+Author: Lewis Carroll
+
+Illustrator: Arthur Rackham
+
+Release Date: May 19, 2009 [EBook #28885]
+
+Language: English
+
+Character set encoding: ISO-8859-1
+
+*** START OF THIS PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***
+
+
+
+
+Produced by Jana Srna, Emmy and the Online Distributed
+Proofreading Team at http://www.pgdp.net (This file was
+produced from images generously made available by the
+University of Florida Digital Collections.)
+
+
+
+
+
+
+
+
+
+
+
+ALICE'S ADVENTURES IN WONDERLAND
+
+[Illustration: "Alice"]
+
+[Illustration:
+
+ ALICE'SADVENTURES
+ INWONDERLAND
+ BYLEWISCARROLL
+ ILLUSTRATEDBY
+ ARTHURRACKHAM
+
+ WITH A PROEM BY AUSTIN DOBSON
+
+ LONDONWILLIAMHEINEMANN
+ NEWYORKDOUBLEDAYPAGE&Co]
+
+ PRINTED IN ENGLAND
+
+ _'Tis two score years since CARROLL'S art,
+ With topsy-turvy magic,
+ Sent ALICE wondering through a part
+ Half-comic and half-tragic._
+
+ _Enchanting ALICE! Black-and-white
+ Has made your deeds perennial;
+ And naught save "Chaos and old Night"
+ Can part you now from TENNIEL;_
+
+ _But still you are a Type, and based
+ In Truth, like LEAR and HAMLET;
+ And Types may be re-draped to taste
+ In cloth-of-gold or camlet._
+
+ _Here comes afresh Costumier, then;
+ That Taste may gain a wrinkle
+ From him who drew with such deft pen
+ The rags of RIP VAN WINKLE!_
+
+ _AUSTIN DOBSON._
+
+
+
+ All in the golden afternoon
+ Full leisurely we glide;
+ For both our oars, with little skill,
+ By little arms are plied,
+ While little hands make vain pretence
+ Our wanderings to guide.
+
+ Ah, cruel Three! In such an hour,
+ Beneath such dreamy weather,
+ To beg a tale of breath too weak
+ To stir the tiniest feather!
+ Yet what can one poor voice avail
+ Against three tongues together?
+
+ Imperious Prima flashes forth
+ Her edict "to begin it"--
+ In gentler tone Secunda hopes
+ "There will be nonsense in it!"--
+ While Tertia interrupts the tale
+ Not _more_ than once a minute.
+
+ Anon, to sudden silence won,
+ In fancy they pursue
+ The dream-child moving through a land
+ Of wonders wild and new,
+ In friendly chat with bird or beast--
+ And half believe it true.
+
+ And ever, as the story drained
+ The wells of fancy dry.
+ And faintly strove that weary one
+ To put the subject by,
+ "The rest next time--" "It _is_ next time!"
+ The happy voices cry.
+
+ Thus grew the tale of Wonderland:
+ Thus slowly, one by one,
+ Its quaint events were hammered out--
+ And now the tale is done,
+ And home we steer, a merry crew,
+ Beneath the setting sun.
+
+ Alice! a childish story take,
+ And with a gentle hand
+ Lay it where Childhood's dreams are twined
+ In Memory's mystic band,
+ Like pilgrim's wither'd wreath of flowers
+ Pluck'd in a far-off land.
+
+
+
+
+CONTENTS
+
+
+ PAGE
+
+ I. DOWN THE RABBIT-HOLE 1
+
+ II. THE POOL OF TEARS 13
+
+ III. A CAUCUS-RACE AND A LONG TALE 24
+
+ IV. THE RABBIT SENDS IN A LITTLE BILL 35
+
+ V. ADVICE FROM A CATERPILLAR 49
+
+ VI. PIG AND PEPPER 64
+
+ VII. A MAD TEA-PARTY 82
+
+ VIII. THE QUEEN'S CROQUET-GROUND 96
+
+ IX. THE MOCK TURTLE'S STORY 111
+
+ X. THE LOBSTER QUADRILLE 126
+
+ XI. WHO STOLE THE TARTS? 139
+
+ XII. ALICE'S EVIDENCE 150
+
+
+
+
+LIST OF THE PLATES
+
+
+ _To face page_
+
+ Alice _Frontispiece_
+
+ The Pool of Tears 22
+
+ They all crowded round it panting and
+ asking, "But who has won?" 28
+
+ "Why, Mary Ann, what are you doing out
+ here?" 36
+
+ Advice from a Caterpillar 50
+
+ An unusually large saucepan flew close
+ by it, and very nearly carried it off 70
+
+ It grunted again so violently that she
+ looked down into its face in some alarm 74
+
+ A Mad Tea-Party 84
+
+ The Queen turned angrily away from him
+ and said to the Knave, "Turn them over" 100
+
+ The Queen never left off quarrelling
+ with the other players, and shouting
+ "Off with his head!" or, "Off with her
+ head!" 116
+
+ The Mock Turtle drew a long breath and
+ said, "That's very curious" 132
+
+ Who stole the Tarts? 140
+
+ At this the whole pack rose up into the
+ air, and came flying down upon her 158
+
+
+
+
+CHAPTER I
+
+
+[Sidenote: _Down the Rabbit-Hole_]
+
+ALICE was beginning to get very tired of sitting by her
+sister on the bank, and of having nothing to do: once or twice she had
+peeped into the book her sister was reading, but it had no pictures or
+conversations in it, "and what is the use of a book," thought Alice,
+"without pictures or conversations?"
+
+So she was considering in her own mind (as well as she could, for the
+hot day made her feel very sleepy and stupid) whether the pleasure of
+making a daisy-chain would be worth the trouble of getting up and
+picking the daisies, when suddenly a White Rabbit with pink eyes ran
+close by her.
+
+There was nothing so _very_ remarkable in that; nor did Alice think it
+so _very_ much out of the way to hear the Rabbit say to itself, "Oh
+dear! Oh dear! I shall be too late!" (when she thought it over
+afterwards, it occurred to her that she ought to have wondered at this,
+but at the time it all seemed quite natural); but when the Rabbit
+actually _took a watch out of its waistcoat-pocket_, and looked at it,
+and then hurried on, Alice started to her feet, for it flashed across
+her mind that she had never before seen a rabbit with either a
+waistcoat-pocket, or a watch to take out of it, and burning with
+curiosity, she ran across the field after it, and was just in time to
+see it pop down a large rabbit-hole under the hedge.
+
+In another moment down went Alice after it, never once considering how
+in the world she was to get out again.
+
+The rabbit-hole went straight on like a tunnel for some way, and then
+dipped suddenly down, so suddenly that Alice had not a moment to think
+about stopping herself before she found herself falling down what seemed
+to be a very deep well.
+
+[Illustration]
+
+Either the well was very deep, or she fell very slowly, for she had
+plenty of time as she went down to look about her, and to wonder what
+was going to happen next. First, she tried to look down and make out
+what she was coming to, but it was too dark to see anything; then she
+looked at the sides of the well and noticed that they were filled with
+cupboards and book-shelves: here and there she saw maps and pictures
+hung upon pegs. She took down a jar from one of the shelves as she
+passed; it was labelled "ORANGE MARMALADE," but to her disappointment it
+was empty; she did not like to drop the jar for fear of killing
+somebody underneath, so managed to put it into one of the cupboards as
+she fell past it.
+
+"Well!" thought Alice to herself. "After such a fall as this, I shall
+think nothing of tumbling down stairs! How brave they'll all think me at
+home! Why, I wouldn't say anything about it, even if I fell off the top
+of the house!" (Which was very likely true.)
+
+Down, down, down. Would the fall _never_ come to an end? "I wonder how
+many miles I've fallen by this time?" she said aloud. "I must be getting
+somewhere near the centre of the earth. Let me see: that would be four
+thousand miles down. I think--" (for, you see, Alice had learnt several
+things of this sort in her lessons in the schoolroom, and though this
+was not a _very_ good opportunity for showing off her knowledge, as
+there was no one to listen to her, still it was good practice to say it
+over) "--yes, that's about the right distance--but then I wonder what
+Latitude or Longitude I've got to?" (Alice had no idea what Latitude
+was, or Longitude either, but thought they were nice grand words to
+say.)
+
+Presently she began again. "I wonder if I shall fall right _through_ the
+earth! How funny it'll seem to come out among the people that walk with
+their heads downwards! The Antipathies, I think--" (she was rather glad
+there _was_ no one listening, this time, as it didn't sound at all the
+right word) "--but I shall have to ask them what the name of the country
+is, you know. Please, Ma'am, is this New Zealand or Australia?" (and she
+tried to curtsey as she spoke--fancy _curtseying_ as you're falling
+through the air! Do you think you could manage it?) "And what an
+ignorant little girl she'll think me! No, it'll never do to ask: perhaps
+I shall see it written up somewhere."
+
+Down, down, down. There was nothing else to do, so Alice soon began
+talking again. "Dinah'll miss me very much to-night, I should think!"
+(Dinah was the cat.) "I hope they'll remember her saucer of milk at
+tea-time. Dinah, my dear, I wish you were down here with me! There are
+no mice in the air, I'm afraid, but you might catch a bat, and that's
+very like a mouse, you know. But do cats eat bats, I wonder?" And here
+Alice began to get rather sleepy, and went on saying to herself, in a
+dreamy sort of way, "Do cats eat bats? Do cats eat bats?" and sometimes,
+"Do bats eat cats?" for, you see, as she couldn't answer either
+question, it didn't much matter which way she put it. She felt that she
+was dozing off, and had just begun to dream that she was walking hand in
+hand with Dinah, and saying to her very earnestly, "Now, Dinah, tell me
+the truth: did you ever eat a bat?" when suddenly, thump! thump! down
+she came upon a heap of sticks and dry leaves, and the fall was over.
+
+Alice was not a bit hurt, and she jumped up on to her feet in a moment:
+she looked up, but it was all dark overhead; before her was another long
+passage, and the White Rabbit was still in sight, hurrying down it.
+There was not a moment to be lost: away went Alice like the wind, and
+was just in time to hear it say, as it turned a corner, "Oh my ears and
+whiskers, how late it's getting!" She was close behind it when she
+turned the corner, but the Rabbit was no longer to be seen: she found
+herself in a long, low hall, which was lit up by a row of lamps hanging
+from the roof.
+
+There were doors all round the hall, but they were all locked; and when
+Alice had been all the way down one side and up the other, trying every
+door, she walked sadly down the middle, wondering how she was ever to
+get out again.
+
+Suddenly she came upon a little three-legged table, all made of solid
+glass; there was nothing on it but a tiny golden key, and Alice's first
+idea was that this might belong to one of the doors of the hall; but,
+alas! either the locks were too large, or the key was too small, but at
+any rate it would not open any of them. However, on the second time
+round, she came upon a low curtain she had not noticed before, and
+behind it was a little door about fifteen inches high: she tried the
+little golden key in the lock, and to her great delight it fitted!
+
+Alice opened the door and found that it led into a small passage, not
+much larger than a rat-hole: she knelt down and looked along the passage
+into the loveliest garden you ever saw. How she longed to get out of
+that dark hall, and wander about among those beds of bright flowers and
+those cool fountains, but she could not even get her head through the
+doorway; "and even if my head would go through," thought poor Alice, "it
+would be of very little use without my shoulders. Oh, how I wish I could
+shut up like a telescope! I think I could, if I only knew how to begin."
+For, you see, so many out-of-the-way things had happened lately, that
+Alice had begun to think that very few things indeed were really
+impossible.
+
+There seemed to be no use in waiting by the little door, so she went
+back to the table, half hoping she might find another key on it, or at
+any rate a book of rules for shutting people up like telescopes: this
+time she found a little bottle on it ("which certainly was not here
+before," said Alice,) and tied round the neck of the bottle was a paper
+label, with the words "DRINK ME" beautifully printed on it in large
+letters.
+
+It was all very well to say "Drink me," but the wise little Alice was
+not going to do _that_ in a hurry. "No, I'll look first," she said, "and
+see whether it's marked '_poison_' or not;" for she had read several
+nice little stories about children who had got burnt, and eaten up by
+wild beasts, and other unpleasant things, all because they _would_ not
+remember the simple rules their friends had taught them: such as, that a
+red-hot poker will burn you if you hold it too long; and that, if you
+cut your finger _very_ deeply with a knife, it usually bleeds; and she
+had never forgotten that, if you drink much from a bottle marked
+"poison," it is almost certain to disagree with you, sooner or later.
+
+However, this bottle was _not_ marked "poison," so Alice ventured to
+taste it, and finding it very nice (it had, in fact, a sort of mixed
+flavour of cherry-tart, custard, pineapple, roast turkey, coffee, and
+hot buttered toast,) she very soon finished it off.
+
+ * * * * *
+
+"What a curious feeling!" said Alice. "I must be shutting up like a
+telescope."
+
+And so it was indeed: she was now only ten inches high, and her face
+brightened up at the thought that she was now the right size for going
+through that little door into that lovely garden. First, however, she
+waited for a few minutes to see if she was going to shrink any further:
+she felt a little nervous about this: "for it might end, you know," said
+Alice to herself, "in my going out altogether, like a candle. I wonder
+what I should be like then?" And she tried to fancy what the flame of a
+candle looks like after the candle is blown out, for she could not
+remember ever having seen such a thing.
+
+After a while, finding that nothing more happened, she decided on going
+into the garden at once; but, alas for poor Alice! when she got to the
+door, she found she had forgotten the little golden key, and when she
+went back to the table for it, she found she could not possibly reach
+it: she could see it quite plainly through the glass, and she tried her
+best to climb up one of the legs of the table, but it was too slippery;
+and when she had tired herself out with trying, the poor little thing
+sat down and cried.
+
+"Come, there's no use in crying like that!" said Alice to herself,
+rather sharply. "I advise you to leave off this minute!" She generally
+gave herself very good advice (though she very seldom followed it), and
+sometimes she scolded herself so severely as to bring tears into her
+eyes; and once she remembered trying to box her own ears for having
+cheated herself in a game of croquet she was playing against herself,
+for this curious child was very fond of pretending to be two people.
+"But it's no use now," thought poor Alice, "to pretend to be two people!
+Why there's hardly enough of me left to make _one_ respectable person!"
+
+Soon her eye fell on a little glass box that was lying under the table:
+she opened it, and found in it a very small cake, on which the words
+"EAT ME" were beautifully marked in currants. "Well, I'll eat it," said
+Alice, "and if it makes me grow larger, I can reach the key; and if it
+makes me grow smaller, I can creep under the door; so either way I'll
+get into the garden, and I don't care which happens!"
+
+She ate a little bit, and said anxiously to herself, "Which way? Which
+way?" holding her hand on the top of her head to feel which way it was
+growing, and she was quite surprised to find that she remained the same
+size; to be sure, this is what generally happens when one eats cake,
+but Alice had got so much into the way of expecting nothing but
+out-of-the-way things to happen, that it seemed quite dull and stupid
+for life to go on in the common way.
+
+So she set to work, and very soon finished off the cake.
+
+ * * * * *
+
+
+
+
+CHAPTER II
+
+
+[Sidenote: _Pool of Tears_]
+
+"CURIOUSER and curiouser!" cried Alice (she was so much
+surprised, that for a moment she quite forgot how to speak good
+English); "now I'm opening out like the largest telescope that ever was!
+Good-bye, feet!" (for when she looked down at her feet, they seemed to
+be almost out of sight, they were getting so far off). "Oh, my poor
+little feet, I wonder who will put on your shoes and stockings for you
+now, dears? I'm sure _I_ sha'n't be able! I shall be a great deal too
+far off to trouble myself about you: you must manage the best way you
+can--but I must be kind to them," thought Alice, "or perhaps they won't
+walk the way I want to go! Let me see: I'll give them a new pair of
+boots every Christmas."
+
+And she went on planning to herself how she would manage it. "They must
+go by the carrier," she thought; "and how funny it'll seem, sending
+presents to one's own feet! And how odd the directions will look!
+
+ Alice's Right Foot, Esq.
+ Hearthrug,
+ near the Fender,
+ (with Alice's love).
+
+Oh dear, what nonsense I'm talking!"
+
+Just then her head struck against the roof of the hall: in fact she was
+now rather more than nine feet high, and she at once took up the little
+golden key and hurried off to the garden door.
+
+Poor Alice! It was as much as she could do, lying down on one side, to
+look through into the garden with one eye; but to get through was more
+hopeless than ever: she sat down and began to cry again.
+
+"You ought to be ashamed of yourself," said Alice, "a great girl like
+you" (she might well say this), "to go on crying in this way! Stop this
+moment, I tell you!" But she went on all the same, shedding gallons of
+tears, until there was a large pool all round her, about four inches
+deep and reaching half down the hall.
+
+[Illustration: CURIOUSER AND CURIOUSER]
+
+After a time she heard a little pattering of feet in the distance, and
+she hastily dried her eyes to see what was coming. It was the White
+Rabbit returning, splendidly dressed, with a pair of white kid gloves in
+one hand and a large fan in the other: he came trotting along in a great
+hurry, muttering to himself as he came, "Oh! the Duchess, the Duchess!
+Oh! won't she be savage if I've kept her waiting!" Alice felt so
+desperate that she was ready to ask help of any one; so, when the
+Rabbit came near her, she began, in a low, timid voice, "If you please,
+sir----" The Rabbit started violently, dropped the white kid gloves and
+the fan, and scurried away into the darkness as hard as he could go.
+
+Alice took up the fan and gloves, and, as the hall was very hot, she
+kept fanning herself all the time she went on talking! "Dear, dear! How
+queer everything is to-day! And yesterday things went on just as usual.
+I wonder if I've been changed during the night? Let me think: _was_ I
+the same when I got up this morning? I almost think I can remember
+feeling a little different. But if I'm not the same, the next question
+is, who in the world am I? Ah, _that's_ the great puzzle!" And she began
+thinking over all the children she knew that were of the same age as
+herself, to see if she could have been changed for any of them.
+
+"I'm sure I'm not Ada," she said, "for her hair goes in such long
+ringlets, and mine doesn't go in ringlets at all; and I'm sure I can't
+be Mabel, for I know all sorts of things, and she, oh! she knows such a
+very little! Besides, _she's_ she, and _I'm_ I, and--oh dear, how
+puzzling it all is! I'll try if I know all the things I used to know.
+Let me see: four times five is twelve, and four times six is thirteen,
+and four times seven is--oh dear! I shall never get to twenty at that
+rate! However, the Multiplication Table doesn't signify: let's try
+Geography. London is the capital of Paris, and Paris is the capital of
+Rome, and Rome--no, _that's_ all wrong, I'm certain! I must have been
+changed for Mabel! I'll try and say '_How doth the little----_'" and she
+crossed her hands on her lap as if she were saying lessons, and began to
+repeat it, but her voice sounded hoarse and strange, and the words did
+not come the same as they used to do:--
+
+ "How doth the little crocodile
+ Improve his shining tail,
+ And pour the waters of the Nile
+ On every golden scale!
+
+ "How cheerfully he seems to grin,
+ How neatly spreads his claws,
+ And welcomes little fishes in,
+ With gently smiling jaws!"
+
+"I'm sure those are not the right words," said poor Alice, and her eyes
+filled with tears again as she went on. "I must be Mabel, after all, and
+I shall have to go and live in that poky little house, and have next to
+no toys to play with, and oh! ever so many lessons to learn! No, I've
+made up my mind about it; if I'm Mabel, I'll stay down here! It'll be no
+use their putting their heads down and saying, 'Come up again, dear!' I
+shall only look up and say, 'Who am I then? Tell me that first, and
+then, if I like being that person, I'll come up: if not, I'll stay down
+here till I'm somebody else'--but, oh dear!" cried Alice with a sudden
+burst of tears, "I do wish they _would_ put their heads down! I am so
+_very_ tired of being all alone here!"
+
+As she said this she looked down at her hands, and was surprised to see
+that she had put on one of the Rabbit's little white kid gloves while
+she was talking. "How _can_ I have done that?" she thought. "I must be
+growing small again." She got up and went to the table to measure
+herself by it, and found that, as nearly as she could guess, she was now
+about two feet high, and was going on shrinking rapidly: she soon found
+out that the cause of this was the fan she was holding, and she dropped
+it hastily, just in time to avoid shrinking away altogether.
+
+"That _was_ a narrow escape!" said Alice, a good deal frightened at the
+sudden change, but very glad to find herself still in existence; "and
+now for the garden!" and she ran with all speed back to the little door:
+but alas! the little door was shut again, and the little golden key was
+lying on the glass table as before, "and things are worse than ever,"
+thought the poor child, "for I never was so small as this before, never!
+And I declare it's too bad, that it is!"
+
+As she said these words her foot slipped, and in another moment, splash!
+she was up to her chin in salt water. Her first idea was that she had
+somehow fallen into the sea, "and in that case I can go back by
+railway," she said to herself. (Alice had been to the seaside once in
+her life, and had come to the general conclusion, that wherever you go
+to on the English coast you find a number of bathing machines in the
+sea, some children digging in the sand with wooden spades, then a row
+of lodging houses, and behind them a railway station.) However, she soon
+made out that she was in the pool of tears which she had wept when she
+was nine feet high.
+
+"I wish I hadn't cried so much!" said Alice, as she swam about, trying
+to find her way out. "I shall be punished for it now, I suppose, by
+being drowned in my own tears! That _will_ be a queer thing, to be sure!
+However, everything is queer to-day."
+
+Just then she heard something splashing about in the pool a little way
+off, and she swam nearer to make out what it was: at first she thought
+it must be a walrus or hippopotamus, but then she remembered how small
+she was now, and she soon made out that it was only a mouse that had
+slipped in like herself.
+
+"Would it be of any use now," thought Alice, "to speak to this mouse?
+Everything is so out-of-the-way down here, that I should think very
+likely it can talk: at any rate, there's no harm in trying." So she
+began: "O Mouse, do you know the way out of this pool? I am very tired
+of swimming about here, O Mouse!" (Alice thought this must be the right
+way of speaking to a mouse; she had never done such a thing before, but
+she remembered having seen in her brother's Latin Grammar, "A mouse--of
+a mouse--to a mouse--a mouse--O mouse!") The Mouse looked at her rather
+inquisitively, and seemed to her to wink with one of its little eyes,
+but it said nothing.
+
+"Perhaps it doesn't understand English," thought Alice; "I daresay it's
+a French mouse, come over with William the Conqueror." (For, with all
+her knowledge of history, Alice had no very clear notion how long ago
+anything had happened.) So she began again: "O est ma chatte?" which
+was the first sentence in her French lesson-book. The Mouse gave a
+sudden leap out of the water, and seemed to quiver all over with fright.
+"Oh, I beg your pardon!" cried Alice hastily, afraid that she had hurt
+the poor animal's feelings. "I quite forgot you didn't like cats."
+
+"Not like cats!" cried the Mouse, in a shrill, passionate voice. "Would
+_you_ like cats if you were me?"
+
+"Well, perhaps not," said Alice in a soothing tone: "don't be angry
+about it. And yet I wish I could show you our cat Dinah: I think you'd
+take a fancy to cats if you could only see her. She is such a dear quiet
+thing," Alice went on, half to herself, as she swam lazily about in the
+pool, "and she sits purring so nicely by the fire, licking her paws and
+washing her face--and she is such a nice soft thing to nurse--and she's
+such a capital one for catching mice----oh, I beg your pardon!" cried
+Alice again, for this time the Mouse was bristling all over, and she
+felt certain it must be really offended. "We won't talk about her any
+more if you'd rather not."
+
+"We, indeed!" cried the Mouse, who was trembling down to the end of his
+tail. "As if _I_ would talk on such a subject! Our family always _hated_
+cats: nasty, low, vulgar things! Don't let me hear the name again!"
+
+[Illustration: _The Pool of Tears_]
+
+"I won't indeed!" said Alice, in a great hurry to change the subject of
+conversation. "Are you--are you fond--of--of dogs?" The Mouse did not
+answer, so Alice went on eagerly: "There is such a nice little dog near
+our house I should like to show you! A little bright-eyed terrier, you
+know, with oh, such long curly brown hair! And it'll fetch things
+when you throw them, and it'll sit up and beg for its dinner, and all
+sorts of things--I can't remember half of them--and it belongs to a
+farmer, you know, and he says it's so useful, it's worth a hundred
+pounds! He says it kills all the rats and--oh dear!" cried Alice in a
+sorrowful tone, "I'm afraid I've offended it again!" For the Mouse was
+swimming away from her as hard as it could go, and making quite a
+commotion in the pool as it went.
+
+So she called softly after it, "Mouse dear! Do come back again, and we
+won't talk about cats or dogs either, if you don't like them!"
+
+When the Mouse heard this, it turned round and swam slowly back to her:
+its face was quite pale (with passion, Alice thought), and it said in a
+low trembling voice, "Let us get to the shore, and then I'll tell you my
+history, and you'll understand why it is I hate cats and dogs."
+
+It was high time to go, for the pool was getting quite crowded with the
+birds and animals that had fallen into it: there were a Duck and a Dodo,
+a Lory and an Eaglet, and several other curious creatures. Alice led the
+way, and the whole party swam to the shore.
+
+
+
+
+CHAPTER III
+
+
+[Sidenote: _A Caucus-race and a Long Tale_]
+
+THEY were indeed a queer-looking party that assembled on
+the bank--the birds with draggled feathers, the animals with their fur
+clinging close to them, and all dripping wet, cross, and uncomfortable.
+
+The first question of course was, how to get dry again: they had a
+consultation about this, and after a few minutes it seemed quite natural
+to Alice to find herself talking familiarly with them, as if she had
+known them all her life. Indeed, she had quite a long argument with the
+Lory, who at last turned sulky, and would only say, "I am older than
+you, and must know better;" and this Alice would not allow without
+knowing how old it was, and, as the Lory positively refused to tell its
+age, there was no more to be said.
+
+At last the Mouse, who seemed to be a person of authority among them,
+called out "Sit down, all of you, and listen to me! _I'll_ soon make you
+dry enough!" They all sat down at once, in a large ring, with the Mouse
+in the middle. Alice kept her eyes anxiously fixed on it, for she felt
+sure she would catch a bad cold if she did not get dry very soon.
+
+"Ahem!" said the Mouse with an important air. "Are you all ready? This
+is the driest thing I know. Silence all round, if you please! 'William
+the Conqueror, whose cause was favoured by the pope, was soon submitted
+to by the English, who wanted leaders, and had been of late much
+accustomed to usurpation and conquest. Edwin and Morcar, the earls of
+Mercia and Northumbria--'"
+
+"Ugh!" said the Lory, with a shiver.
+
+"I beg your pardon!" said the Mouse, frowning, but very politely. "Did
+you speak?"
+
+"Not I!" said the Lory hastily.
+
+"I thought you did," said the Mouse, "--I proceed. 'Edwin and Morcar,
+the earls of Mercia and Northumbria, declared for him: and even
+Stigand, the patriotic Archbishop of Canterbury, found it advisable--'"
+
+"Found _what_?" said the Duck.
+
+"Found _it_," the Mouse replied rather crossly: "of course you know what
+'it' means."
+
+"I know what 'it' means well enough, when _I_ find a thing," said the
+Duck; "it's generally a frog or a worm. The question is, what did the
+archbishop find?"
+
+The Mouse did not notice this question, but hurriedly went on, "'--found
+it advisable to go with Edgar Atheling to meet William and offer him the
+crown. William's conduct at first was moderate. But the insolence of his
+Normans--' How are you getting on now, my dear?" it continued, turning
+to Alice as it spoke.
+
+"As wet as ever," said Alice in a melancholy tone; "doesn't seem to dry
+me at all."
+
+"In that case," said the Dodo solemnly, rising to its feet, "I move that
+the meeting adjourn, for the immediate adoption of more energetic
+remedies----"
+
+"Speak English!" said the Eaglet. "I don't know the meaning of half
+those long words, and, what's more, I don't believe you do either!" And
+the Eaglet bent down its head to hide a smile: some of the other birds
+tittered audibly.
+
+"What I was going to say," said the Dodo in an offended tone, "was that
+the best thing to get us dry would be a Caucus-race."
+
+"What _is_ a Caucus-race?" said Alice; not that she much wanted to know,
+but the Dodo had paused as if it thought that _somebody_ ought to speak,
+and no one else seemed inclined to say anything.
+
+"Why," said the Dodo, "the best way to explain it is to do it." (And, as
+you might like to try the thing yourself some winter day, I will tell
+you how the Dodo managed it.)
+
+First it marked out a race-course, in a sort of circle, ("the exact
+shape doesn't matter," it said,) and then all the party were placed
+along the course, here and there. There was no "One, two, three, and
+away," but they began running when they liked, and left off when they
+liked, so that it was not easy to know when the race was over. However,
+when they had been running half an hour or so, and were quite dry again,
+the Dodo suddenly called "The race is over!" and they all crowded round
+it, panting, and asking "But who has won?"
+
+This question the Dodo could not answer without a great deal of thought,
+and it stood for a long time with one finger pressed upon its forehead
+(the position in which you usually see Shakespeare, in the pictures of
+him), while the rest waited in silence. At last the Dodo said
+"_Everybody_ has won, and _all_ must have prizes."
+
+"But who is to give the prizes?" quite a chorus of voices asked.
+
+"Why, _she_, of course," said the Dodo, pointing to Alice with one
+finger; and the whole party at once crowded round her, calling out in a
+confused way, "Prizes! Prizes!"
+
+Alice had no idea what to do, and in despair she put her hand in her
+pocket, and pulled out a box of comfits (luckily the salt water had not
+got into it), and handed them round as prizes. There was exactly one
+apiece all round.
+
+ _They all crowded round it panting and asking,
+ "But who has won?"_
+
+[Illustration]
+
+"But she must have a prize herself, you know," said the Mouse.
+
+"Of course," the Dodo replied very gravely.
+
+"What else have you got in your pocket?" it went on, turning to Alice.
+
+"Only a thimble," said Alice sadly.
+
+"Hand it over here," said the Dodo.
+
+Then they all crowded round her once more, while the Dodo solemnly
+presented the thimble, saying "We beg your acceptance of this elegant
+thimble;" and, when it had finished this short speech, they all cheered.
+
+Alice thought the whole thing very absurd, but they all looked so grave
+that she did not dare to laugh; and, as she could not think of anything
+to say, she simply bowed, and took the thimble, looking as solemn as she
+could.
+
+The next thing was to eat the comfits; this caused some noise and
+confusion, as the large birds complained that they could not taste
+theirs, and the small ones choked and had to be patted on the back.
+However, it was over at last, and they sat down again in a ring, and
+begged the Mouse to tell them something more.
+
+"You promised to tell me your history, you know," said Alice, "and why
+it is you hate--C and D," she added in a whisper, half afraid that it
+would be offended again.
+
+[Illustration]
+
+"Mine is a long and sad tale!" said the Mouse, turning to Alice and
+sighing.
+
+"It _is_ a long tail, certainly," said Alice, looking down with wonder
+at the Mouse's tail; "but why do you call it sad?" And she kept on
+puzzling about it while the Mouse was speaking, so that her idea of the
+tale was something like this:--
+
+ "Fury said to
+ a mouse, That
+ he met in the
+ house, 'Let
+ us both go
+ to law: _I_
+ will prose-
+ cute _you_.--
+ Come, I'll
+ take no de-
+ nial: We
+ must have
+ the trial;
+ For really
+ this morn-
+ ing I've
+ nothing
+ to do.'
+ Said the
+ mouse to
+ the cur,
+ 'Such a
+ trial, dear
+ sir, With
+ no jury
+ or judge,
+ would
+ be wast-
+ ing our
+ breath.'
+ 'I'll be
+ judge,
+ I'll be
+ jury,'
+ said
+ cun-
+ ning
+ old
+ Fury:
+ 'I'll
+ try
+ the
+ whole
+ cause,
+ and
+ con-
+ demn
+ you to
+ death.'
+
+"You are not attending!" said the Mouse to Alice severely. "What are you
+thinking of?"
+
+"I beg your pardon," said Alice very humbly: "you had got to the fifth
+bend, I think?"
+
+"I had _not_!" cried the Mouse, angrily.
+
+"A knot!" said Alice, always ready to make herself useful, and looking
+anxiously about her. "Oh, do let me help to undo it!"
+
+"I shall do nothing of the sort," said the Mouse, getting up and walking
+away. "You insult me by talking such nonsense!"
+
+"I didn't mean it!" pleaded poor Alice. "But you're so easily offended,
+you know!"
+
+The Mouse only growled in reply.
+
+"Please come back and finish your story!" Alice called after it. And the
+others all joined in chorus, "Yes, please do!" but the Mouse only shook
+its head impatiently and walked a little quicker.
+
+"What a pity it wouldn't stay!" sighed the Lory, as soon as it was quite
+out of sight; and an old Crab took the opportunity of saying to her
+daughter, "Ah, my dear! Let this be a lesson to you never to lose
+_your_ temper!" "Hold your tongue, Ma!" said the young Crab, a little
+snappishly. "You're enough to try the patience of an oyster!"
+
+"I wish I had our Dinah here, I know I do!" said Alice aloud, addressing
+nobody in particular. "She'd soon fetch it back!"
+
+"And who is Dinah, if I might venture to ask the question?" said the
+Lory.
+
+Alice replied eagerly, for she was always ready to talk about her pet:
+"Dinah's our cat. And she's such a capital one for catching mice, you
+ca'n't think! And oh, I wish you could see her after the birds! Why,
+she'll eat a little bird as soon as look at it!"
+
+This speech caused a remarkable sensation among the party. Some of the
+birds hurried off at once; one old Magpie began wrapping itself up very
+carefully, remarking "I really must be getting home; the night-air
+doesn't suit my throat!" and a Canary called out in a trembling voice to
+its children "Come away, my dears! It's high time you were all in bed!"
+On various pretexts they all moved off, and Alice was soon left alone.
+
+"I wish I hadn't mentioned Dinah!" she said to herself in a melancholy
+tone. "Nobody seems to like her, down here, and I'm sure she's the best
+cat in the world! Oh, my dear Dinah! I wonder if I shall ever see you
+any more!" And here poor Alice began to cry again, for she felt very
+lonely and low-spirited. In a little while, however, she again heard a
+little pattering of footsteps in the distance, and she looked up
+eagerly, half hoping that the Mouse had changed his mind, and was coming
+back to finish his story.
+
+
+
+
+CHAPTER IV
+
+
+[Sidenote: _The Rabbit sends in a Little Bill_]
+
+IT was the White Rabbit, trotting slowly back again, and
+looking anxiously about as it went, as if it had lost something; and she
+heard it muttering to itself, "The Duchess! The Duchess! Oh my dear
+paws! Oh my fur and whiskers! She'll get me executed, as sure as ferrets
+are ferrets! Where _can_ I have dropped them, I wonder?" Alice guessed
+in a moment that it was looking for the fan and the pair of white kid
+gloves, and she very good-naturedly began hunting about for them, but
+they were nowhere to be seen--everything seemed to have changed since
+her swim in the pool, and the great hall, with the glass table and the
+little door, had vanished completely.
+
+Very soon the Rabbit noticed Alice, as she went hunting about, and
+called out to her in an angry tone, "Why, Mary Ann, what _are_ you
+doing out here? Run home this moment, and fetch me a pair of gloves and
+a fan! Quick, now!" And Alice was so much frightened that she ran off at
+once in the direction it pointed to, without trying to explain the
+mistake it had made.
+
+"He took me for his housemaid," she said to herself as she ran. "How
+surprised he'll be when he finds out who I am! But I'd better take him
+his fan and gloves--that is, if I can find them." As she said this, she
+came upon a neat little house, on the door of which was a bright brass
+plate with the name "W. RABBIT" engraved upon it. She went in without
+knocking, and hurried up stairs, in great fear lest she should meet the
+real Mary Ann, and be turned out of the house before she had found the
+fan and gloves.
+
+[Illustration: "_Why, Mary Ann, what are you doing out here?_"]
+
+"How queer it seems," Alice said to herself, "to be going messages for a
+rabbit! I suppose Dinah'll be sending me on messages next!" And she
+began fancying the sort of thing that would happen: "'Miss Alice! Come
+here directly, and get ready for your walk!' 'Coming in a minute, nurse!
+But I've got to watch this mouse-hole till Dinah comes back, and see
+that the mouse doesn't get out.' Only I don't think," Alice went on,
+"that they'd let Dinah stop in the house if it began ordering people
+about like that!"
+
+By this time she had found her way into a tidy little room with a table
+in the window, and on it (as she had hoped) a fan and two or three pairs
+of tiny white kid gloves: she took up the fan and a pair of the gloves,
+and was just going to leave the room, when her eye fell upon a little
+bottle that stood near the looking-glass. There was no label this time
+with the words "DRINK ME," but nevertheless she uncorked it and put it
+to her lips. "I know _something_ interesting is sure to happen," she
+said to herself, "whenever I eat or drink anything; so I'll just see
+what this bottle does. I do hope it will make me grow large again, for
+really I'm quite tired of being such a tiny little thing!"
+
+It did so indeed, and much sooner than she had expected: before she had
+drunk half the bottle, she found her head pressing against the ceiling,
+and had to stoop to save her neck from being broken. She hastily put
+down the bottle, saying to herself "That's quite enough--I hope I
+sha'n't grow any more--As it is, I can't get out at the door--I do wish
+I hadn't drunk quite so much!"
+
+Alas! it was too late to wish that! She went on growing, and growing,
+and very soon had to kneel down on the floor: in another minute there
+was not even room for this, and she tried the effect of lying down with
+one elbow against the door, and the other arm curled round her head.
+Still she went on growing, and, as a last resource, she put one arm out
+of the window, and one foot up the chimney, and said to herself "Now I
+can do no more, whatever happens. What _will_ become of me?"
+
+Luckily for Alice, the little magic bottle had now had its full effect,
+and she grew no larger: still it was very uncomfortable, and, as there
+seemed to be no sort of chance of her ever getting out of the room
+again, no wonder she felt unhappy.
+
+"It was much pleasanter at home," thought poor Alice, "when one wasn't
+always growing larger and smaller, and being ordered about by mice and
+rabbits. I almost wish I hadn't gone down that rabbit-hole--and
+yet--and yet--it's rather curious, you know, this sort of life! I do
+wonder what _can_ have happened to me! When I used to read fairy-tales,
+I fancied that kind of thing never happened, and now here I am in the
+middle of one! There ought to be a book written about me, that there
+ought! And when I grow up, I'll write one--but I'm grown up now," she
+added in a sorrowful tone; "at least there's no room to grow up any more
+_here_."
+
+"But then," thought Alice, "shall I _never_ get any older than I am now?
+That'll be a comfort, one way--never to be an old woman--but
+then--always to have lessons to learn! Oh, I shouldn't like _that_!"
+
+"Oh, you foolish Alice!" she answered herself. "How can you learn
+lessons in here? Why, there's hardly room for _you_, and no room at all
+for any lesson-books!"
+
+And so she went on, taking first one side and then the other, and making
+quite a conversation of it altogether; but after a few minutes she heard
+a voice outside, and stopped to listen.
+
+"Mary Ann! Mary Ann!" said the voice. "Fetch me my gloves this moment!"
+Then came a little pattering of feet on the stairs. Alice knew it was
+the Rabbit coming to look for her, and she trembled till she shook the
+house, quite forgetting that she was now about a thousand times as large
+as the Rabbit, and had no reason to be afraid of it.
+
+Presently the Rabbit came up to the door, and tried to open it; but, as
+the door opened inwards, and Alice's elbow was pressed hard against it,
+that attempt proved a failure. Alice heard it say to itself "Then I'll
+go round and get in at the window."
+
+"_That_ you won't" thought Alice, and, after waiting till she fancied
+she heard the Rabbit just under the window, she suddenly spread out her
+hand, and made a snatch in the air. She did not get hold of anything,
+but she heard a little shriek and a fall, and a crash of broken glass,
+from which she concluded that it was just possible it had fallen into a
+cucumber-frame, or something of the sort.
+
+Next came an angry voice--the Rabbit's--"Pat! Pat! Where are you?" And
+then a voice she had never heard before, "Sure then I'm here! Digging
+for apples, yer honour!"
+
+"Digging for apples, indeed!" said the Rabbit angrily. "Here! Come and
+help me out of _this_!" (Sounds of more broken glass.)
+
+"Now tell me, Pat, what's that in the window?"
+
+"Sure, it's an arm, yer honour." (He pronounced it "arrum.")
+
+"An arm, you goose! Who ever saw one that size? Why, it fills the whole
+window!"
+
+"Sure, it does, yer honour? but it's an arm for all that."
+
+"Well, it's got no business there, at any rate: go and take it away!"
+
+There was a long silence after this, and Alice could only hear whispers
+now and then; such as, "Sure, I don't like it, yer honour, at all, at
+all!" "Do as I tell you, you coward!" and at last she spread out her
+hand again, and made another snatch in the air. This time there were
+_two_ little shrieks, and more sounds of broken glass. "What a number of
+cucumber-frames there must be!" thought Alice. "I wonder what they'll do
+next! As for pulling me out of the window, I only wish they _could_!
+I'm sure _I_ don't want to stay in here any longer!"
+
+She waited for some time without hearing anything more: at last came a
+rumbling of little cart-wheels, and the sound of a good many voices all
+talking together: she made out the words: "Where's the other
+ladder?--Why I hadn't to bring but one; Bill's got the other--Bill!
+Fetch it here, lad!--Here, put 'em up at this corner--No, tie 'em
+together first--they don't reach half high enough yet--Oh! they'll do
+well enough; don't be particular--Here, Bill! catch hold of this
+rope--Will the roof bear?--Mind that loose slate--Oh, it's coming down!
+Heads below!" (a loud crash)--"Now, who did that?--It was Bill, I
+fancy--Who's to go down the chimney?--Nay, _I_ sha'n't! _You_ do
+it!--_That_ I won't, then! Bill's to go down--Here, Bill! the master
+says you've to go down the chimney!"
+
+"Oh! So Bill's got to come down the chimney, has he?" said Alice to
+herself. "Why, they seem to put everything upon Bill! I wouldn't be in
+Bill's place for a good deal: this fireplace is narrow, to be sure; but
+I _think_ I can kick a little!"
+
+She drew her foot as far down the chimney as she could, and waited till
+she heard a little animal (she couldn't guess of what sort it was)
+scratching and scrambling about in the chimney close above her: then,
+saying to herself "This is Bill," she gave one sharp kick, and waited to
+see what would happen next.
+
+The first thing she heard was a general chorus of "There goes Bill!"
+then the Rabbit's voice alone--"Catch him, you by the hedge!" then
+silence, and then another confusion of voices--"Hold up his head--Brandy
+now--Don't choke him--How was it, old fellow? What happened to you? Tell
+us all about it!"
+
+At last came a little feeble, squeaking voice, ("That's Bill," thought
+Alice,) "Well, I hardly know--No more, thank ye; I'm better now--but I'm
+a deal too flustered to tell you--all I know is, something comes at me
+like a Jack-in-the-box, and up I goes like a sky-rocket!"
+
+"So you did, old fellow!" said the others.
+
+"We must burn the house down!" said the Rabbit's voice. And Alice
+called out as loud as she could, "If you do, I'll set Dinah at you!"
+
+There was a dead silence instantly, and Alice thought to herself "I
+wonder what they _will_ do next! If they had any sense, they'd take the
+roof off." After a minute or two they began moving about again, and
+Alice heard the Rabbit say "A barrowful will do, to begin with."
+
+"A barrowful of _what_?" thought Alice. But she had not long to doubt,
+for the next moment a shower of little pebbles came rattling in at the
+window, and some of them hit her in the face. "I'll put a stop to this,"
+she said to herself, and shouted out "You'd better not do that again!"
+which produced another dead silence.
+
+Alice noticed with some surprise that the pebbles were all turning into
+little cakes as they lay on the floor, and a bright idea came into her
+head. "If I eat one of these cakes," she thought, "it's sure to make
+_some_ change in my size; and, as it can't possibly make me larger, it
+must make me smaller, I suppose."
+
+So she swallowed one of the cakes, and was delighted to find that she
+began shrinking directly. As soon as she was small enough to get through
+the door, she ran out of the house, and found quite a crowd of little
+animals and birds waiting outside. The poor little Lizard, Bill, was in
+the middle, being held up by two guinea-pigs, who were giving it
+something out of a bottle. They all made a rush at Alice the moment she
+appeared; but she ran off as hard as she could, and soon found herself
+safe in a thick wood.
+
+"The first thing I've got to do," said Alice to herself, as she wandered
+about in the wood, "is to grow to my right size again; and the second
+thing is to find my way into that lovely garden. I think that will be
+the best plan."
+
+It sounded an excellent plan, no doubt, and very neatly and simply
+arranged; the only difficulty was, that she had not the smallest idea
+how to set about it; and, while she was peering about anxiously among
+the trees, a little sharp bark just over her head made her look up in a
+great hurry.
+
+An enormous puppy was looking down at her with large round eyes, and
+feebly stretching out one paw, trying to touch her. "Poor little
+thing!" said Alice, in a coaxing tone, and she tried hard to whistle to
+it; but she was terribly frightened all the time at the thought that it
+might be hungry, in which case it would be very likely to eat her up in
+spite of all her coaxing.
+
+Hardly knowing what she did, she picked up a little bit of stick, and
+held it out to the puppy; whereupon the puppy jumped into the air off
+all its feet at once, with a yelp of delight, and rushed at the stick,
+and made believe to worry it; then Alice dodged behind a great thistle,
+to keep herself from being run over; and, the moment she appeared on the
+other side, the puppy made another rush at the stick, and tumbled head
+over heels in its hurry to get hold of it; then Alice, thinking it was
+very like having a game of play with a cart-horse, and expecting every
+moment to be trampled under its feet, ran round the thistle again; then
+the puppy began a series of short charges at the stick, running a little
+way forwards each time and a long way back, and barking hoarsely all the
+while, till at last it sat down a good way off, panting, with its
+tongue hanging out of its mouth, and its great eyes half shut.
+
+This seemed to Alice a good opportunity for making her escape; so she
+set off at once, and ran till she was quite tired and out of breath, and
+till the puppy's bark sounded quite faint in the distance.
+
+"And yet what a dear little puppy it was!" said Alice, as she leant
+against a buttercup to rest herself, and fanned herself with one of the
+leaves. "I should have liked teaching it tricks very much, if--if I'd
+only been the right size to do it! Oh, dear! I'd nearly forgotten that
+I've got to grow up again! Let me see--how _is_ it to be managed? I
+suppose I ought to eat or drink something or other; but the great
+question is, what?"
+
+The great question certainly was, what? Alice looked all round her at
+the flowers and the blades of grass, but she could not see anything that
+looked like the right thing to eat or drink under the circumstances.
+There was a large mushroom growing near her, about the same height as
+herself; and, when she had looked under it, and on both sides of it, and
+behind it, it occurred to her that she might as well look and see what
+was on the top of it.
+
+She stretched herself up on tiptoe, and peeped over the edge of the
+mushroom, and her eyes immediately met those of a large blue
+caterpillar, that was sitting on the top with its arms folded, quietly
+smoking a long hookah, and taking not the smallest notice of her or of
+anything else.
+
+
+
+
+CHAPTER V
+
+
+[Sidenote: _Advice from a Caterpillar_]
+
+THE Caterpillar and Alice looked at each other for some
+time in silence: at last the Caterpillar took the hookah out of its
+mouth, and addressed her in a languid, sleepy voice.
+
+"Who are _you_?" said the Caterpillar.
+
+This was not an encouraging opening for a conversation. Alice replied,
+rather shyly, "I hardly know, sir, just at present--at least I know who
+I _was_ when I got up this morning, but I think I must have been changed
+several times since then."
+
+"What do you mean by that?" said the Caterpillar sternly. "Explain
+yourself!"
+
+"I can't explain _myself_, I'm afraid, sir," said Alice, "because I'm
+not myself, you see."
+
+"I don't see," said the Caterpillar.
+
+"I'm afraid I can't put it more clearly," Alice replied very politely,
+"for I can't understand it myself to begin with; and being so many
+different sizes in a day is very confusing."
+
+"It isn't," said the Caterpillar.
+
+"Well, perhaps you haven't found it so yet," said Alice, "but when you
+have to turn into a chrysalis--you will some day, you know--and then
+after that into a butterfly, I should think you'll feel it a little
+queer, won't you?"
+
+"Not a bit," said the Caterpillar.
+
+"Well, perhaps your feelings may be different," said Alice; "all I know
+is, it would feel very queer to _me_."
+
+"You!" said the Caterpillar contemptuously. "Who are _you_?"
+
+Which brought them back again to the beginning of the conversation.
+Alice felt a little irritated at the Caterpillar's making such _very_
+short remarks, and she drew herself up and said, very gravely, "I think
+you ought to tell me who _you_ are, first."
+
+"Why?" said the Caterpillar.
+
+[Illustration: _Advice from a Caterpillar_]
+
+Here was another puzzling question; and as Alice could not think of any
+good reason, and as the Caterpillar seemed to be in a _very_
+unpleasant state of mind, she turned away.
+
+"Come back!" the Caterpillar called after her. "I've something important
+to say!"
+
+This sounded promising, certainly: Alice turned and came back again.
+
+"Keep your temper," said the Caterpillar.
+
+"Is that all?" said Alice, swallowing down her anger as well as she
+could.
+
+"No," said the Caterpillar.
+
+Alice thought she might as well wait, as she had nothing else to do, and
+perhaps after all it might tell her something worth hearing. For some
+minutes it puffed away without speaking, but at last it unfolded its
+arms, took the hookah out of its mouth again, and said, "So you think
+you're changed, do you?"
+
+"I'm afraid I am, sir," said Alice; "I can't remember things as I
+used--and I don't keep the same size for ten minutes together!"
+
+"Can't remember _what_ things?" said the Caterpillar.
+
+"Well, I've tried to say '_How doth the little busy bee_,' but it all
+came different!" Alice replied in a very melancholy voice.
+
+"Repeat '_You are old, Father William_,'" said the Caterpillar.
+
+Alice folded her hands, and began:--
+
+ "You are old, Father William," the young man said,
+ "And your hair has become very white;
+ And yet you incessantly stand on your head--
+ Do you think, at your age, it is right?"
+
+ "In my youth," Father William replied to his son,
+ "I feared it might injure the brain;
+ But, now that I'm perfectly sure I have none,
+ Why, I do it again and again."
+
+ "You are old," said the youth, "as I mentioned before,
+ And have grown most uncommonly fat;
+ Yet you turned a back-somersault in at the door--
+ Pray, what is the reason of that?"
+
+ "In my youth," said the sage, as he shook his grey locks,
+ "I kept all my limbs very supple
+ By the use of this ointment--one shilling the box--
+ Allow me to sell you a couple?"
+
+ "You are old," said the youth, "and your jaws are too weak
+ For anything tougher than suet;
+ Yet you finished the goose, with the bones and the beak--
+ Pray, how did you manage to do it?"
+
+ "In my youth," said his father, "I took to the law
+ And argued each case with my wife;
+ And the muscular strength, which it gave to my jaw,
+ Has lasted the rest of my life."
+
+ "You are old," said the youth, "one would hardly suppose
+ That your eye was as steady as ever;
+ Yet you balanced an eel on the end of your nose--
+ What made you so awfully clever?"
+
+ "I have answered three questions, and that is enough,"
+ Said his father; "don't give yourself airs!
+ Do you think I can listen all day to such stuff?
+ Be off, or I'll kick you down stairs!"
+
+"That is not said right," said the Caterpillar.
+
+"Not _quite_ right, I'm afraid," said Alice, timidly; "some of the
+words have got altered."
+
+"It is wrong from beginning to end," said the Caterpillar, decidedly,
+and there was silence for some minutes.
+
+The Caterpillar was the first to speak.
+
+"What size do you want to be?" it asked.
+
+"Oh, I'm not particular as to size," Alice hastily replied; "only one
+doesn't like changing so often, you know."
+
+"I _don't_ know," said the Caterpillar.
+
+Alice said nothing: she had never been so much contradicted in all her
+life before, and she felt that she was losing her temper.
+
+"Are you content now?" said the Caterpillar.
+
+"Well, I should like to be a _little_ larger, sir, if you wouldn't
+mind," said Alice: "three inches is such a wretched height to be."
+
+"It is a very good height indeed!" said the Caterpillar angrily, rearing
+itself upright as it spoke (it was exactly three inches high).
+
+"But I'm not used to it!" pleaded poor Alice in a piteous tone. And she
+thought to herself, "I wish the creatures wouldn't be so easily
+offended!"
+
+"You'll get used to it in time," said the Caterpillar; and it put its
+hookah into its mouth and began smoking again.
+
+This time Alice waited patiently until it chose to speak again. In a
+minute or two the Caterpillar took the hookah out of its mouth and
+yawned once or twice, and shook itself. Then it got down off the
+mushroom, and crawled away into the grass, merely remarking as it went,
+"One side will make you grow taller, and the other side will make you
+grow shorter."
+
+"One side of _what_? The other side of _what_?" thought Alice to
+herself.
+
+"Of the mushroom," said the Caterpillar, just as if she had asked it
+aloud; and in another moment it was out of sight.
+
+Alice remained looking thoughtfully at the mushroom for a minute, trying
+to make out which were the two sides of it; and as it was perfectly
+round, she found this a very difficult question. However, at last she
+stretched her arms round it as far as they would go, and broke off a bit
+of the edge with each hand.
+
+"And now which is which?" she said to herself, and nibbled a little of
+the right-hand bit to try the effect: the next moment she felt a violent
+blow underneath her chin: it had struck her foot!
+
+[Illustration]
+
+She was a good deal frightened by this very sudden change, but she felt
+that there was no time to be lost, as she was shrinking rapidly; so she
+set to work at once to eat some of the other bit. Her chin was pressed
+so closely against her foot that there was hardly room to open her
+mouth; but she did it at last, and managed to swallow a morsel of the
+left-hand bit.
+
+ * * * * *
+
+"Come, my head's free at last!" said Alice in a tone of delight, which
+changed into alarm in another moment, when she found that her shoulders
+were nowhere to be found: all she could see, when she looked down, was
+an immense length of neck, which seemed to rise like a stalk out of a
+sea of green leaves that lay far below her.
+
+"What _can_ all that green stuff be?" said Alice. "And where have my
+shoulders got to? And oh, my poor hands, how is it I ca'n't see you?"
+She was moving them about as she spoke, but no result seemed to follow,
+except a little shaking among the distant green leaves.
+
+As there seemed to be no chance of getting her hands up to her head, she
+tried to get her head down to them, and was delighted to find that her
+neck would bend about easily in any direction, like a serpent. She had
+just succeeded in curving it down into a graceful zigzag, and was going
+to dive in among the leaves, which she found to be nothing but the tops
+of the trees under which she had been wandering, when a sharp hiss made
+her draw back in a hurry: a large pigeon had flown into her face, and
+was beating her violently with its wings.
+
+"Serpent!" screamed the Pigeon.
+
+"I'm _not_ a serpent!" said Alice indignantly. "Let me alone!"
+
+"Serpent, I say again!" repeated the Pigeon, but in a more subdued tone,
+and added with a kind of a sob, "I've tried every way, and nothing seems
+to suit them!"
+
+"I haven't the least idea what you're talking about," said Alice.
+
+"I've tried the roots of trees, and I've tried banks, and I've tried
+hedges," the Pigeon went on, without attending to her; "but those
+serpents! There's no pleasing them!"
+
+Alice was more and more puzzled, but she thought there was no use in
+saying anything more till the Pigeon had finished.
+
+"As if it wasn't trouble enough hatching the eggs," said the Pigeon;
+"but I must be on the look-out for serpents night and day! Why, I
+haven't had a wink of sleep these three weeks!"
+
+"I'm very sorry you've been annoyed," said Alice, who was beginning to
+see its meaning.
+
+[Illustration]
+
+"And just as I'd taken the highest tree in the wood," continued the
+Pigeon, raising its voice to a shriek, "and just as I was thinking I
+should be free of them at last, they must needs come wriggling down from
+the sky! Ugh, Serpent!"
+
+"But I'm _not_ a serpent, I tell you!" said Alice. "I'm a---- I'm a
+----"
+
+"Well! _What_ are you?" said the Pigeon. "I can see you're trying to
+invent something!"
+
+"I--I'm a little girl," said Alice, rather doubtfully, as she remembered
+the number of changes she had gone through that day.
+
+"A likely story indeed!" said the Pigeon in a tone of the deepest
+contempt. "I've seen a good many little girls in my time, but never
+_one_ with such a neck as that! No, no! You're a serpent; and there's no
+use denying it. I suppose you'll be telling me next that you never
+tasted an egg!"
+
+"I _have_ tasted eggs, certainly," said Alice, who was a very truthful
+child; "but little girls eat eggs quite as much as serpents do, you
+know."
+
+"I don't believe it," said the Pigeon; "but if they do, why then
+they're a kind of serpent, that's all I can say."
+
+This was such a new idea to Alice, that she was quite silent for a
+minute or two, which gave the Pigeon the opportunity of adding, "You're
+looking for eggs, I know _that_ well enough; and what does it matter to
+me whether you're a little girl or a serpent?"
+
+"It matters a good deal to _me_," said Alice hastily; "but I'm not
+looking for eggs, as it happens; and if I was, I shouldn't want _yours_:
+I don't like them raw."
+
+"Well, be off, then!" said the Pigeon in a sulky tone, as it settled
+down again into its nest. Alice crouched down among the trees as well as
+she could, for her neck kept getting entangled among the branches, and
+every now and then she had to stop and untwist it. After a while she
+remembered that she still held the pieces of mushroom in her hands, and
+she set to work very carefully, nibbling first at one and then at the
+other, and growing sometimes taller and sometimes shorter, until she had
+succeeded in bringing herself down to her usual height.
+
+It was so long since she had been anything near the right size, that it
+felt quite strange at first; but she got used to it in a few minutes,
+and began talking to herself, as usual. "Come, there's half my plan done
+now! How puzzling all these changes are! I'm never sure what I'm going
+to be, from one minute to another! However, I've got back to my right
+size: the next thing is, to get into that beautiful garden--how _is_
+that to be done, I wonder?" As she said this, she came suddenly upon an
+open place, with a little house in it about four feet high. "Whoever
+lives there," thought Alice, "it'll never do to come upon them _this_
+size: why, I should frighten them out of their wits!" So she began
+nibbling at the right-hand bit again, and did not venture to go near the
+house till she had brought herself down to nine inches high.
+
+
+
+
+CHAPTER VI
+
+
+[Sidenote: _Pig and Pepper_]
+
+FOR a minute or two she stood looking at the house, and
+wondering what to do next, when suddenly a footman in livery came
+running out of the wood--(she considered him to be a footman because he
+was in livery: otherwise, judging by his face only, she would have
+called him a fish)--and rapped loudly at the door with his knuckles. It
+was opened by another footman in livery, with a round face and large
+eyes like a frog; and both footmen, Alice noticed, had powdered hair
+that curled all over their heads. She felt very curious to know what it
+was all about, and crept a little way out of the wood to listen.
+
+The Fish-Footman began by producing from under his arm a great letter,
+nearly as large as himself, and this he handed over to the other,
+saying, in a solemn tone, "For the Duchess. An invitation from the
+Queen to play croquet." The Frog-Footman repeated, in the same solemn
+tone, only changing the order of the words a little, "From the Queen. An
+invitation for the Duchess to play croquet."
+
+Then they both bowed low, and their curls got entangled together.
+
+Alice laughed so much at this, that she had to run back into the wood
+for fear of their hearing her; and, when she next peeped out, the
+Fish-Footman was gone, and the other was sitting on the ground near the
+door, staring stupidly up into the sky.
+
+Alice went timidly up to the door and knocked.
+
+"There's no use in knocking," said the Footman, "and that for two
+reasons. First, because I'm on the same side of the door as you are;
+secondly, because they're making such a noise inside, no one could
+possibly hear you." And certainly there was a most extraordinary noise
+going on within--a constant howling and sneezing, and every now and then
+a great crash, as if a dish or kettle had been broken to pieces.
+
+"Please, then," said Alice, "how am I to get in?"
+
+"There might be some sense in your knocking," the Footman went on
+without attending to her, "if we had the door between us. For instance,
+if you were _inside_, you might knock, and I could let you out, you
+know." He was looking up into the sky all the time he was speaking, and
+this Alice thought decidedly uncivil. "But perhaps he can't help it,"
+she said to herself: "his eyes are so _very_ nearly at the top of his
+head. But at any rate he might answer questions. How am I to get in?"
+she repeated aloud.
+
+"I shall sit here," the Footman remarked, "till to-morrow----"
+
+At this moment the door of the house opened, and a large plate came
+skimming out, straight at the Footman's head: it just grazed his nose,
+and broke to pieces against one of the trees behind him.
+
+"----or next day, maybe," the Footman continued in the same tone,
+exactly as if nothing had happened.
+
+"How am I to get in?" asked Alice again in a louder tone.
+
+"_Are_ you to get in at all?" said the Footman. "That's the first
+question, you know."
+
+[Illustration]
+
+It was, no doubt: only Alice did not like to be told so. "It's really
+dreadful," she muttered to herself, "the way all the creatures argue.
+It's enough to drive one crazy!"
+
+The Footman seemed to consider this a good opportunity for repeating his
+remark, with variations. "I shall sit here," he said, "on and off, for
+days and days."
+
+"But what am _I_ to do?" said Alice.
+
+"Anything you like," said the Footman, and began whistling.
+
+"Oh, there's no use in talking to him," said Alice desperately: "he's
+perfectly idiotic!" And she opened the door and went in.
+
+The door led right into a large kitchen, which was full of smoke from
+one end to the other: the Duchess was sitting on a three-legged stool in
+the middle, nursing a baby, the cook was leaning over the fire, stirring
+a large cauldron which seemed to be full of soup.
+
+"There's certainly too much pepper in that soup!" Alice said to herself,
+as well as she could for sneezing.
+
+There was certainly too much of it in the air. Even the Duchess sneezed
+occasionally; and the baby was sneezing and howling alternately without
+a moment's pause. The only things in the kitchen that did not sneeze,
+were the cook, and a large cat which was sitting on the hearth and
+grinning from ear to ear.
+
+"Please would you tell me," said Alice a little timidly, for she was not
+quite sure whether it was good manners for her to speak first, "why your
+cat grins like that?"
+
+"It's a Cheshire cat," said the Duchess, "and that's why. Pig!"
+
+She said the last word with such sudden violence that Alice quite
+jumped; but she saw in another moment that it was addressed to the baby,
+and not to her, so she took courage, and went on again:
+
+"I didn't know that Cheshire cats always grinned; in fact, I didn't know
+that cats _could_ grin."
+
+"They all can," said the Duchess; "and most of 'em do."
+
+"I don't know of any that do," Alice said very politely, feeling quite
+pleased to have got into a conversation.
+
+"You don't know much," said the Duchess; "and that's a fact."
+
+Alice did not at all like the tone of this remark, and thought it would
+be as well to introduce some other subject of conversation. While she
+was trying to fix on one, the cook took the cauldron of soup off the
+fire, and at once set to work throwing everything within her reach at
+the Duchess and the baby--the fire-irons came first; then followed a
+shower of saucepans, plates, and dishes. The Duchess took no notice of
+them even when they hit her; and the baby was howling so much already,
+that it was quite impossible to say whether the blows hurt it or not.
+
+"Oh, _please_ mind what you're doing!" cried Alice, jumping up and down
+in an agony of terror. "Oh, there goes his _precious_ nose"; as an
+unusually large saucepan flew close by it, and very nearly carried it
+off.
+
+"If everybody minded their own business," the Duchess said in a hoarse
+growl, "the world would go round a deal faster than it does."
+
+[Illustration: _An unusually large saucepan flew close by it, and very
+nearly carried it off_]
+
+"Which would _not_ be an advantage," said Alice, who felt very glad to
+get an opportunity of showing off a little of her knowledge. "Just think
+what work it would make with the day and night! You see the earth
+takes twenty-four hours to turn round on its axis----"
+
+"Talking of axes," said the Duchess, "chop off her head."
+
+Alice glanced rather anxiously at the cook, to see if she meant to take
+the hint; but the cook was busily engaged in stirring the soup, and did
+not seem to be listening, so she ventured to go on again: "Twenty-four
+hours, I _think_; or is it twelve? I----"
+
+"Oh, don't bother _me_," said the Duchess; "I never could abide
+figures!" And with that she began nursing her child again, singing a
+sort of lullaby to it as she did so, and giving it a violent shake at
+the end of every line:
+
+ "Speak roughly to your little boy,
+ And beat him when he sneezes:
+ He only does it to annoy,
+ Because he knows it teases."
+
+CHORUS
+
+ (In which the cook and the baby joined):
+ "Wow! wow! wow!"
+
+While the Duchess sang the second verse of the song, she kept tossing
+the baby violently up and down, and the poor little thing howled so,
+that Alice could hardly hear the words:
+
+ "I speak severely to my boy,
+ I beat him when he sneezes;
+ For he can thoroughly enjoy
+ The pepper when he pleases!"
+
+ CHORUS.
+
+ "Wow! wow! wow!"
+
+"Here! you may nurse it a bit if you like!" the Duchess said to Alice,
+flinging the baby at her as she spoke. "I must go and get ready to play
+croquet with the Queen," and she hurried out of the room. The cook threw
+a frying-pan after her as she went out, but it just missed her.
+
+Alice caught the baby with some difficulty, as it was a queer-shaped
+little creature, and held out its arms and legs in all directions, "just
+like a star-fish," thought Alice. The poor little thing was snorting
+like a steam-engine when she caught it, and kept doubling itself up and
+straightening itself out again, so that altogether, for the first minute
+or two, it was as much as she could do to hold it.
+
+As soon as she had made out the proper way of nursing it, (which was to
+twist it up into a knot, and then keep tight hold of its right ear and
+left foot, so as to prevent its undoing itself,) she carried it out into
+the open air. "If I don't take this child away with me," thought Alice,
+"they're sure to kill it in a day or two: wouldn't it be murder to leave
+it behind?" She said the last words out loud, and the little thing
+grunted in reply (it had left off sneezing by this time). "Don't grunt,"
+said Alice; "that's not at all a proper way of expressing yourself."
+
+The baby grunted again, and Alice looked very anxiously into its face to
+see what was the matter with it. There could be no doubt that it had a
+_very_ turn-up nose, much more like a snout than a real nose; also its
+eyes were getting extremely small for a baby: altogether Alice did not
+like the look of the thing at all. "But perhaps it was only sobbing,"
+she thought, and looked into its eyes again, to see if there were any
+tears.
+
+No, there were no tears. "If you're going to turn into a pig, my dear,"
+said Alice, seriously, "I'll have nothing more to do with you. Mind
+now!" The poor little thing sobbed again (or grunted, it was impossible
+to say which), and they went on for some while in silence.
+
+Alice was just beginning to think to herself, "Now, what am I to do with
+this creature when I get it home?" when it grunted again, so violently,
+that she looked down into its face in some alarm. This time there could
+be _no_ mistake about it: it was neither more nor less than a pig, and
+she felt that it would be quite absurd for her to carry it any further.
+
+So she set the little creature down, and felt quite relieved to see it
+trot quietly away into the wood. "If it had grown up," she said to
+herself, "it would have made a dreadfully ugly child: but it makes
+rather a handsome pig, I think." And she began thinking over other
+children she knew, who might do very well as pigs, and was just saying
+to herself, "if one only knew the right way to change them----" when she
+was a little startled by seeing the Cheshire Cat sitting on a bough of a
+tree a few yards off.
+
+[Illustration: _It grunted again so violently that she looked down into
+its face in some alarm_]
+
+The Cat only grinned when it saw Alice. It looked good-natured, she
+thought: still it had _very_ long claws and a great many teeth, so she
+felt that it ought to be treated with respect.
+
+[Illustration]
+
+"Cheshire Puss," she began, rather timidly, as she did not at all know
+whether it would like the name: however, it only grinned a little wider.
+"Come, it's pleased so far," thought Alice, and she went on. "Would you
+tell me, please, which way I ought to go from here?"
+
+"That depends a good deal on where you want to get to," said the Cat.
+
+"I don't much care where----" said Alice.
+
+"Then it doesn't matter which way you go," said the Cat.
+
+"---- so long as I get _somewhere_," Alice added as an explanation.
+
+"Oh, you're sure to do that," said the Cat, "if you only walk long
+enough."
+
+Alice felt that this could not be denied, so she tried another question.
+"What sort of people live about here?"
+
+"In _that_ direction," the Cat said, waving its right paw round, "lives
+a Hatter: and in _that_ direction," waving the other paw, "lives a March
+Hare. Visit either you like: they're both mad."
+
+"But I don't want to go among mad people," Alice remarked.
+
+"Oh, you ca'n't help that," said the Cat: "we're all mad here. I'm mad.
+You're mad."
+
+"How do you know I'm mad?" said Alice.
+
+"You must be," said the Cat, "or you wouldn't have come here."
+
+Alice didn't think that proved it at all; however, she went on. "And how
+do you know that you're mad?"
+
+"To begin with," said the Cat, "a dog's not mad. You grant that?"
+
+"I suppose so," said Alice.
+
+"Well, then," the Cat went on, "you see a dog growls when it's angry,
+and wags its tail when it's pleased. Now _I_ growl when I'm pleased, and
+wag my tail when I'm angry. Therefore I'm mad."
+
+"_I_ call it purring, not growling," said Alice.
+
+"Call it what you like," said the Cat. "Do you play croquet with the
+Queen to-day?"
+
+"I should like it very much," said Alice, "but I haven't been invited
+yet."
+
+"You'll see me there," said the Cat and vanished.
+
+Alice was not much surprised at this, she was getting so used to queer
+things happening. While she was looking at the place where it had been,
+it suddenly appeared again.
+
+"By-the-bye, what became of the baby?" said the Cat. "I'd nearly
+forgotten to ask."
+
+"It turned into a pig," Alice quietly said, just as if it had come back
+in a natural way.
+
+"I thought it would," said the Cat, and vanished again.
+
+Alice waited a little, half expecting to see it again, but it did not
+appear, and after a minute or two she walked on in the direction in
+which the March Hare was said to live. "I've seen hatters before," she
+said to herself; "the March Hare will be much the most interesting, and
+perhaps as this is May, it won't be raving mad--at least not so mad as
+it was in March." As she said this, she looked up, and there was the Cat
+again, sitting on the branch of a tree.
+
+"Did you say pig, or fig?" said the Cat.
+
+"I said pig," replied Alice; "and I wish you wouldn't keep appearing and
+vanishing so suddenly: you make one quite giddy."
+
+"All right," said the Cat; and this time it vanished quite slowly,
+beginning with the end of the tail, and ending with the grin, which
+remained some time after the rest of it had gone.
+
+"Well! I've often seen a cat without a grin," thought Alice; "but a grin
+without a cat! It's the most curious thing I ever saw in all my life."
+
+[Illustration]
+
+She had not gone much farther before she came in sight of the house of
+the March Hare: she thought it must be the right house, because the
+chimneys were shaped like ears and the roof was thatched with fur. It
+was so large a house, that she did not like to go nearer till she had
+nibbled some more of the left-hand bit of mushroom, and raised herself,
+to about two feet high: even then she walked up towards it rather
+timidly, saying to herself, "Suppose it should be raving mad after all!
+I almost wish I'd gone to see the Hatter instead!"
+
+
+
+
+CHAPTER VII
+
+
+[Sidenote: _A Mad Tea-party_]
+
+THERE was a table set out under a tree in front of the
+house, and the March Hare and the Hatter were having tea at it: a
+Dormouse was sitting between them, fast asleep, and the other two were
+using it as a cushion resting their elbows on it, and talking over its
+head. "Very uncomfortable for the Dormouse," thought Alice; "only as
+it's asleep, suppose it doesn't mind."
+
+The table was a large one, but the three were all crowded together at
+one corner of it. "No room! No room!" they cried out when they saw Alice
+coming. "There's _plenty_ of room!" said Alice indignantly, and she sat
+down in a large arm-chair at one end of the table.
+
+"Have some wine," the March Hare said in an encouraging tone.
+
+Alice looked all round the table, but there was nothing on it but tea.
+"I don't see any wine," she remarked.
+
+"There isn't any," said the March Hare.
+
+"Then it wasn't very civil of you to offer it," said Alice angrily.
+
+"It wasn't very civil of you to sit down without being invited," said
+the March Hare.
+
+"I didn't know it was _your_ table," said Alice; "it's laid for a great
+many more than three."
+
+"Your hair wants cutting," said the Hatter. He had been looking at Alice
+for some time with great curiosity, and this was his first speech.
+
+"You should learn not to make personal remarks," Alice said with some
+severity; "it's very rude."
+
+The Hatter opened his eyes very wide on hearing this; but all he _said_
+was "Why is a raven like a writing-desk?"
+
+"Come, we shall have some fun now!" thought Alice. "I'm glad they've
+begun asking riddles.--I believe I can guess that," she added aloud.
+
+"Do you mean that you think you can find out the answer to it?" said
+the March Hare.
+
+"Exactly so," said Alice.
+
+"Then you should say what you mean," the March Hare went on.
+
+"I do," Alice hastily replied; "at least--at least I mean what I
+say--that's the same thing, you know."
+
+"Not the same thing a bit!" said the Hatter. "Why, you might just as
+well say that 'I see what I eat' is the same thing as 'I eat what I
+see'!"
+
+"You might just as well say," added the March Hare, "that 'I like what I
+get' is the same thing as 'I get what I like'!"
+
+"You might just as well say," added the Dormouse, which seemed to be
+talking in his sleep, "that 'I breathe when I sleep' is the same thing
+as 'I sleep when I breathe'!"
+
+"It _is_ the same thing with you," said the Hatter; and here the
+conversation dropped, and the party sat silent for a minute, while Alice
+thought over all she could remember about ravens and writing-desks,
+which wasn't much.
+
+[Illustration: _A Mad Tea Party_]
+
+The Hatter was the first to break the silence. "What day of the month
+is it?" he said, turning to Alice: he had taken his watch out of his
+pocket, and was looking at it uneasily, shaking it every now and then,
+and holding it to his ear.
+
+Alice considered a little, and then said "The fourth."
+
+"Two days wrong!" sighed the Hatter. "I told you butter would not suit
+the works!" he added, looking angrily at the March Hare.
+
+"It was the _best_ butter," the March Hare meekly replied.
+
+"Yes, but some crumbs must have got in as well," the Hatter grumbled:
+"you shouldn't have put it in with the bread-knife."
+
+The March Hare took the watch and looked at it gloomily: then he dipped
+it into his cup of tea, and looked at it again: but he could think of
+nothing better to say than his first remark, "It was the _best_ butter,
+you know."
+
+Alice had been looking over his shoulder with some curiosity. "What a
+funny watch!" she remarked. "It tells the day of the month, and doesn't
+tell what o'clock it is!"
+
+"Why should it?" muttered the Hatter. "Does _your_ watch tell you what
+year it is?"
+
+"Of course not," Alice replied very readily: "but that's because it
+stays the same year for such a long time together."
+
+"Which is just the case with _mine_," said the Hatter.
+
+Alice felt dreadfully puzzled. The Hatter's remark seemed to have no
+meaning in it, and yet it was certainly English. "I don't quite
+understand," she said, as politely as she could.
+
+"The Dormouse is asleep again," said the Hatter, and he poured a little
+hot tea upon its nose.
+
+The Dormouse shook its head impatiently, and said, without opening its
+eyes, "Of course, of course; just what I was going to remark myself."
+
+"Have you guessed the riddle yet?" the Hatter said, turning to Alice
+again.
+
+"No, I give it up," Alice replied: "what's the answer?"
+
+"I haven't the slightest idea," said the Hatter.
+
+"Nor I," said the March Hare.
+
+Alice sighed wearily. "I think you might do something better with the
+time," she said, "than wasting it asking riddles with no answers."
+
+"If you knew Time as well as I do," said the Hatter, "you wouldn't talk
+about wasting _it_. It's _him_."
+
+"I don't know what you mean," said Alice.
+
+"Of course you don't!" the Hatter said, tossing his head contemptuously.
+"I daresay you never spoke to Time!"
+
+"Perhaps not," Alice cautiously replied: "but I know I have to beat time
+when I learn music."
+
+"Ah! that accounts for it," said the Hatter. "He won't stand beating.
+Now, if you only kept on good terms with him, he'd do almost anything
+you liked with the clock. For instance, suppose it were nine o'clock in
+the morning, just time to begin lessons: you'd only have to whisper a
+hint to Time, and round goes the clock in a twinkling! Half-past one,
+time for dinner!"
+
+("I only wish it was," the March Hare said to itself in a whisper.)
+
+"That would be grand, certainly," said Alice thoughtfully: "but then--I
+shouldn't be hungry for it, you know."
+
+"Not at first, perhaps," said the Hatter: "but you could keep it to
+half-past one as long as you liked."
+
+"Is that the way _you_ manage?" Alice asked.
+
+The Hatter shook his head mournfully. "Not I!" he replied. "We
+quarrelled last March----just before _he_ went mad, you know----"
+(pointing with his teaspoon to the March Hare), "it was at the great
+concert given by the Queen of Hearts, and I had to sing
+
+ 'Twinkle, twinkle, little bat!
+ How I wonder what you're at!'
+
+You know that song, perhaps?"
+
+"I've heard something like it," said Alice.
+
+"It goes on, you know," the Hatter continued, "in this way:--
+
+ 'Up above the world you fly,
+ Like a tea-tray in the sky.
+ Twinkle, twinkle----'"
+
+Here the Dormouse shook itself, and began singing in its sleep
+"_Twinkle, twinkle, twinkle, twinkle_----" and went on so long that they
+had to pinch it to make it stop.
+
+"Well, I'd hardly finished the first verse," said the Hatter, "when the
+Queen jumped up and bawled out 'He's murdering the time! Off with his
+head!'"
+
+"How dreadfully savage!" exclaimed Alice.
+
+"And ever since that," the Hatter went on in a mournful tone, "he won't
+do a thing I ask! It's always six o'clock now."
+
+A bright idea came into Alice's head. "Is that the reason so many
+tea-things are put out here?" she asked.
+
+"Yes, that's it," said the Hatter with a sigh: "it's always tea-time,
+and we've no time to wash the things between whiles."
+
+"Then you keep moving round, I suppose?" said Alice.
+
+"Exactly so," said the Hatter: "as the things get used up."
+
+"But what happens when you come to the beginning again?" Alice ventured
+to ask.
+
+"Suppose we change the subject," the March Hare interrupted, yawning.
+"I'm getting tired of this. I vote the young lady tells us a story."
+
+"I'm afraid I don't know one," said Alice, rather alarmed at the
+proposal.
+
+"Then the Dormouse shall!" they both cried. "Wake up, Dormouse!" And
+they pinched it on both sides at once.
+
+The Dormouse slowly opened his eyes. "I wasn't asleep," he said in a
+hoarse, feeble voice: "I heard every word you fellows were saying."
+
+"Tell us a story!" said the March Hare.
+
+"Yes, please do!" pleaded Alice.
+
+"And be quick about it," added the Hatter, "or you'll be asleep again
+before it's done."
+
+"Once upon a time there were three little sisters," the Dormouse began
+in a great hurry; "and their names were Elsie, Lacie, and Tillie; and
+they lived at the bottom of a well----"
+
+"What did they live on?" said Alice, who always took a great interest in
+questions of eating and drinking.
+
+"They lived on treacle," said the Dormouse, after thinking a minute or
+two.
+
+"They couldn't have done that, you know," Alice gently remarked; "they'd
+have been ill."
+
+"So they were," said the Dormouse; "_very_ ill."
+
+Alice tried a little to fancy to herself what such an extraordinary way
+of living would be like, but it puzzled her too much, so she went on:
+"But why did they live at the bottom of a well?"
+
+"Take some more tea," the March Hare said to Alice, very earnestly.
+
+"I've had nothing yet," Alice replied in an offended tone, "so I can't
+take more."
+
+"You mean you can't take _less_," said the Hatter; "it's very easy to
+take _more_ than nothing."
+
+"Nobody asked _your_ opinion," said Alice.
+
+"Who's making personal remarks now?" the Hatter asked triumphantly.
+
+Alice did not quite know what to say to this: so she helped herself to
+some tea and bread-and-butter, and then turned to the Dormouse, and
+repeated her question. "Why did they live at the bottom of a well?"
+
+The Dormouse again took a minute or two to think about it, and then
+said, "It was a treacle-well."
+
+"There's no such thing!" Alice was beginning very angrily, but the
+Hatter and the March Hare went "Sh! sh!" and the Dormouse sulkily
+remarked: "If you can't be civil, you'd better finish the story for
+yourself."
+
+"No, please go on!" Alice said very humbly. "I won't interrupt you
+again. I dare say there may be _one_."
+
+"One, indeed!" said the Dormouse indignantly. However, he consented to
+go on. "And so these three little sisters--they were learning to draw,
+you know----"
+
+"What did they draw?" said Alice, quite forgetting her promise.
+
+"Treacle," said the Dormouse, without considering at all this time.
+
+"I want a clean cup," interrupted the Hatter: "let's all move one place
+on."
+
+He moved as he spoke, and the Dormouse followed him: the March Hare
+moved into the Dormouse's place, and Alice rather unwillingly took the
+place of the March Hare. The Hatter was the only one who got any
+advantage from the change: and Alice was a good deal worse off than
+before, as the March Hare had just upset the milk-jug into his plate.
+
+Alice did not wish to offend the Dormouse again, so she began very
+cautiously: "But I don't understand. Where did they draw the treacle
+from?"
+
+"You can draw water out of a water-well," said the Hatter; "so I should
+think you could draw treacle out of a treacle-well--eh, stupid!"
+
+"But they were _in_ the well," Alice said to the Dormouse, not choosing
+to notice this last remark.
+
+"Of course they were," said the Dormouse; "----well in."
+
+This answer so confused poor Alice that she let the Dormouse go on for
+some time without interrupting it.
+
+"They were learning to draw," the Dormouse went on, yawning and rubbing
+its eyes, for it was getting very sleepy; "and they drew all manner of
+things--everything that begins with an M----"
+
+"Why with an M?" said Alice.
+
+"Why not?" said the March Hare.
+
+Alice was silent.
+
+The Dormouse had closed its eyes by this time, and was going off into a
+dose; but, on being pinched by the Hatter, it woke up again with a
+little shriek, and went on: "----that begins with an M, such as
+mouse-traps, and the moon, and memory, and muchness--you know you say
+things are 'much of a muchness'--did you ever see such a thing as a
+drawing of a muchness?"
+
+"Really, now you ask me," said Alice, very much confused, "I don't
+think----"
+
+"Then you shouldn't talk," said the Hatter.
+
+This piece of rudeness was more than Alice could bear: she got up in
+great disgust and walked off; the Dormouse fell asleep instantly, and
+neither of the others took the least notice of her going, though she
+looked back once or twice, half hoping that they would call after her:
+the last time she saw them, they were trying to put the Dormouse into
+the teapot.
+
+"At any rate I'll never go _there_ again!" said Alice as she picked her
+way through the wood. "It's the stupidest tea-party I ever was at in all
+my life!"
+
+Just as she said this, she noticed that one of the trees had a door
+leading right into it. "That's very curious!" she thought. "But
+everything's curious to-day. I think I may as well go in at once." And
+in she went.
+
+Once more she found herself in the long hall, and close to the little
+glass table. "Now I'll manage better this time," she said to herself,
+and began by taking the little golden key, and unlocking the door that
+led into the garden. Then she set to work nibbling at the mushroom (she
+had kept a piece of it in her pocket) till she was about a foot high:
+then she walked down the little passage: and _then_--she found herself
+at last in the beautiful garden, among the bright flower-beds and the
+cool fountains.
+
+
+
+
+CHAPTER VIII
+
+
+[Sidenote: _The Queen's Croquet-Ground_]
+
+A LARGE rose-tree stood near the entrance of the garden:
+the roses growing on it were white, but there were three gardeners at
+it, busily painting them red. Alice thought this a very curious thing,
+and she went nearer to watch them, and just as she came up to them she
+heard one of them say "Look out now, Five! Don't go splashing paint over
+me like that!"
+
+"I couldn't help it," said Five, in a sulky tone. "Seven jogged my
+elbow."
+
+On which Seven looked up and said, "That's right, Five! Always lay the
+blame on others!"
+
+"_You'd_ better not talk!" said Five. "I heard the Queen say only
+yesterday you deserved to be beheaded!"
+
+"What for?" said the one who had first spoken.
+
+"That's none of _your_ business, Two!" said Seven.
+
+"Yes, it _is_ his business!" said Five. "And I'll tell him--it was for
+bringing the cook tulip-roots instead of onions."
+
+Seven flung down his brush, and had just begun "Well, of all the unjust
+things----" when his eye chanced to fall upon Alice, as she stood
+watching them, and he checked himself suddenly: the others looked round
+also, and all of them bowed low.
+
+"Would you tell me," said Alice, a little timidly, "why you are painting
+those roses?"
+
+Five and Seven said nothing, but looked at Two. Two began in a low
+voice, "Why, the fact is, you see, Miss, this here ought to have been a
+_red_ rose-tree, and we put a white one in by mistake; and if the Queen
+was to find it out, we should all have our heads cut off, you know. So
+you see, Miss, we're doing our best, afore she comes, to----" At this
+moment, Five, who had been anxiously looking across the garden, called
+out "The Queen! The Queen!" and the three gardeners instantly threw
+themselves flat upon their faces. There was a sound of many footsteps,
+and Alice looked round, eager to see the Queen.
+
+First came ten soldiers carrying clubs; these were all shaped like the
+three gardeners, oblong and flat, with their hands and feet at the
+corners: next the ten courtiers; these were ornamented all over with
+diamonds, and walked two and two, as the soldiers did. After these came
+the royal children; there were ten of them, and the little dears came
+jumping merrily along hand in hand, in couples; they were all ornamented
+with hearts. Next came the guests, mostly Kings and Queens, and among
+them Alice recognised the White Rabbit: it was talking in a hurried,
+nervous manner, smiling at everything that was said, and went by without
+noticing her. Then followed the Knave of Hearts, carrying the King's
+crown on a crimson velvet cushion; and last of all this grand
+procession, came THE KING AND QUEEN OF HEARTS.
+
+Alice was rather doubtful whether she ought not to lie down on her face
+like the three gardeners, but she could not remember ever having heard
+of such a rule at processions; "and besides, what would be the use of a
+procession," thought she, "if people had to lie down upon their faces,
+so that they couldn't see it?" So she stood still where she was, and
+waited.
+
+When the procession came opposite to Alice, they all stopped and looked
+at her, and the Queen said severely, "Who is this?" She said it to the
+Knave of Hearts, who only bowed and smiled in reply.
+
+"Idiot!" said the Queen, tossing her head impatiently; and turning to
+Alice, she went on, "What's your name, child?"
+
+"My name is Alice, so please your Majesty," said Alice very politely;
+but she added, to herself, "Why, they're only a pack of cards, after
+all. I needn't be afraid of them!"
+
+"And who are _these_?" said the Queen, pointing to the three gardeners
+who were lying round the rose-tree; for, you see, as they were lying on
+their faces, and the pattern on their backs was the same as the rest of
+the pack, she could not tell whether they were gardeners, or soldiers,
+or courtiers, or three of her own children.
+
+"How should _I_ know?" said Alice, surprised at her own courage. "It's
+no business of _mine_."
+
+The Queen turned crimson with fury, and, after glaring at her for a
+moment like a wild beast, screamed "Off with her head! Off----"
+
+"Nonsense!" said Alice, very loudly and decidedly, and the Queen was
+silent.
+
+The King laid his hand upon her arm, and timidly said "Consider my dear:
+she is only a child!"
+
+The Queen turned angrily away from him, and said to the Knave "Turn them
+over!"
+
+The Knave did so, very carefully, with one foot.
+
+"Get up!" said the Queen, in a shrill, loud voice, and the three
+gardeners instantly jumped up, and began bowing to the King, the Queen,
+the royal children, and everybody else.
+
+"Leave off that!" screamed the Queen. "You make me giddy." And then,
+turning to the rose-tree, she went on, "What _have_ you been doing
+here?"
+
+"May it please your Majesty," said Two, in a very humble tone, going
+down on one knee as he spoke, "we were trying----"
+
+[Illustration: _The Queen turned angrily away from him and said to the
+Knave, "Turn them over"_]
+
+"_I_ see!" said the Queen, who had meanwhile been examining the roses.
+"Off with their heads!" and the procession moved on, three of the
+soldiers remaining behind to execute the unfortunate gardeners, who ran
+to Alice for protection.
+
+"You shan't be beheaded!" said Alice, and she put them into a large
+flower-pot that stood near. The three soldiers wandered about for a
+minute or two, looking for them, and then quietly marched off after the
+others.
+
+"Are their heads off?" shouted the Queen.
+
+"Their heads are gone, if it please your Majesty!" the soldiers shouted
+in reply.
+
+"That's right!" shouted the Queen. "Can you play croquet?"
+
+The soldiers were silent, and looked at Alice, as the question was
+evidently meant for her.
+
+"Yes!" shouted Alice.
+
+"Come on, then!" roared the Queen, and Alice joined the procession,
+wondering very much what would happen next.
+
+"It's--it's a very fine day!" said a timid voice at her side. She was
+walking by the White Rabbit, who was peeping anxiously into her face.
+
+"Very," said Alice: "----where's the Duchess?"
+
+"Hush! Hush!" said the Rabbit in a low hurried tone. He looked anxiously
+over his shoulder as he spoke, and then raised himself upon tiptoe, put
+his mouth close to her ear, and whispered "She's under sentence of
+execution."
+
+"What for?" said Alice.
+
+"Did you say 'What a pity!'?" the Rabbit asked.
+
+"No, I didn't," said Alice: "I don't think it's at all a pity. I said
+'What for?'"
+
+"She boxed the Queen's ears--" the Rabbit began. Alice gave a little
+scream of laughter. "Oh, hush!" the Rabbit whispered in a frightened
+tone. "The Queen will hear you! You see she came rather late, and the
+Queen said----"
+
+"Get to your places!" shouted the Queen in a voice of thunder, and
+people began running about in all directions, tumbling up against each
+other; however, they got settled down in a minute or two, and the game
+began. Alice thought she had never seen such a curious croquet-ground in
+all her life; it was all ridges and furrows; the balls were live
+hedgehogs, the mallets live flamingoes, and the soldiers had to double
+themselves up and to stand upon their hands and feet, to make the
+arches.
+
+[Illustration]
+
+The chief difficulty Alice found at first was in managing her flamingo;
+she succeeded in getting its body tucked away, comfortably enough, under
+her arm, with its legs hanging down, but generally, just as she had got
+its neck nicely straightened out, and was going to give the hedgehog a
+blow with its head, it _would_ twist itself round and look up in her
+face, with such a puzzled expression that she could not help bursting
+out laughing: and when she had got its head down, and was going to
+begin again, it was very provoking to find that the hedgehog had
+unrolled itself and was in the act of crawling away: besides all this,
+there was generally a ridge or a furrow in the way wherever she wanted
+to send the hedgehog to, and, as the doubled-up soldiers were always
+getting up and walking off to other parts of the ground, Alice soon came
+to the conclusion that it was a very difficult game indeed.
+
+The players all played at once without waiting for turns, quarrelling
+all the while, and fighting for the hedgehogs; and in a very short time
+the Queen was in a furious passion, and went stamping about, and
+shouting "Off with his head!" or "Off with her head!" about once in a
+minute.
+
+Alice began to feel very uneasy: to be sure she had not as yet had any
+dispute with the Queen, but she knew that it might happen any minute,
+"and then," thought she, "what would become of me? They're dreadfully
+fond of beheading people here: the great wonder is that there's any one
+left alive!"
+
+She was looking about for some way of escape, and wondering whether she
+could get away without being seen, when she noticed a curious
+appearance in the air: it puzzled her very much at first, but, after
+watching it a minute or two, she made it out to be a grin, and she said
+to herself "It's the Cheshire Cat: now I shall have somebody to talk
+to."
+
+"How are you getting on?" said the Cat, as soon as there was mouth
+enough for it to speak with.
+
+Alice waited till the eyes appeared, and then nodded. "It's no use
+speaking to it," she thought, "till its ears have come, or at least one
+of them." In another minute the whole head appeared, and then Alice put
+down her flamingo, and began an account of the game, feeling very glad
+she had some one to listen to her. The Cat seemed to think that there
+was enough of it now in sight, and no more of it appeared.
+
+"I don't think they play at all fairly," Alice began, in rather a
+complaining tone, "and they all quarrel so dreadfully one can't hear
+oneself speak--and they don't seem to have any rules in particular; at
+least, if there are, nobody attends to them--and you've no idea how
+confusing it is all the things being alive; for instance, there's the
+arch I've got to go through next walking about at the other end of the
+ground--and I should have croqueted the Queen's hedgehog just now, only
+it ran away when it saw mine coming!"
+
+[Illustration]
+
+"How do you like the Queen?" said the Cat in a low voice.
+
+"Not at all," said Alice: "she's so extremely----" Just then she noticed
+that the Queen was close behind her listening: so she went on,
+"----likely to win, that it's hardly worth while finishing the game."
+
+The Queen smiled and passed on.
+
+"Who _are_ you talking to?" said the King, coming up to Alice, and
+looking at the Cat's head with great curiosity.
+
+"It's a friend of mine--a Cheshire Cat," said Alice: "allow me to
+introduce it."
+
+"I don't like the look of it at all," said the King: "however, it may
+kiss my hand if it likes."
+
+"I'd rather not," the Cat remarked.
+
+"Don't be impertinent," said the King, "and don't look at me like that!"
+He got behind Alice as he spoke.
+
+"A cat may look at a king," said Alice. "I've read that in some book,
+but I don't remember where."
+
+"Well, it must be removed," said the King very decidedly, and he called
+to the Queen, who was passing at the moment, "My dear! I wish you would
+have this cat removed!"
+
+The Queen had only one way of settling all difficulties, great or small.
+"Off with his head!" she said, without even looking round.
+
+"I'll fetch the executioner myself," said the King eagerly, and he
+hurried off.
+
+Alice thought she might as well go back and see how the game was going
+on, as she heard the Queen's voice in the distance, screaming with
+passion. She had already heard her sentence three of the players to be
+executed for having missed their turns, and she did not like the look of
+things at all, as the game was in such confusion that she never knew
+whether it was her turn or not. So she went in search of her hedgehog.
+
+The hedgehog was engaged in a fight with another hedgehog, which seemed
+to Alice an excellent opportunity for croqueting one of them with the
+other: the only difficulty was, that her flamingo was gone across to the
+other side of the garden, where Alice could see it trying in a helpless
+sort of way to fly up into one of the trees.
+
+By the time she had caught the flamingo and brought it back, the fight
+was over, and both the hedgehogs were out of sight: "but it doesn't
+matter much," thought Alice, "as all the arches are gone from this side
+of the ground." So she tucked it under her arm, that it might not escape
+again, and went back for a little more conversation with her friend.
+
+When she got back to the Cheshire Cat, she was surprised to find quite a
+large crowd collected round it: there was a dispute going on between the
+executioner, the King, and the Queen, who were all talking at once,
+while all the rest were quite silent, and looked very uncomfortable.
+
+The moment Alice appeared, she was appealed to by all three to settle
+the question, and they repeated their arguments to her, though, as they
+all spoke at once, she found it very hard indeed to make out exactly
+what they said.
+
+[Illustration]
+
+The executioner's argument was, that you couldn't cut off a head unless
+there was a body to cut it off from: that he had never had to do such a
+thing before, and he wasn't going to begin at _his_ time of life.
+
+The King's argument was, that anything that had a head could be
+beheaded, and that you weren't to talk nonsense.
+
+The Queen's argument was, that if something wasn't done about it in less
+than no time, she'd have everybody executed all round. (It was this last
+remark that had made the whole party look so grave and anxious.)
+
+Alice could think of nothing else to say but "It belongs to the Duchess:
+you'd better ask _her_ about it."
+
+"She's in prison," the Queen said to the executioner; "fetch her here."
+And the executioner went off like an arrow.
+
+The Cat's head began fading away the moment he was gone, and by the time
+he had come back with the Duchess, it had entirely disappeared; so the
+King and the executioner ran wildly up and down looking for it, while
+the rest of the party went back to the game.
+
+
+
+
+CHAPTER IX
+
+
+[Sidenote: _The Mock Turtle's Story_]
+
+"YOU can't think how glad I am to see you again, you
+dear old thing!" said the Duchess, as she tucked her arm affectionately
+into Alice's, and they walked off together.
+
+Alice was very glad to find her in such a pleasant temper, and thought
+to herself that perhaps it was only the pepper that had made her so
+savage when they met in the kitchen.
+
+"When _I'm_ a Duchess," she said to herself (not in a very hopeful tone
+though), "I won't have any pepper in my kitchen _at all_. Soup does very
+well without--Maybe it's always pepper that makes people hot-tempered,"
+she went on, very much pleased at having found out a new kind of rule,
+"and vinegar that makes them sour--and camomile that makes them
+bitter--and--barley-sugar and such things that make children
+sweet-tempered. I only wish people knew _that_: then they wouldn't be
+so stingy about it, you know----"
+
+She had quite forgotten the Duchess by this time, and was a little
+startled when she heard her voice close to her ear. "You're thinking
+about something, my dear, and that makes you forget to talk. I can't
+tell you just now what the moral of that is, but I shall remember it in
+a bit."
+
+"Perhaps it hasn't one," Alice ventured to remark.
+
+"Tut, tut, child!" said the Duchess. "Every thing's got a moral, if only
+you can find it." And she squeezed herself up closer to Alice's side as
+she spoke.
+
+Alice did not much like her keeping so close to her: first, because the
+Duchess was _very_ ugly; and secondly, because she was exactly the right
+height to rest her chin on Alice's shoulder, and it was an uncomfortably
+sharp chin. However, she did not like to be rude, so she bore it as well
+as she could. "The game's going on rather better now," she said, by way
+of keeping up the conversation a little.
+
+"'Tis so," said the Duchess: "and the moral of that is--'Oh, 'tis love,
+'tis love, that makes the world go round!'"
+
+"Somebody said," Alice whispered, "that it's done by everybody minding
+their own business!"
+
+"Ah, well! It means much the same thing," said the Duchess, digging her
+sharp little chin into Alice's shoulder as she added, "and the moral of
+_that_ is--'Take care of the sense, and the sounds will take care of
+themselves.'"
+
+"How fond she is of finding morals in things!" Alice thought to herself.
+
+"I dare say you're wondering why I don't put my arm round your waist,"
+the Duchess said after a pause: "the reason is, that I'm doubtful about
+the temper of your flamingo. Shall I try the experiment?"
+
+"He might bite," Alice cautiously replied, not feeling at all anxious to
+have the experiment tried.
+
+"Very true," said the Duchess: "flamingoes and mustard both bite. And
+the moral of that is--'Birds of a feather flock together.'"
+
+"Only mustard isn't a bird," Alice remarked.
+
+"Right, as usual," said the Duchess: "what a clear way you have of
+putting things!"
+
+"It's a mineral, I _think_," said Alice.
+
+"Of course it is," said the Duchess, who seemed ready to agree to
+everything that Alice said: "there's a large mustard-mine near here. And
+the moral of that is--'The more there is of mine, the less there is of
+yours.'"
+
+"Oh, I know!" exclaimed Alice, who had not attended to this last remark.
+"It's a vegetable. It doesn't look like one, but it is."
+
+"I quite agree with you," said the Duchess; "and the moral of that
+is--'Be what you would seem to be'--or if you'd like it put more
+simply--'Never imagine yourself not to be otherwise than what it might
+appear to others that what you were or might have been was not otherwise
+than what you had been would have appeared to them to be otherwise.'"
+
+"I think I should understand that better," Alice said very politely, "if
+I had it written down: but I can't quite follow it as you say it."
+
+"That's nothing to what I could say if I chose," the Duchess replied, in
+a pleased tone.
+
+"Pray don't trouble yourself to say it any longer than that," said
+Alice.
+
+"Oh, don't talk about trouble!" said the Duchess. "I make you a present
+of everything I've said as yet."
+
+"A cheap sort of present!" thought Alice. "I'm glad they don't give
+birthday presents like that!" But she did not venture to say it out
+loud.
+
+"Thinking again?" the Duchess asked with another dig of her sharp little
+chin.
+
+"I've a right to think," said Alice sharply, for she was beginning to
+feel a little worried.
+
+"Just about as much right," said the Duchess, "as pigs have to fly; and
+the m----"
+
+But here, to Alice's great surprise, the Duchess's voice died away, even
+in the middle of her favourite word "moral," and the arm that was linked
+into hers began to tremble. Alice looked up, and there stood the Queen
+in front of them, with her arms folded, frowning like a thunderstorm.
+
+"A fine day, your Majesty!" the Duchess began in a low, weak voice.
+
+"Now, I give you fair warning," shouted the Queen, stamping on the
+ground as she spoke; "either you or your head must be off, and that in
+about half no time! Take your choice!"
+
+The Duchess took her choice, and was gone in a moment.
+
+"Let's go on with the game," the Queen said to Alice; and Alice was too
+much frightened to say a word, but slowly followed her back to the
+croquet-ground.
+
+The other guests had taken advantage of the Queen's absence, and were
+resting in the shade: however, the moment they saw her, they hurried
+back to the game, the Queen merely remarking that a moment's delay would
+cost them their lives.
+
+[Illustration: _The Queen never left off quarrelling with the other
+players, and shouting "Off with his head!" or, "Off with her head!"_]
+
+All the time they were playing the Queen never left off quarrelling with
+the other players, and shouting "Off with his head!" or "Off with her
+head!" Those whom she sentenced were taken into custody by the soldiers,
+who of course had to leave off being arches to do this, so that by the
+end of half an hour or so there were no arches left, and all the
+players, except the King, the Queen, and Alice, were in custody and
+under sentence of execution.
+
+Then the Queen left off, quite out of breath, and said to Alice, "Have
+you seen the Mock Turtle yet?"
+
+"No," said Alice. "I don't even know what a Mock Turtle is."
+
+"It's the thing Mock Turtle Soup is made from," said the Queen.
+
+"I never saw one, or heard of one," said Alice.
+
+"Come on then," said the Queen, "and he shall tell you his history."
+
+As they walked off together, Alice heard the King say in a low voice, to
+the company generally, "You are all pardoned." "Come, _that's_ a good
+thing!" she said to herself, for she had felt quite unhappy at the
+number of executions the Queen had ordered.
+
+They very soon came upon a Gryphon, lying fast asleep in the sun. (If
+you don't know what a Gryphon is, look at the picture.) "Up, lazy
+thing!" said the Queen, "and take this young lady to see the Mock
+Turtle, and to hear his history. I must go back and see after some
+executions I have ordered," and she walked off, leaving Alice alone
+with the Gryphon. Alice did not quite like the look of the creature, but
+on the whole she thought it would be quite as safe to stay with it as to
+go after that savage Queen: so she waited.
+
+The Gryphon sat up and rubbed its eyes: then it watched the Queen till
+she was out of sight: then it chuckled. "What fun!" said the Gryphon,
+half to itself, half to Alice.
+
+"What _is_ the fun?" said Alice.
+
+"Why, _she_," said the Gryphon. "It's all her fancy, that: they never
+executes nobody, you know. Come on!"
+
+"Everybody says 'come on!' here," thought Alice, as she went slowly
+after it: "I never was so ordered about in my life, never!"
+
+[Illustration]
+
+They had not gone far before they saw the Mock Turtle in the distance,
+sitting sad and lonely on a little ledge of rock, and, as they came
+nearer, Alice could hear him sighing as if his heart would break. She
+pitied him deeply. "What is his sorrow?" she asked the Gryphon, and the
+Gryphon answered, very nearly in the same words as before, "It's all
+his fancy, that: he hasn't got no sorrow, you know. Come on!"
+
+So they went up to the Mock Turtle, who looked at them with large eyes
+full of tears, but said nothing.
+
+"This here young lady," said the Gryphon, "she wants to know your
+history, she do."
+
+"I'll tell it her," said the Mock Turtle in a deep, hollow tone; "sit
+down, both of you, and don't speak a word till I've finished."
+
+So they sat down, and nobody spoke for some minutes. Alice thought to
+herself, "I don't see how he can _ever_ finish, if he doesn't begin."
+But she waited patiently.
+
+"Once," said the Mock Turtle at last, with a deep sigh, "I was a real
+Turtle."
+
+These words were followed by a very long silence, broken only by an
+occasional exclamation of "Hjckrrh!" from the Gryphon, and the constant
+heavy sobbing of the Mock Turtle. Alice was very nearly getting up and
+saying "Thank you, sir, for your interesting story," but she could not
+help thinking there _must_ be more to come, so she sat still and said
+nothing.
+
+"When we were little," the Mock Turtle went on at last, more calmly,
+though still sobbing a little now and then, "we went to school in the
+sea. The master was an old Turtle--we used to call him Tortoise----"
+
+"Why did you call him Tortoise, if he wasn't one?" Alice asked.
+
+"We called him Tortoise because he taught us," said the Mock Turtle
+angrily: "really you are very dull!"
+
+"You ought to be ashamed of yourself for asking such a simple question,"
+added the Gryphon; and then they both sat silent and looked at poor
+Alice, who felt ready to sink into the earth. At last the Gryphon said
+to the Mock Turtle, "Drive on, old fellow. Don't be all day about it!"
+and he went on in these words:
+
+"Yes, we went to school in the sea, though you mayn't believe it----"
+
+"I never said I didn't!" interrupted Alice.
+
+"You did," said the Mock Turtle.
+
+"Hold your tongue!" added the Gryphon, before Alice could speak again.
+The Mock Turtle went on:--
+
+"We had the best of educations--in fact, we went to school every
+day----"
+
+"_I've_ been to a day-school, too," said Alice; "you needn't be so proud
+as all that."
+
+"With extras?" asked the Mock Turtle a little anxiously.
+
+"Yes," said Alice, "we learned French and music."
+
+"And washing?" said the Mock Turtle.
+
+"Certainly not!" said Alice indignantly.
+
+"Ah! then yours wasn't a really good school," said the Mock Turtle in a
+tone of relief. "Now at _ours_ they had at the end of the bill, 'French,
+music, _and washing_--extra.'"
+
+"You couldn't have wanted it much," said Alice; "living at the bottom of
+the sea."
+
+"I couldn't afford to learn it," said the Mock Turtle with a sigh. "I
+only took the regular course."
+
+"What was that?" inquired Alice.
+
+"Reeling and Writhing, of course, to begin with," the Mock Turtle
+replied; "and then the different branches of Arithmetic--Ambition,
+Distraction, Uglification, and Derision."
+
+"I never heard of 'Uglification,'" Alice ventured to say. "What is it?"
+
+The Gryphon lifted up both its paws in surprise. "Never heard of
+uglifying!" it exclaimed. "You know what to beautify is, I suppose?"
+
+"Yes," said Alice doubtfully: "it means--to--make--anything--prettier."
+
+"Well, then," the Gryphon went on, "if you don't know what to uglify is,
+you are a simpleton."
+
+Alice did not feel encouraged to ask any more questions about it, so she
+turned to the Mock Turtle and said, "What else had you to learn?"
+
+"Well, there was Mystery," the Mock Turtle replied, counting off the
+subjects on his flappers, "--Mystery, ancient and modern, with
+Seaography: then Drawling--the Drawling-master was an old conger-eel,
+that used to come once a week: _he_ taught us Drawling, Stretching, and
+Fainting in Coils."
+
+"What was _that_ like?" said Alice.
+
+"Well, I can't show it you myself," the Mock Turtle said: "I'm too
+stiff. And the Gryphon never learnt it."
+
+"Hadn't time," said the Gryphon: "I went to the Classical master,
+though. He was an old crab, _he_ was."
+
+"I never went to him," the Mock Turtle said with a sigh: "he taught
+Laughing and Grief, they used to say."
+
+"So he did, so he did," said the Gryphon, sighing in his turn; and both
+creatures hid their faces in their paws.
+
+"And how many hours a day did you do lessons?" said Alice, in a hurry to
+change the subject.
+
+"Ten hours the first day," said the Mock Turtle: "nine the next, and so
+on."
+
+"What a curious plan!" exclaimed Alice.
+
+"That's the reason they're called lessons," the Gryphon remarked:
+"because they lessen from day to day."
+
+This was quite a new idea to Alice, and she thought over it a little
+before she made her next remark. "Then the eleventh day must have been a
+holiday."
+
+"Of course it was," said the Mock Turtle.
+
+"And how did you manage on the twelfth?" Alice went on eagerly.
+
+"That's enough about lessons," the Gryphon interrupted in a very decided
+tone: "tell her something about the games now."
+
+
+
+
+CHAPTER X
+
+
+[Sidenote: _The Lobster Quadrille_]
+
+THE Mock Turtle sighed deeply, and drew the back of one
+flapper across his eyes. He looked at Alice, and tried to speak, but,
+for a minute or two, sobs choked his voice. "Same as if he had a bone in
+his throat," said the Gryphon: and it set to work shaking him and
+punching him in the back. At last the Mock Turtle recovered his voice,
+and, with tears running down his cheeks, went on again:
+
+"You may not have lived much under the sea--" ("I haven't," said Alice)
+"and perhaps you were never even introduced to a lobster--" (Alice began
+to say "I once tasted----" but checked herself hastily, and said "No,
+never") "--so you can have no idea what a delightful thing a Lobster
+Quadrille is!"
+
+"No, indeed," said Alice. "What sort of a dance is it?"
+
+"Why," said the Gryphon, "you first form into a line along the
+sea-shore----"
+
+"Two lines!" cried the Mock Turtle. "Seals, turtles, and so on; then,
+when you've cleared the jelly-fish out of the way----"
+
+"_That_ generally takes some time," interrupted the Gryphon.
+
+"--you advance twice----"
+
+"Each with a lobster as a partner!" cried the Gryphon.
+
+"Of course," the Mock Turtle said: "advance twice, set to partners----"
+
+"--change lobsters, and retire in same order," continued the Gryphon.
+
+"Then, you know," the Mock Turtle went on, "you throw the----"
+
+"The lobsters!" shouted the Gryphon, with a bound into the air.
+
+"--as far out to sea as you can----"
+
+"Swim, after them!" screamed the Gryphon.
+
+"Turn a somersault in the sea!" cried the Mock Turtle, capering wildly
+about.
+
+"Change lobsters again!" yelled the Gryphon.
+
+"Back to land again, and--that's all the first figure," said the Mock
+Turtle, suddenly dropping his voice; and the two creatures, who had been
+jumping about like mad things all this time, sat down again very sadly
+and quietly, and looked at Alice.
+
+"It must be a very pretty dance," said Alice, timidly.
+
+"Would you like to see a little of it?" said the Mock Turtle.
+
+"Very much indeed," said Alice.
+
+"Come, let's try the first figure!" said the Mock Turtle to the Gryphon.
+"We can do it without lobsters, you know. Which shall sing?"
+
+"Oh, _you_ sing," said the Gryphon. "I've forgotten the words."
+
+So they began solemnly dancing round and round Alice, every now and then
+treading on her toes when they passed too close, and waving their
+forepaws to mark the time, while the Mock Turtle sang this, very slowly
+and sadly:--
+
+ "Will you walk a little faster?" said a whiting to a snail,
+ "There's a porpoise close behind us, and he's treading on my tail.
+ See how eagerly the lobsters and the turtles all advance!
+ They are waiting on the shingle--will you come and join the dance?
+ Will you, won't you, will you, won't you, will you join the dance?
+ Will you, won't you, will you, won't you, won't you join the dance?
+
+ "You can really have no notion how delightful it will be,
+ When they take us up and throw us, with the lobsters, out to sea!"
+ But the snail replied: "Too far, too far!" and gave a look askance--
+ Said he thanked the whiting kindly, but he would not join the dance.
+ Would not, could not, would not, could not, would not join the dance.
+ Would not, could not, would not, could not, could not join the dance.
+
+ "What matters it how far we go?" his scaly friend replied;
+ "There is another shore, you know, upon the other side.
+ The further off from England the nearer is to France--
+ Then turn not pale, beloved snail, but come and join the dance.
+ Will you, won't you, will you, won't you, will you join the dance?
+ Will you, won't you, will you, won't you, won't you join the dance?"
+
+"Thank you, it's a very interesting dance to watch," said Alice, feeling
+very glad that it was over at last: "and I do so like that curious song
+about the whiting!"
+
+"Oh, as to the whiting," said the Mock Turtle, "they--you've seen them,
+of course?"
+
+"Yes," said Alice, "I've often seen them at dinn----" she checked
+herself hastily.
+
+"I don't know where Dinn may be," said the Mock Turtle, "but if you've
+seen them so often, of course you know what they're like."
+
+"I believe so," Alice replied thoughtfully. "They have their tails in
+their mouths--and they're all over crumbs."
+
+"You're wrong about the crumbs," said the Mock Turtle: "crumbs would all
+wash off in the sea. But they _have_ their tails in their mouths; and
+the reason is--" here the Mock Turtle yawned and shut his eyes. "Tell
+her about the reason and all that," he said to the Gryphon.
+
+"The reason is," said the Gryphon, "that they _would_ go with the
+lobsters to the dance. So they got thrown out to sea. So they had to
+fall a long way. So they got their tails fast in their mouths. So they
+couldn't get them out again. That's all."
+
+"Thank you," said Alice. "It's very interesting. I never knew so much
+about a whiting before."
+
+"I can tell you more than that, if you like," said the Gryphon. "Do you
+know why it's called a whiting?"
+
+"I never thought about it," said Alice. "Why?"
+
+"_It does the boots and shoes_," the Gryphon replied very solemnly.
+
+Alice was thoroughly puzzled. "Does the boots and shoes!" she repeated
+in a wondering tone.
+
+"Why, what are _your_ shoes done with?" said the Gryphon. "I mean, what
+makes them so shiny?"
+
+Alice looked down at them, and considered a little before she gave her
+answer. "They're done with blacking, I believe."
+
+"Boots and shoes under the sea," the Gryphon went on in a deep voice,
+"are done with whiting. Now you know."
+
+"And what are they made of?" Alice asked in a tone of great curiosity.
+
+"Soles and eels, of course," the Gryphon replied rather impatiently:
+"any shrimp could have told you that."
+
+"If I'd been the whiting," said Alice, whose thoughts were still running
+on the song, "I'd have said to the porpoise, 'Keep back, please: we
+don't want _you_ with us!'"
+
+"They were obliged to have him with them," the Mock Turtle said: "no
+wise fish would go anywhere without a porpoise."
+
+"Wouldn't it really?" said Alice in a tone of great surprise.
+
+"Of course not," said the Mock Turtle: "why, if a fish came to _me_, and
+told me he was going a journey, I should say, 'With what porpoise?'"
+
+"Don't you mean 'purpose'?" said Alice.
+
+"I mean what I say," the Mock Turtle replied in an offended tone. And
+the Gryphon added, "Come, let's hear some of _your_ adventures."
+
+[Illustration: _The Mock Turtle drew a long breath and said, "That's
+very curious"_]
+
+"I could tell you my adventures--beginning from this morning," said
+Alice a little timidly: "but it's no use going back to yesterday,
+because I was a different person then."
+
+"Explain all that," said the Mock Turtle.
+
+"No, no! The adventures first," said the Gryphon in an impatient tone:
+"explanations take such a dreadful time."
+
+So Alice began telling them her adventures from the time when she first
+saw the White Rabbit. She was a little nervous about it just at first,
+the two creatures got so close to her, one on each side, and opened
+their eyes and mouths so _very_ wide, but she gained courage as she went
+on. Her listeners were perfectly quiet till she got to the part about
+her repeating "_You are old, Father William_," to the Caterpillar, and
+the words all coming different, and then the Mock Turtle drew a long
+breath, and said, "That's very curious."
+
+"It's all about as curious as it can be," said the Gryphon.
+
+"It all came different!" the Mock Turtle repeated thoughtfully. "I
+should like to hear her repeat something now. Tell her to begin." He
+looked at the Gryphon as if he thought it had some kind of authority
+over Alice.
+
+"Stand up and repeat '_'Tis the voice of the sluggard_,'" said the
+Gryphon.
+
+"How the creatures order one about, and make one repeat lessons!"
+thought Alice. "I might as well be at school at once." However, she got
+up, and began to repeat it, but her head was so full of the Lobster
+Quadrille, that she hardly knew what she was saying, and the words came
+very queer indeed:--
+
+ "'Tis the voice of the Lobster; I heard him declare,
+ 'You have baked me too brown, I must sugar my hair.'
+ As a duck with its eyelids, so he with his nose
+ Trims his belt and his buttons, and turns out his toes.
+ When the sands are all dry, he is gay as a lark,
+ And will talk in contemptuous tones of the Shark:
+ But, when the tide rises and sharks are around,
+ His voice has a timid and tremulous sound."
+
+"That's different from what _I_ used to say when I was a child," said
+the Gryphon.
+
+"Well, _I_ never heard it before," said the Mock Turtle: "but it sounds
+uncommon nonsense."
+
+Alice said nothing; she had sat down with her face in her hands,
+wondering if anything would _ever_ happen in a natural way again.
+
+"I should like to have it explained," said the Mock Turtle.
+
+"She ca'n't explain it," hastily said the Gryphon. "Go on with the next
+verse."
+
+"But about his toes?" the Mock Turtle persisted. "How _could_ he turn
+them out with his nose, you know?"
+
+"It's the first position in dancing," Alice said; but was dreadfully
+puzzled by the whole thing, and longed to change the subject.
+
+"Go on with the next verse," the Gryphon repeated: "it begins '_I passed
+by his garden_.'"
+
+Alice did not dare to disobey, though she felt sure it would all come
+wrong, and she went on in a trembling voice:
+
+ "I passed by his garden, and marked, with one eye,
+ How the Owl and the Panther were sharing a pie:
+ The Panther took pie-crust, and gravy, and meat,
+ While the Owl had the dish as its share of the treat.
+ When the pie was all finished, the Owl, as a boon,
+ Was kindly permitted to pocket the spoon:
+ While the Panther received knife and fork with a growl,
+ And concluded the banquet by----"
+
+"What _is_ the use of repeating all that stuff," the Mock Turtle
+interrupted, "if you don't explain it as you go on? It's by far the most
+confusing thing _I_ ever heard!"
+
+[Illustration]
+
+"Yes, I think you'd better leave off," said the Gryphon: and Alice was
+only too glad to do so.
+
+"Shall we try another figure of the Lobster Quadrille?" the Gryphon went
+on. "Or would you like the Mock Turtle to sing you another song?"
+
+"Oh, a song, please, if the Mock Turtle would be so kind," Alice
+replied, so eagerly that the Gryphon said, in a rather offended tone,
+"H'm! No accounting for tastes! Sing her '_Turtle Soup_,' will you, old
+fellow?"
+
+The Mock Turtle sighed deeply, and began, in a voice choked with sobs,
+to sing this:--
+
+ "Beautiful Soup, so rich and green,
+ Waiting in a hot tureen!
+ Who for such dainties would not stoop?
+ Soup of the evening, beautiful Soup!
+ Soup of the evening, beautiful Soup!
+ Beau--ootiful Soo--oop!
+ Beau--ootiful Soo--oop!
+ Soo--oop of the e--e--evening,
+ Beautiful, beautiful Soup!
+
+ "Beautiful Soup! Who cares for fish,
+ Game, or any other dish?
+ Who would not give all else for two
+ Pennyworth only of beautiful Soup?
+ Pennyworth only of beautiful Soup?
+ Beau--ootiful Soo--oop!
+ Beau--ootiful Soo--oop!
+ Soo--oop of the e--e--evening,
+ Beautiful, beauti--FUL SOUP!"
+
+"Chorus again!" cried the Gryphon, and the Mock Turtle had just begun
+to repeat it, when a cry of "The trial's beginning!" was heard in the
+distance.
+
+"Come on!" cried the Gryphon, and, taking Alice by the hand, it hurried
+off, without waiting for the end of the song.
+
+"What trial is it?" Alice panted as she ran; but the Gryphon only
+answered "Come on!" and ran the faster, while more and more faintly
+came, carried on the breeze that followed them, the melancholy words:--
+
+ "Soo--oop of the e--e--evening,
+ Beautiful, beautiful Soup!"
+
+
+
+
+CHAPTER XI
+
+
+[Sidenote: _Who Stole the Tarts?_]
+
+THE King and Queen of Hearts were seated on their throne
+when they arrived, with a great crowd assembled about them--all sorts of
+little birds and beasts, as well as the whole pack of cards: the Knave
+was standing before them, in chains, with a soldier on each side to
+guard him; and near the King was the White Rabbit, with a trumpet in one
+hand, and a scroll of parchment in the other. In the very middle of the
+court was a table, with a large dish of tarts upon it: they looked so
+good, that it made Alice quite hungry to look at them--"I wish they'd
+get the trial done," she thought, "and hand round the refreshments!" But
+there seemed to be no chance of this, so she began looking about her, to
+pass away the time.
+
+Alice had never been in a court of justice before, but she had read
+about them in books, and she was quite pleased to find that she knew the
+name of nearly everything there. "That's the judge," she said to
+herself, "because of his great wig."
+
+The judge, by the way, was the King; and as he wore his crown over the
+wig, he did not look at all comfortable, and it was certainly not
+becoming.
+
+"And that's the jury-box," thought Alice, "and those twelve creatures,"
+(she was obliged to say "creatures," you see, because some of them were
+animals, and some were birds,) "I suppose they are the jurors." She said
+this last word two or three times over to herself, being rather proud of
+it: for she thought, and rightly too, that very few little girls of her
+age knew the meaning of it at all. However, "jurymen" would have done
+just as well.
+
+The twelve jurors were all writing very busily on slates. "What are they
+all doing?" Alice whispered to the Gryphon. "They can't have anything to
+put down yet, before the trial's begun."
+
+[Illustration: _Who stole the tarts?_]
+
+"They're putting down their names," the Gryphon whispered in reply,
+"for fear they should forget them before the end of the trial."
+
+"Stupid things!" Alice began in a loud, indignant voice, but she stopped
+hastily, for the White Rabbit cried out "Silence in the court!" and the
+King put on his spectacles and looked anxiously round, to see who was
+talking.
+
+Alice could see, as well as if she were looking over their shoulders,
+that all the jurors were writing down "stupid things!" on their slates,
+and she could even make out that one of them didn't know how to spell
+"stupid," and that he had to ask his neighbour to tell him. "A nice
+muddle their slates will be in before the trial's over!" thought Alice.
+
+One of the jurors had a pencil that squeaked. This, of course, Alice
+could _not_ stand, and she went round the court and got behind him, and
+very soon found an opportunity of taking it away. She did it so quickly
+that the poor little juror (it was Bill, the Lizard) could not make out
+at all what had become of it; so, after hunting all about for it, he
+was obliged to write with one finger for the rest of the day; and this
+was of very little use, as it left no mark on the slate.
+
+"Herald, read the accusation!" said the King.
+
+On this the White Rabbit blew three blasts on the trumpet, and then
+unrolled the parchment scroll, and read as follows:
+
+ "The Queen of Hearts, she made some tarts,
+ All on a summer day:
+ The Knave of Hearts, he stole those tarts,
+ And took them quite away!"
+
+"Consider your verdict," the King said to the jury.
+
+"Not yet, not yet!" the Rabbit hastily interrupted. "There's a great
+deal to come before that!"
+
+"Call the first witness," said the King; and the Rabbit blew three
+blasts on the trumpet, and called out "First witness!"
+
+The first witness was the Hatter. He came in with a teacup in one hand
+and a piece of bread-and-butter in the other. "I beg pardon, your
+Majesty," he began, "for bringing these in; but I hadn't quite finished
+my tea when I was sent for."
+
+"You ought to have finished," said the King. "When did you begin?"
+
+The Hatter looked at the March Hare, who had followed him into the
+court, arm-in-arm with the Dormouse. "Fourteenth of March, I _think_ it
+was," he said.
+
+"Fifteenth," said the March Hare.
+
+"Sixteenth," said the Dormouse.
+
+"Write that down," the King said to the jury, and the jury eagerly wrote
+down all three dates on their slates, and then added them up, and
+reduced the answer to shillings and pence.
+
+"Take off your hat," the King said to the Hatter.
+
+"It isn't mine," said the Hatter.
+
+"_Stolen!_" the King exclaimed, turning to the jury, who instantly made
+a memorandum of the fact.
+
+"I keep them to sell," the Hatter added as an explanation: "I've none of
+my own. I'm a hatter."
+
+Here the Queen put on her spectacles, and began staring hard at the
+Hatter, who turned pale and fidgeted.
+
+"Give your evidence," said the King; "and don't be nervous, or I'll have
+you executed on the spot."
+
+This did not seem to encourage the witness at all: he kept shifting from
+one foot to the other, looking uneasily at the Queen, and in his
+confusion he bit a large piece out of his teacup instead of the
+bread-and-butter.
+
+Just at this moment Alice felt a very curious sensation, which puzzled
+her a good deal until she made out what it was: she was beginning to
+grow larger again, and she thought at first she would get up and leave
+the court; but on second thoughts she decided to remain where she was as
+long as there was room for her.
+
+"I wish you wouldn't squeeze so," said the Dormouse, who was sitting
+next to her. "I can hardly breathe."
+
+"I can't help it," said Alice very meekly: "I'm growing."
+
+"You've no right to grow _here_," said the Dormouse.
+
+"Don't talk nonsense," said Alice more boldly: "you know you're growing
+too."
+
+"Yes, but _I_ grow at a reasonable pace," said the Dormouse; "not in
+that ridiculous fashion." And he got up very sulkily and crossed over to
+the other side of the court.
+
+All this time the Queen had never left off staring at the Hatter, and,
+just as the Dormouse crossed the court, she said to one of the officers
+of the court, "Bring me the list of the singers in the last concert!" on
+which the wretched Hatter trembled so, that he shook off both his shoes.
+
+"Give your evidence," the King repeated angrily, "or I'll have you
+executed, whether you're nervous or not."
+
+"I'm a poor man, your Majesty," the Hatter began, in a trembling voice,
+"--and I hadn't begun my tea--not above a week or so--and what with the
+bread-and-butter getting so thin--and the twinkling of the tea----"
+
+"The twinkling of _what_?" said the King.
+
+"It _began_ with the tea," the Hatter replied.
+
+"Of course twinkling _begins_ with a T!" said the King sharply. "Do you
+take me for a dunce? Go on!"
+
+"I'm a poor man," the Hatter went on, "and most things twinkled after
+that--only the March Hare said----"
+
+"I didn't!" the March Hare interrupted in a great hurry.
+
+"You did!" said the Hatter.
+
+"I deny it!" said the March Hare.
+
+"He denies it," said the King: "leave out that part."
+
+"Well, at any rate, the Dormouse said----" the Hatter went on, looking
+anxiously round to see if he would deny it too: but the Dormouse denied
+nothing, being fast asleep.
+
+"After that," continued the Hatter, "I cut some more
+bread-and-butter----"
+
+"But what did the Dormouse say?" one of the jury asked.
+
+"That I can't remember," said the Hatter.
+
+"You _must_ remember," remarked the King, "or I'll have you executed."
+
+The miserable Hatter dropped his teacup and bread-and-butter, and went
+down on one knee. "I'm a poor man, your Majesty," he began.
+
+"You're a _very_ poor _speaker_," said the King.
+
+Here one of the guinea-pigs cheered, and was immediately suppressed by
+the officers of the court. (As that is rather a hard word, I will just
+explain to you how it was done. They had a large canvas bag, which tied
+up at the mouth with strings: into this they slipped the guinea-pig,
+head first, and then sat upon it.)
+
+"I'm glad I've seen that done," thought Alice. "I've so often read in
+the newspapers, at the end of trials, 'There was some attempt at
+applause, which was immediately suppressed by the officers of the
+court,' and I never understood what it meant till now."
+
+"If that's all you know about it, you may stand down," continued the
+King.
+
+"I can't go no lower," said the Hatter: "I'm on the floor, as it is."
+
+"Then you may _sit_ down," the King replied.
+
+Here the other guinea-pig cheered, and was suppressed.
+
+"Come, that finishes the guinea-pigs!" thought Alice. "Now we shall get
+on better."
+
+"I'd rather finish my tea," said the Hatter, with an anxious look at
+the Queen, who was reading the list of singers.
+
+"You may go," said the King; and the Hatter hurriedly left the court,
+without even waiting to put his shoes on.
+
+"--and just take his head off outside," the Queen added to one of the
+officers; but the Hatter was out of sight before the officer could get
+to the door.
+
+"Call the next witness!" said the King.
+
+The next witness was the Duchess's cook. She carried the pepper-box in
+her hand, and Alice guessed who it was, even before she got into the
+court, by the way the people near the door began sneezing all at once.
+
+"Give your evidence," said the King.
+
+"Sha'n't," said the cook.
+
+The King looked anxiously at the White Rabbit, who said in a low voice,
+"Your Majesty must cross-examine _this_ witness."
+
+"Well, if I must, I must," the King said with a melancholy air, and,
+after folding his arms and frowning at the cook till his eyes were
+nearly out of sight, he said in a deep voice, "What are tarts made of?"
+
+"Pepper, mostly," said the cook.
+
+"Treacle," said a sleepy voice behind her.
+
+"Collar that Dormouse," the Queen shrieked out. "Behead that Dormouse!
+Turn that Dormouse out of court! Suppress him! Pinch him! Off with his
+whiskers."
+
+For some minutes the whole court was in confusion, getting the Dormouse
+turned out, and, by the time they had settled down again, the cook had
+disappeared.
+
+[Illustration]
+
+"Never mind!" said the King, with an air of great relief. "Call the next
+witness." And he added in an undertone to the Queen, "Really, my dear,
+_you_ must cross-examine the next witness. It quite makes my forehead
+ache!"
+
+Alice watched the White Rabbit as he fumbled over the list, feeling very
+curious to see what the next witness would be like, "--for they haven't
+got much evidence _yet_," she said to herself. Imagine her surprise,
+when the White Rabbit read out, at the top of his shrill little voice,
+the name "Alice!"
+
+
+
+
+CHAPTER XII
+
+
+[Sidenote: _Alice's Evidence_]
+
+"HERE!" cried Alice, quite forgetting in the flurry of
+the moment how large she had grown in the last few minutes, and she
+jumped up in such a hurry that she tipped over the jury-box with the
+edge of her skirt, upsetting all the jurymen on to the heads of the
+crowd below, and there they lay sprawling about, reminding her very much
+of a globe of gold-fish she had accidentally upset the week before.
+
+"Oh, I _beg_ your pardon!" she exclaimed in a tone of great dismay, and
+began picking them up again as quickly as she could, for the accident of
+the gold-fish kept running in her head, and she had a vague sort of idea
+that they must be collected at once and put back into the jury-box, or
+they would die.
+
+"The trial cannot proceed," said the King in a very grave voice, "until
+all the jurymen are back in their proper places--_all_," he repeated
+with great emphasis, looking hard at Alice as he said so.
+
+Alice looked at the jury-box, and saw that, in her haste, she had put
+the Lizard in head downwards, and the poor little thing was waving its
+tail about in a melancholy way, being quite unable to move. She soon got
+it out again, and put it right; "not that it signifies much," she said
+to herself; "I should think it would be _quite_ as much use in the trial
+one way up as the other."
+
+As soon as the jury had a little recovered from the shock of being
+upset, and their slates and pencils had been found and handed back to
+them, they set to work very diligently to write out a history of the
+accident, all except the Lizard, who seemed too much overcome to do
+anything but sit with its mouth open, gazing up into the roof of the
+court.
+
+"What do you know about this business?" the King said to Alice.
+
+"Nothing," said Alice.
+
+"Nothing _whatever_?" persisted the King.
+
+"Nothing whatever," said Alice.
+
+"That's very important," the King said, turning to the jury. They were
+just beginning to write this down on their slates, when the White Rabbit
+interrupted: "_Un_important, your Majesty means, of course," he said in
+a very respectful tone, but frowning and making faces at him as he
+spoke.
+
+"_Un_important, of course, I meant," the King hastily said, and went on
+himself in an undertone,"important--unimportant--unimportant--important----"
+as if he were trying which word sounded best.
+
+Some of the jury wrote it down "important," and some "unimportant."
+Alice could see this, as she was near enough to look over their slates;
+"but it doesn't matter a bit," she thought to herself.
+
+At this moment the King, who had been for some time busily writing in
+his note-book, called out "Silence!" and read out from his book, "Rule
+Forty-two. _All persons more than a mile high to leave the court._"
+
+Everybody looked at Alice.
+
+"_I'm_ not a mile high," said Alice.
+
+"You are," said the King.
+
+"Nearly two miles high," added the Queen.
+
+"Well, I sha'n't go, at any rate," said Alice: "besides, that's not a
+regular rule: you invented it just now."
+
+"It's the oldest rule in the book," said the King.
+
+"Then it ought to be Number One," said Alice.
+
+The King turned pale, and shut his note-book hastily. "Consider your
+verdict," he said to the jury, in a low trembling voice.
+
+"There's more evidence to come yet, please your Majesty," said the White
+Rabbit, jumping up in a great hurry: "this paper has just been picked
+up."
+
+"What's in it?" said the Queen.
+
+"I haven't opened it yet," said the White Rabbit, "but it seems to be a
+letter, written by the prisoner to--to somebody."
+
+"It must have been that," said the King, "unless it was written to
+nobody, which isn't usual, you know."
+
+"Who is it directed to?" said one of the jurymen.
+
+"It isn't directed at all," said the White Rabbit; "in fact, there's
+nothing written on the _outside_." He unfolded the paper as he spoke,
+and added "It isn't a letter after all: it's a set of verses."
+
+"Are they in the prisoner's handwriting?" asked another of the jurymen.
+
+"No, they're not," said the White Rabbit, "and that's the queerest thing
+about it." (The jury all looked puzzled.)
+
+"He must have imitated somebody else's hand," said the King. (The jury
+all brightened up again.)
+
+"Please your Majesty," said the Knave, "I didn't write it, and they
+can't prove that I did: there's no name signed at the end."
+
+"If you didn't sign it," said the King, "that only makes the matter
+worse. You _must_ have meant some mischief, or else you'd have signed
+your name like an honest man."
+
+There was a general clapping of hands at this: it was the first really
+clever thing the King had said that day.
+
+"That _proves_ his guilt, of course," said the Queen: "so, off with----"
+
+"It doesn't prove anything of the sort!" said Alice. "Why, you don't
+even know what they're about!"
+
+"Read them," said the King.
+
+The White Rabbit put on his spectacles. "Where shall I begin, please
+your Majesty?" he asked.
+
+"Begin at the beginning," the King said gravely, "and go on till you
+come to the end; then stop."
+
+There was dead silence in the court, whilst the White Rabbit read out
+these verses:--
+
+ "They told me you had been to her,
+ And mentioned me to him:
+ She gave me a good character,
+ But said I could not swim.
+
+ He sent them word I had not gone,
+ (We know it to be true):
+ If she should push the matter on,
+ What would become of you?
+
+ I gave her one, they gave him two,
+ You gave us three or more;
+ They all returned from him to you,
+ Though they were mine before.
+
+ If I or she should chance to be
+ Involved in this affair,
+ He trusts to you to set them free,
+ Exactly as we were.
+
+ My notion was that you had been
+ (Before she had this fit)
+ An obstacle that came between
+ Him, and ourselves, and it.
+
+ Don't let him know she liked them best,
+ For this must ever be
+ A secret, kept from all the rest,
+ Between yourself and me."
+
+"That's the most important piece of evidence we've heard yet," said the
+King, rubbing his hands; "so now let the jury----"
+
+"If any of them can explain it," said Alice, (she had grown so large in
+the last few minutes that she wasn't a bit afraid of interrupting him,)
+"I'll give him sixpence. _I_ don't believe there's an atom of meaning in
+it."
+
+The jury all wrote down on their slates, "_She_ doesn't believe there's
+an atom of meaning in it," but none of them attempted to explain the
+paper.
+
+"If there's no meaning in it," said the King, "that saves a world of
+trouble, you know, as we needn't try to find any. And yet I don't
+know," he went on, spreading out the verses on his knee, and looking at
+them with one eye; "I seem to see some meaning in them after all.
+'----_said I could not swim_--' you can't swim can you?" he added,
+turning to the Knave.
+
+The Knave shook his head sadly. "Do I look like it?" he said. (Which he
+certainly did _not_, being made entirely of cardboard.)
+
+"All right, so far," said the King, as he went on muttering over the
+verses to himself: "'_We know it to be true_--' that's the jury, of
+course--'_If she should push the matter on_'--that must be the
+Queen--'_What would become of you?_'--What, indeed!--'_I gave her one,
+they gave him two_--' why, that must be what he did with the tarts, you
+know----"
+
+"But it goes on '_they all returned from him to you_,'" said Alice.
+
+"Why, there they are!" said the King triumphantly, pointing to the tarts
+on the table. "Nothing can be clearer than _that_. Then again--'_before
+she had this fit_--' you never had _fits_, my dear, I think?" he said to
+the Queen.
+
+"Never!" said the Queen furiously, throwing an inkstand at the Lizard
+as she spoke. (The unfortunate little Bill had left off writing on his
+slate with one finger, as he found it made no mark; but he now hastily
+began again, using the ink, that was trickling down his face, as long as
+it lasted.)
+
+"Then the words don't _fit_ you," said the King, looking round the court
+with a smile. There was a dead silence.
+
+"It's a pun!" the King added in an angry tone, and everybody laughed.
+
+"Let the jury consider their verdict," the King said, for about the
+twentieth time that day.
+
+"No, no!" said the Queen. "Sentence first--verdict afterwards."
+
+"Stuff and nonsense!" said Alice loudly. "The idea of having the
+sentence first!"
+
+"Hold your tongue!" said the Queen, turning purple.
+
+"I won't!" said Alice.
+
+"Off with her head!" the Queen shouted at the top of her voice. Nobody
+moved.
+
+"Who cares for _you_?" said Alice (she had grown to her full size by
+this time). "You're nothing but a pack of cards!"
+
+[Illustration: _At this the whole pack rose up into the air, and came
+flying down upon her_]
+
+At this the whole pack rose up into the air, and came flying down upon
+her: she gave a little scream, half of fright and half of anger, and
+tried to beat them off, and found herself lying on the bank, with her
+head in the lap of her sister, who was gently brushing away some dead
+leaves that had fluttered down from the trees upon her face.
+
+"Wake up, Alice dear!" said her sister. "Why, what a long sleep you've
+had!"
+
+"Oh, I've had such a curious dream!" said Alice, and she told her
+sister, as well as she could remember them, all these strange Adventures
+of hers that you have just been reading about; and when she had
+finished, her sister kissed her, and said "It _was_ a curious dream,
+dear, certainly: but now run in to your tea; it's getting late." So
+Alice got up and ran off, thinking while she ran, as well she might,
+what a wonderful dream it had been.
+
+
+
+
+BUT her sister sat still just as she had left her, leaning her head,
+watching the setting sun, and thinking of little Alice and all her
+wonderful Adventures, till she too began dreaming after a fashion, and
+this was her dream:
+
+First, she dreamed of little Alice herself, and once again the tiny
+hands were clasped upon her knee, and the bright eager eyes were looking
+up into hers--she could hear the very tones of her voice, and see that
+queer little toss of her head to keep back the wandering hair that
+_would_ always get into her eyes--and still as she listened, or seemed
+to listen, the whole place around her became alive with the strange
+creatures of her little sister's dream.
+
+The long grass rustled at her feet as the White Rabbit hurried by--the
+frightened Mouse splashed his way through the neighbouring pool--she
+could hear the rattle of the teacups as the March Hare and his friends
+shared their never-ending meal, and the shrill voice of the Queen
+ordering off her unfortunate guests to execution--once more the pig-baby
+was sneezing on the Duchess' knee, while plates and dishes crashed
+around it--once more the shriek of the Gryphon, the squeaking of the
+Lizard's slate-pencil, and the choking of the suppressed guinea-pigs,
+filled the air, mixed up with the distant sobs of the miserable Mock
+Turtle.
+
+So she sat on with closed eyes, and half believed herself in Wonderland,
+though she knew she had but to open them again, and all would change to
+dull reality--the grass would be only rustling in the wind, and the pool
+rippling to the waving of the reeds--the rattling teacups would change
+to the tinkling sheep-bells, and the Queen's shrill cries to the voice
+of the shepherd boy--and the sneeze of the baby, the shriek of the
+Gryphon, and all the other queer noises, would change (she knew) to the
+confused clamour of the busy farm-yard--while the lowing of the cattle
+in the distance would take the place of the Mock Turtle's heavy sobs.
+
+Lastly, she pictured to herself how this same little sister of hers
+would, in the after-time, be herself a grown woman; and how she would
+keep, through all her riper years, the simple and loving heart of her
+childhood: and how she would gather about her other little children,
+and make _their_ eyes bright and eager with many a strange tale, perhaps
+even with the dream of Wonderland of long ago: and how she would feel
+with all their simple sorrows, and find a pleasure in all their simple
+joys, remembering her own child-life, and the happy summer days.
+
+
+THE END
+
+
+
+
+ ILLUSTRATIONS REPRODUCED BY HENTSCHEL COLOURTYPE
+ TEXT PRINTED BY BALLANTYNE & COMPANY LTD
+ AT THE BALLANTYNE PRESS
+ TAVISTOCK STREET
+ LONDON
+
+ * * * * *
+
+Transcriber's Notes:
+
+Page 8, opening quote added to text (doorway; "and even if)
+
+Page 33, "she" changed to "she's" (And she's such a)
+
+Page 37, "quiet" changed to "quite" (I'm quite tired of)
+
+Page 41, colon changed to period (arm, yer honour.)
+
+Page 42, "wont" changed to "want" (want to stay)
+
+Page 66, closing quotation mark added (to-morrow----")
+
+Page 69, single quotation mark changed to double (cat," said the
+Duchess)
+
+Page 91, word "to" added to text (minute or two to)
+
+Page 103, word "as" added to the text (just as she had)
+
+Page 104, "hedge-hog" changed to "hedgehog" (send the hedgehog to)
+
+Page 126, end parenthesis added ("No, never")
+
+Page 153, added an apostrophe (What's in it?)
+
+
+
+
+
+
+End of Project Gutenberg's Alice's Adventures in Wonderland, by Lewis Carroll
+
+*** END OF THIS PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***
+
+***** This file should be named 28885-8.txt or 28885-8.zip *****
+This and all associated files of various formats will be found in:
+ http://www.gutenberg.org/2/8/8/8/28885/
+
+Produced by Jana Srna, Emmy and the Online Distributed
+Proofreading Team at http://www.pgdp.net (This file was
+produced from images generously made available by the
+University of Florida Digital Collections.)
+
+
+Updated editions will replace the previous one--the old editions
+will be renamed.
+
+Creating the works from public domain print editions means that no
+one owns a United States copyright in these works, so the Foundation
+(and you!) can copy and distribute it in the United States without
+permission and without paying copyright royalties. Special rules,
+set forth in the General Terms of Use part of this license, apply to
+copying and distributing Project Gutenberg-tm electronic works to
+protect the PROJECT GUTENBERG-tm concept and trademark. Project
+Gutenberg is a registered trademark, and may not be used if you
+charge for the eBooks, unless you receive specific permission. If you
+do not charge anything for copies of this eBook, complying with the
+rules is very easy. You may use this eBook for nearly any purpose
+such as creation of derivative works, reports, performances and
+research. They may be modified and printed and given away--you may do
+practically ANYTHING with public domain eBooks. Redistribution is
+subject to the trademark license, especially commercial
+redistribution.
+
+
+
+*** START: FULL LICENSE ***
+
+THE FULL PROJECT GUTENBERG LICENSE
+PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
+
+To protect the Project Gutenberg-tm mission of promoting the free
+distribution of electronic works, by using or distributing this work
+(or any other work associated in any way with the phrase "Project
+Gutenberg"), you agree to comply with all the terms of the Full Project
+Gutenberg-tm License (available with this file or online at
+http://gutenberg.net/license).
+
+
+Section 1. General Terms of Use and Redistributing Project Gutenberg-tm
+electronic works
+
+1.A. By reading or using any part of this Project Gutenberg-tm
+electronic work, you indicate that you have read, understand, agree to
+and accept all the terms of this license and intellectual property
+(trademark/copyright) agreement. If you do not agree to abide by all
+the terms of this agreement, you must cease using and return or destroy
+all copies of Project Gutenberg-tm electronic works in your possession.
+If you paid a fee for obtaining a copy of or access to a Project
+Gutenberg-tm electronic work and you do not agree to be bound by the
+terms of this agreement, you may obtain a refund from the person or
+entity to whom you paid the fee as set forth in paragraph 1.E.8.
+
+1.B. "Project Gutenberg" is a registered trademark. It may only be
+used on or associated in any way with an electronic work by people who
+agree to be bound by the terms of this agreement. There are a few
+things that you can do with most Project Gutenberg-tm electronic works
+even without complying with the full terms of this agreement. See
+paragraph 1.C below. There are a lot of things you can do with Project
+Gutenberg-tm electronic works if you follow the terms of this agreement
+and help preserve free future access to Project Gutenberg-tm electronic
+works. See paragraph 1.E below.
+
+1.C. The Project Gutenberg Literary Archive Foundation ("the Foundation"
+or PGLAF), owns a compilation copyright in the collection of Project
+Gutenberg-tm electronic works. Nearly all the individual works in the
+collection are in the public domain in the United States. If an
+individual work is in the public domain in the United States and you are
+located in the United States, we do not claim a right to prevent you from
+copying, distributing, performing, displaying or creating derivative
+works based on the work as long as all references to Project Gutenberg
+are removed. Of course, we hope that you will support the Project
+Gutenberg-tm mission of promoting free access to electronic works by
+freely sharing Project Gutenberg-tm works in compliance with the terms of
+this agreement for keeping the Project Gutenberg-tm name associated with
+the work. You can easily comply with the terms of this agreement by
+keeping this work in the same format with its attached full Project
+Gutenberg-tm License when you share it without charge with others.
+
+1.D. The copyright laws of the place where you are located also govern
+what you can do with this work. Copyright laws in most countries are in
+a constant state of change. If you are outside the United States, check
+the laws of your country in addition to the terms of this agreement
+before downloading, copying, displaying, performing, distributing or
+creating derivative works based on this work or any other Project
+Gutenberg-tm work. The Foundation makes no representations concerning
+the copyright status of any work in any country outside the United
+States.
+
+1.E. Unless you have removed all references to Project Gutenberg:
+
+1.E.1. The following sentence, with active links to, or other immediate
+access to, the full Project Gutenberg-tm License must appear prominently
+whenever any copy of a Project Gutenberg-tm work (any work on which the
+phrase "Project Gutenberg" appears, or with which the phrase "Project
+Gutenberg" is associated) is accessed, displayed, performed, viewed,
+copied or distributed:
+
+This eBook is for the use of anyone anywhere at no cost and with
+almost no restrictions whatsoever. You may copy it, give it away or
+re-use it under the terms of the Project Gutenberg License included
+with this eBook or online at www.gutenberg.net
+
+1.E.2. If an individual Project Gutenberg-tm electronic work is derived
+from the public domain (does not contain a notice indicating that it is
+posted with permission of the copyright holder), the work can be copied
+and distributed to anyone in the United States without paying any fees
+or charges. If you are redistributing or providing access to a work
+with the phrase "Project Gutenberg" associated with or appearing on the
+work, you must comply either with the requirements of paragraphs 1.E.1
+through 1.E.7 or obtain permission for the use of the work and the
+Project Gutenberg-tm trademark as set forth in paragraphs 1.E.8 or
+1.E.9.
+
+1.E.3. If an individual Project Gutenberg-tm electronic work is posted
+with the permission of the copyright holder, your use and distribution
+must comply with both paragraphs 1.E.1 through 1.E.7 and any additional
+terms imposed by the copyright holder. Additional terms will be linked
+to the Project Gutenberg-tm License for all works posted with the
+permission of the copyright holder found at the beginning of this work.
+
+1.E.4. Do not unlink or detach or remove the full Project Gutenberg-tm
+License terms from this work, or any files containing a part of this
+work or any other work associated with Project Gutenberg-tm.
+
+1.E.5. Do not copy, display, perform, distribute or redistribute this
+electronic work, or any part of this electronic work, without
+prominently displaying the sentence set forth in paragraph 1.E.1 with
+active links or immediate access to the full terms of the Project
+Gutenberg-tm License.
+
+1.E.6. You may convert to and distribute this work in any binary,
+compressed, marked up, nonproprietary or proprietary form, including any
+word processing or hypertext form. However, if you provide access to or
+distribute copies of a Project Gutenberg-tm work in a format other than
+"Plain Vanilla ASCII" or other format used in the official version
+posted on the official Project Gutenberg-tm web site (www.gutenberg.net),
+you must, at no additional cost, fee or expense to the user, provide a
+copy, a means of exporting a copy, or a means of obtaining a copy upon
+request, of the work in its original "Plain Vanilla ASCII" or other
+form. Any alternate format must include the full Project Gutenberg-tm
+License as specified in paragraph 1.E.1.
+
+1.E.7. Do not charge a fee for access to, viewing, displaying,
+performing, copying or distributing any Project Gutenberg-tm works
+unless you comply with paragraph 1.E.8 or 1.E.9.
+
+1.E.8. You may charge a reasonable fee for copies of or providing
+access to or distributing Project Gutenberg-tm electronic works provided
+that
+
+- You pay a royalty fee of 20% of the gross profits you derive from
+ the use of Project Gutenberg-tm works calculated using the method
+ you already use to calculate your applicable taxes. The fee is
+ owed to the owner of the Project Gutenberg-tm trademark, but he
+ has agreed to donate royalties under this paragraph to the
+ Project Gutenberg Literary Archive Foundation. Royalty payments
+ must be paid within 60 days following each date on which you
+ prepare (or are legally required to prepare) your periodic tax
+ returns. Royalty payments should be clearly marked as such and
+ sent to the Project Gutenberg Literary Archive Foundation at the
+ address specified in Section 4, "Information about donations to
+ the Project Gutenberg Literary Archive Foundation."
+
+- You provide a full refund of any money paid by a user who notifies
+ you in writing (or by e-mail) within 30 days of receipt that s/he
+ does not agree to the terms of the full Project Gutenberg-tm
+ License. You must require such a user to return or
+ destroy all copies of the works possessed in a physical medium
+ and discontinue all use of and all access to other copies of
+ Project Gutenberg-tm works.
+
+- You provide, in accordance with paragraph 1.F.3, a full refund of any
+ money paid for a work or a replacement copy, if a defect in the
+ electronic work is discovered and reported to you within 90 days
+ of receipt of the work.
+
+- You comply with all other terms of this agreement for free
+ distribution of Project Gutenberg-tm works.
+
+1.E.9. If you wish to charge a fee or distribute a Project Gutenberg-tm
+electronic work or group of works on different terms than are set
+forth in this agreement, you must obtain permission in writing from
+both the Project Gutenberg Literary Archive Foundation and Michael
+Hart, the owner of the Project Gutenberg-tm trademark. Contact the
+Foundation as set forth in Section 3 below.
+
+1.F.
+
+1.F.1. Project Gutenberg volunteers and employees expend considerable
+effort to identify, do copyright research on, transcribe and proofread
+public domain works in creating the Project Gutenberg-tm
+collection. Despite these efforts, Project Gutenberg-tm electronic
+works, and the medium on which they may be stored, may contain
+"Defects," such as, but not limited to, incomplete, inaccurate or
+corrupt data, transcription errors, a copyright or other intellectual
+property infringement, a defective or damaged disk or other medium, a
+computer virus, or computer codes that damage or cannot be read by
+your equipment.
+
+1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the "Right
+of Replacement or Refund" described in paragraph 1.F.3, the Project
+Gutenberg Literary Archive Foundation, the owner of the Project
+Gutenberg-tm trademark, and any other party distributing a Project
+Gutenberg-tm electronic work under this agreement, disclaim all
+liability to you for damages, costs and expenses, including legal
+fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
+LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE
+PROVIDED IN PARAGRAPH F3. YOU AGREE THAT THE FOUNDATION, THE
+TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE
+LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR
+INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a
+defect in this electronic work within 90 days of receiving it, you can
+receive a refund of the money (if any) you paid for it by sending a
+written explanation to the person you received the work from. If you
+received the work on a physical medium, you must return the medium with
+your written explanation. The person or entity that provided you with
+the defective work may elect to provide a replacement copy in lieu of a
+refund. If you received the work electronically, the person or entity
+providing it to you may choose to give you a second opportunity to
+receive the work electronically in lieu of a refund. If the second copy
+is also defective, you may demand a refund in writing without further
+opportunities to fix the problem.
+
+1.F.4. Except for the limited right of replacement or refund set forth
+in paragraph 1.F.3, this work is provided to you 'AS-IS' WITH NO OTHER
+WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+WARRANTIES OF MERCHANTIBILITY OR FITNESS FOR ANY PURPOSE.
+
+1.F.5. Some states do not allow disclaimers of certain implied
+warranties or the exclusion or limitation of certain types of damages.
+If any disclaimer or limitation set forth in this agreement violates the
+law of the state applicable to this agreement, the agreement shall be
+interpreted to make the maximum disclaimer or limitation permitted by
+the applicable state law. The invalidity or unenforceability of any
+provision of this agreement shall not void the remaining provisions.
+
+1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the
+trademark owner, any agent or employee of the Foundation, anyone
+providing copies of Project Gutenberg-tm electronic works in accordance
+with this agreement, and any volunteers associated with the production,
+promotion and distribution of Project Gutenberg-tm electronic works,
+harmless from all liability, costs and expenses, including legal fees,
+that arise directly or indirectly from any of the following which you do
+or cause to occur: (a) distribution of this or any Project Gutenberg-tm
+work, (b) alteration, modification, or additions or deletions to any
+Project Gutenberg-tm work, and (c) any Defect you cause.
+
+
+Section 2. Information about the Mission of Project Gutenberg-tm
+
+Project Gutenberg-tm is synonymous with the free distribution of
+electronic works in formats readable by the widest variety of computers
+including obsolete, old, middle-aged and new computers. It exists
+because of the efforts of hundreds of volunteers and donations from
+people in all walks of life.
+
+Volunteers and financial support to provide volunteers with the
+assistance they need are critical to reaching Project Gutenberg-tm's
+goals and ensuring that the Project Gutenberg-tm collection will
+remain freely available for generations to come. In 2001, the Project
+Gutenberg Literary Archive Foundation was created to provide a secure
+and permanent future for Project Gutenberg-tm and future generations.
+To learn more about the Project Gutenberg Literary Archive Foundation
+and how your efforts and donations can help, see Sections 3 and 4
+and the Foundation web page at http://www.pglaf.org.
+
+
+Section 3. Information about the Project Gutenberg Literary Archive
+Foundation
+
+The Project Gutenberg Literary Archive Foundation is a non profit
+501(c)(3) educational corporation organized under the laws of the
+state of Mississippi and granted tax exempt status by the Internal
+Revenue Service. The Foundation's EIN or federal tax identification
+number is 64-6221541. Its 501(c)(3) letter is posted at
+http://pglaf.org/fundraising. Contributions to the Project Gutenberg
+Literary Archive Foundation are tax deductible to the full extent
+permitted by U.S. federal laws and your state's laws.
+
+The Foundation's principal office is located at 4557 Melan Dr. S.
+Fairbanks, AK, 99712., but its volunteers and employees are scattered
+throughout numerous locations. Its business office is located at
+809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887, email
+business@pglaf.org. Email contact links and up to date contact
+information can be found at the Foundation's web site and official
+page at http://pglaf.org
+
+For additional contact information:
+ Dr. Gregory B. Newby
+ Chief Executive and Director
+ gbnewby@pglaf.org
+
+
+Section 4. Information about Donations to the Project Gutenberg
+Literary Archive Foundation
+
+Project Gutenberg-tm depends upon and cannot survive without wide
+spread public support and donations to carry out its mission of
+increasing the number of public domain and licensed works that can be
+freely distributed in machine readable form accessible by the widest
+array of equipment including outdated equipment. Many small donations
+($1 to $5,000) are particularly important to maintaining tax exempt
+status with the IRS.
+
+The Foundation is committed to complying with the laws regulating
+charities and charitable donations in all 50 states of the United
+States. Compliance requirements are not uniform and it takes a
+considerable effort, much paperwork and many fees to meet and keep up
+with these requirements. We do not solicit donations in locations
+where we have not received written confirmation of compliance. To
+SEND DONATIONS or determine the status of compliance for any
+particular state visit http://pglaf.org
+
+While we cannot and do not solicit contributions from states where we
+have not met the solicitation requirements, we know of no prohibition
+against accepting unsolicited donations from donors in such states who
+approach us with offers to donate.
+
+International donations are gratefully accepted, but we cannot make
+any statements concerning tax treatment of donations received from
+outside the United States. U.S. laws alone swamp our small staff.
+
+Please check the Project Gutenberg Web pages for current donation
+methods and addresses. Donations are accepted in a number of other
+ways including including checks, online payments and credit card
+donations. To donate, please visit: http://pglaf.org/donate
+
+
+Section 5. General Information About Project Gutenberg-tm electronic
+works.
+
+Professor Michael S. Hart is the originator of the Project Gutenberg-tm
+concept of a library of electronic works that could be freely shared
+with anyone. For thirty years, he produced and distributed Project
+Gutenberg-tm eBooks with only a loose network of volunteer support.
+
+
+Project Gutenberg-tm eBooks are often created from several printed
+editions, all of which are confirmed as Public Domain in the U.S.
+unless a copyright notice is included. Thus, we do not necessarily
+keep eBooks in compliance with any particular paper edition.
+
+
+Most people start at our Web site which has the main PG search facility:
+
+ http://www.gutenberg.net
+
+This Web site includes information about Project Gutenberg-tm,
+including how to make donations to the Project Gutenberg Literary
+Archive Foundation, how to help produce our new eBooks, and how to
+subscribe to our email newsletter to hear about new eBooks.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/examples/items-sorted.txt Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,18 @@
+Compilers: Principles, Techniques, and Tools
+Introduction to Algorithms
+Programming Pearls
+Programming Pearls
+Programming Pearls
+Programming Pearls
+Programming Pearls
+Structure and Interpretation of Computer Programs
+The Art of Computer Programming
+The Art of UNIX Programming
+The Art of UNIX Programming
+The Art of UNIX Programming
+The C Programming Language
+The C Programming Language
+The C Programming Language
+The Mythical Man Month: Essays on Software Engineering
+The Pragmatic Programmer: From Journeyman to Master
+Unix Power Tools
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/examples/items.txt Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,18 @@
+Programming Pearls
+The C Programming Language
+The Mythical Man Month: Essays on Software Engineering
+Programming Pearls
+The C Programming Language
+Structure and Interpretation of Computer Programs
+Programming Pearls
+Compilers: Principles, Techniques, and Tools
+The C Programming Language
+The Art of UNIX Programming
+Programming Pearls
+The Art of Computer Programming
+Introduction to Algorithms
+The Art of UNIX Programming
+The Pragmatic Programmer: From Journeyman to Master
+Programming Pearls
+Unix Power Tools
+The Art of UNIX Programming
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/examples/stalwarts.txt Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,7 @@
+Richard Stallman%rms%GNU Project
+Eric Raymond%ESR%Jargon File
+Ian Murdock% %Debian
+Lawrence Lessig% %Creative Commons
+Linus Torvalds% %Linux Kernel
+Guido van Rossum%BDFL%Python
+Larry Wall% %Perl
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/examples/stalwarts1.txt Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,7 @@
+Richard Stallman%http://www.stallman.org
+Eric Raymond%http://www.catb.org/~esr/
+Ian Murdock%http://ianmurdock.com/
+Lawrence Lessig%http://lessig.org
+Linus Torvalds%http://torvalds-family.blogspot.com/
+Guido van Rossum%http://www.python.org/~guido/
+Larry Wall%http://www.wall.org/~larry/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/examples/stalwarts2.txt Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,7 @@
+http://www.stallman.org%Richard Stallman
+http://www.catb.org/~esr/%Eric Raymond
+http://ianmurdock.com/%Ian Murdock
+http://lessig.org%Lawrence Lessig
+http://torvalds-family.blogspot.com/%Linus Torvalds
+http://www.python.org/~guido/%Guido van Rossum
+http://www.wall.org/~larry/%Larry Wall
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/session4.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,507 @@
+More text processing
+====================
+
+``sort``
+--------
+Let's say we have a file which lists a few of the stalwarts of the open source community and a few details about them, like their "other" name, their homepage address, and what they are well known for or their claim to fame.
+
+::
+
+ Richard Stallman%rms%GNU Project
+ Eric Raymond%ESR%Jargon File
+ Ian Murdock% %Debian
+ Lawrence Lessig% %Creative Commons
+ Linus Torvalds% %Linux Kernel
+ Guido van Rossum%BDFL%Python
+ Larry Wall% %Perl
+
+
+The sort command enables us to do this in a flash! Just running the sort command with the file name as a parameter sorts the lines of the file alphabetically and prints the output on the terminal.
+::
+
+ $ sort stalwarts.txt
+ Eric Raymond%ESR%Jargon File
+ Guido van Rossum%BDFL%Python
+ Ian Murdock% %Debian
+ Larry Wall% %Perl
+ Lawrence Lessig% %Creative Commons
+ Linus Torvalds% %Linux Kernel
+ Richard Stallman%rms%GNU Project
+
+If you wish to sort them reverse alphabetically, you just need to pass the ``-r`` option. Now, you might want to sort the lines, based on each person's claim to fame or their "other" name. What do we do in that case?
+
+Below is an example that sorts the file based on "other" names.
+::
+
+ $ sort -t % -k 2,2 stalwarts.txt
+
+ Ian Murdock% %Debian
+ Larry Wall% %Perl
+ Lawrence Lessig% %Creative Commons
+ Linus Torvalds% %Linux Kernel
+ Guido van Rossum%BDFL%Python
+ Eric Raymond%ESR%Jargon File
+ Richard Stallman%rms%GNU Project
+
+Sort command assumes white space to be the default delimiter for columns in each line. The ``-t`` option specifies the delimiting character, which is ``%`` in this case.
+
+The ``-k`` option starts a key at position 2 and ends it at 2, essentially telling the sort command that it should sort based on the 2nd column, which is the other name. ``sort`` also supports conflict resolution using multiple columns for sorting. You can see that the first three lines have nothing in the "other" names column. We could resolve the conflict by sorting based on the project names (the 3rd column).
+
+::
+
+ $ sort -t % -k 2,2 -k 3,3 stalwarts.txt
+
+ Lawrence Lessig% %Creative Commons
+ Ian Murdock% %Debian
+ Linus Torvalds% %Linux Kernel
+ Larry Wall% %Perl
+ Guido van Rossum%BDFL%Python
+ Eric Raymond%ESR%Jargon File
+ Richard Stallman%rms%GNU Project
+
+``sort`` also has a lot of other options like ignoring case differences, month sort(JAN<FEB<...), merging already sorted files. ``man sort`` would give you a lot of information.
+
+
+``uniq``
+--------
+
+Suppose we have a list of items, say books, and we wish to obtain a list which names of all the books only once, without any duplicates. We use the ``uniq`` command to achieve this.
+
+::
+
+ Programming Pearls
+ The C Programming Language
+ The Mythical Man Month: Essays on Software Engineering
+ Programming Pearls
+ The C Programming Language
+ Structure and Interpretation of Computer Programs
+ Programming Pearls
+ Compilers: Principles, Techniques, and Tools
+ The C Programming Language
+ The Art of UNIX Programming
+ Programming Pearls
+ The Art of Computer Programming
+ Introduction to Algorithms
+ The Art of UNIX Programming
+ The Pragmatic Programmer: From Journeyman to Master
+ Programming Pearls
+ Unix Power Tools
+ The Art of UNIX Programming
+
+Let us try and get rid of the duplicate lines from this file using the ``uniq`` command.
+
+::
+
+ $ uniq items.txt
+ Programming Pearls
+ The C Programming Language
+ The Mythical Man Month: Essays on Software Engineering
+ Programming Pearls
+ The C Programming Language
+ Structure and Interpretation of Computer Programs
+ Programming Pearls
+ Compilers: Principles, Techniques, and Tools
+ The C Programming Language
+ The Art of UNIX Programming
+ Programming Pearls
+ The Art of Computer Programming
+ Introduction to Algorithms
+ The Art of UNIX Programming
+ The Pragmatic Programmer: From Journeyman to Master
+ Programming Pearls
+ Unix Power Tools
+ The Art of UNIX Programming
+
+Nothing happens! Why? The ``uniq`` command removes duplicate lines only when they are next to each other. So, we get a sorted file from the original file and work with that file, henceforth.
+
+::
+
+ $ sort items.txt > items-sorted.txt
+ $ uniq items-sorted.txt
+ Compilers: Principles, Techniques, and Tools
+ Introduction to Algorithms
+ Programming Pearls
+ Structure and Interpretation of Computer Programs
+ The Art of Computer Programming
+ The Art of UNIX Programming
+ The C Programming Language
+ The Mythical Man Month: Essays on Software Engineering
+ The Pragmatic Programmer: From Journeyman to Master
+ Unix Power Tools
+
+``uniq -u`` command gives the lines which are unique and do not have any duplicates in the file. ``uniq -d`` outputs only those lines which have duplicates. The ``-c`` option displays the number of times each line occurs in the file.
+::
+
+ $ uniq -u items-sorted.txt
+ Compilers: Principles, Techniques, and Tools
+ Introduction to Algorithms
+ Structure and Interpretation of Computer Programs
+ The Art of Computer Programming
+ The Mythical Man Month: Essays on Software Engineering
+ The Pragmatic Programmer: From Journeyman to Master
+ Unix Power Tools
+
+ $ uniq -dc items-sorted.txt
+ 5 Programming Pearls
+ 3 The Art of UNIX Programming
+ 3 The C Programming Language
+
+
+``join``
+--------
+
+Now suppose we had the file ``stalwarts1.txt``, which lists the home pages of all the people listed in ``stalwarts.txt``.
+::
+
+ Richard Stallman%http://www.stallman.org
+ Eric Raymond%http://www.catb.org/~esr/
+ Ian Murdock%http://ianmurdock.com/
+ Lawrence Lessig%http://lessig.org
+ Linus Torvalds%http://torvalds-family.blogspot.com/
+ Guido van Rossum%http://www.python.org/~guido/
+ Larry Wall%http://www.wall.org/~larry/
+
+It would be nice to have a single file with the information in both the files. To achieve this we use the ``join`` command.
+::
+
+ $ join stalwarts.txt stalwarts1.txt -t %
+ Richard Stallman%rms%GNU Project%http://www.stallman.org
+ Eric Raymond%ESR%Jargon File%http://www.catb.org/~esr/
+ Ian Murdock% %Debian%http://ianmurdock.com/
+ Lawrence Lessig% %Creative Commons%http://lessig.org
+ Linus Torvalds% %Linux Kernel%http://torvalds-family.blogspot.com/
+ Guido van Rossum%BDFL%Python%http://www.python.org/~guido/
+ Larry Wall% %Perl%http://www.wall.org/~larry/
+
+The ``join`` command joins the two files, based on the common field present in both the files, which is the name, in this case.
+
+The ``-t`` option again specifies the delimiting character. Unless that is specified, join assumes that the fields are separated by spaces.
+
+Note that, for ``join`` to work, the common field should be in the same order in both the files. If this is not so, you could use ``sort``, to sort the files on the common field and then join the files. In the above example, we have the common field to be the first column in both the files. If this is not the case we could use the ``-1`` and ``-2`` options to specify the field to be used for joining the files.
+::
+
+ $ join -2 2 stalwarts.txt stalwarts2.txt -t %
+ Richard Stallman%rms%GNU Project%http://www.stallman.org
+ Eric Raymond%ESR%Jargon File%http://www.catb.org/~esr/
+ Ian Murdock% %Debian%http://ianmurdock.com/
+ Lawrence Lessig% %Creative Commons%http://lessig.org
+ Linus Torvalds% %Linux Kernel%http://torvalds-family.blogspot.com/
+ Guido van Rossum%BDFL%Python%http://www.python.org/~guido/
+ Larry Wall% %Perl%http://www.wall.org/~larry/
+
+
+Generating a word frequency list
+================================
+
+Now, let us use the tools we have learnt to use, to generate a word frequency list of a text file. We shall use the free text of Alice in Wonderland.
+
+The basic steps to achieve this task would be -
+
+1. Eliminate the punctuation and spaces from the document.
+2. Generate a list of words.
+3. Count the words.
+
+We first use ``grep`` and some elementary ``regex`` to eliminate the non-alpha-characters.
+::
+
+ $ grep "[A-Za-z]*" alice-in-wonderland.txt
+
+This outputs all the lines which has any alphabetic characters on it. This isn't of much use, since we haven't done anything with the code. We only require the alphabetic characters, without any of the other junk. ``man grep`` shows us the ``-o`` option for outputting only the text which matches the regular expression.
+::
+
+ $ grep "[A-Za-z]*" -o alice-in-wonderland.txt
+
+Not very surprisingly, we have all the words, spit out in the form of a list! Now that we have a list of words, it is quite simple to count the occurrences of the words. You would've realized that we can make use of ``sort`` and ``uniq`` commands. We pipe the output from the ``grep`` to the ``sort`` and then pipe it's output to ``uniq``.
+::
+
+ $ grep "[A-Za-z]*" -o alice-in-wonderland.txt | sort | uniq -c
+
+Notice that you get the list of all words in the document in the alphabetical order, with it's frequency written next to it. But, you might have observed that Capitalized words and lower case words are being counted as different words. We therefore, replace all the Upper case characters with lower case ones, using the ``tr`` command.
+::
+
+ $ grep "[A-Za-z]*" -o alice-in-wonderland.txt | tr 'A-Z' 'a-z' | sort | uniq -c
+
+Now, it would also be nice to have the list ordered in the decreasing order of the frequency of the appearance of the words. We sort the output of the ``uniq`` command with ``-n`` and ``-r`` options, to get the desired output.
+::
+
+ $ grep "[A-Za-z]*" -o alice-in-wonderland.txt | tr 'A-Z' 'a-z' | sort | uniq -c | sort -nr
+
+Basic editing and editors
+=========================
+
+vim
+---
+Vim is a very powerful editor. It has a lot of commands, and all of them cannot be explained here. We shall try and look at a few, so that you can find your way around in vim.
+
+To open a file in vim, we pass the filename as a parameter to the ``vim`` command. If a file with that filename does not exist, a new file is created.
+::
+
+ $ vim first.txt
+
+To start inserting text into the new file that we have opened, we need to press the ``i`` key. This will take us into the *insert* mode from the *command* mode. Hitting the ``esc`` key, will bring us back to the *command* mode. There is also another mode of vim, called the *visual* mode which will be discussed later in the course.
+
+In general, it is good to spend as little time as possible in the insert mode and extensively use the command mode to achieve various tasks.
+
+To save the file, use ``:w`` in the command mode. From here on, it is understood that we are in the command mode, whenever we are issuing any command to vim.
+
+To save a file and continue editing, use ``:w FILENAME``
+The file name is optional. If you do not specify a filename, it is saved in the same file that you opened. If a file name different from the one you opened is specified, the text is saved with the new name, but you continue editing the file that you opened. The next time you save it without specifying a name, it gets saved with the name of the file that you initially opened.
+
+To save file with a new name and continue editing the new file, use ``:saveas FILENAME``
+
+To save and quit, use ``:wq``
+
+To quit, use ``:q``
+
+To quit without saving, use ``:q!``
+
+Moving around
+~~~~~~~~~~~~~
+
+While you are typing in a file, it is in-convenient to keep moving your fingers from the standard position for typing to the arrow keys. Vim, therefore, provides alternate keys for moving in the document. Note again that, you should be in the command mode, when issuing any commands to vim.
+
+The basic cursor movement can be achieved using the keys, ``h`` (left), ``l`` (right), ``k`` (up) and ``j`` (down).
+::
+
+ ^
+ k
+ < h l >
+ j
+ v
+
+Note: Most commands can be prefixed with a number, to repeat the command. For instance, ``10j`` will move the cursor down 10 lines.
+
+Moving within a line
+++++++++++++++++++++
+
++----------------------------------------+---------+
+| Cursor Movement | Command |
++========================================+=========+
+| Beginning of line | ``0`` |
++----------------------------------------+---------+
+| First non-space character of line | ``^`` |
++----------------------------------------+---------+
+| End of line | ``$`` |
++----------------------------------------+---------+
+| Last non-space character of line | ``g_`` |
++----------------------------------------+---------+
+
+Moving by words and sentences
++++++++++++++++++++++++++++++
++------------------------------+---------+
+| Cursor Movement | Command |
++==============================+=========+
+| Forward, word beginning | ``w`` |
++------------------------------+---------+
+| Backward, word beginning | ``b`` |
++------------------------------+---------+
+| Forward, word end | ``e`` |
++------------------------------+---------+
+| Backward, word end | ``ge`` |
++------------------------------+---------+
+| Forward, sentence beginning | ``)`` |
++------------------------------+---------+
+| Backward, sentence beginning | ``(`` |
++------------------------------+---------+
+| Forward, paragraph beginning | ``}`` |
++------------------------------+---------+
+| Backward, paragraph beginning| ``{`` |
++------------------------------+---------+
+
+More movement commands
+++++++++++++++++++++++
++---------------------------------+------------+
+| Cursor Movement | Command |
++=================================+============+
+| Forward by a screenful of text | ``C-f`` |
++---------------------------------+------------+
+| Backward by a screenful of text | ``C-b`` |
++---------------------------------+------------+
+| Beginning of the screen | ``H`` |
++---------------------------------+------------+
+| Middle of the screen | ``M`` |
++---------------------------------+------------+
+| End of the screen | ``L`` |
++---------------------------------+------------+
+| End of file | ``G`` |
++---------------------------------+------------+
+| Line number ``num`` | ``[num]G`` |
++---------------------------------+------------+
+| Beginning of file | ``gg`` |
++---------------------------------+------------+
+| Next occurrence of the text | ``*`` |
+| under the cursor | |
++---------------------------------+------------+
+| Previous occurrence of the text | ``#`` |
+| under the cursor | |
++---------------------------------+------------+
+
+Note: ``C-x`` is ``Ctrl`` + ``x``
+
+The visual mode
+~~~~~~~~~~~~~~~
+The visual mode is a special mode that is not present in the original vi editor. It allows us to highlight text and perform actions on it. All the movement commands that have been discussed till now work in the visual mode also. The editing commands that will be discussed in the future work on the visual blocks selected, too.
+
+Editing commands
+~~~~~~~~~~~~~~~~
+
+The editing commands usually take the movements as arguments. A movement is equivalent to a selection in the visual mode. The cursor is assumed to have moved over the text in between the initial and the final points of the movement. The motion or the visual block that's been highlighted can be passed as arguments to the editing commands.
+
++-------------------------+---------+
+| Editing effect | Command |
++=========================+=========+
+| Cutting text | ``d`` |
++-------------------------+---------+
+| Copying/Yanking text | ``y`` |
++-------------------------+---------+
+| Pasting copied/cut text | ``p`` |
++-------------------------+---------+
+
+The cut and copy commands take the motions or visual blocks as arguments and act on them. For instance, if you wish to delete the text from the current text position to the beginning of the next word, type ``dw``. If you wish to copy the text from the current position to the end of this sentence, type ``y)``.
+
+Apart from the above commands, that take any motion or visual block as an argument, there are additional special commands.
+
++----------------------------------------+---------+
+| Editing effect | Command |
++========================================+=========+
+| Cut the character under the cursor | ``x`` |
++----------------------------------------+---------+
+| Replace the character under the | ``ra`` |
+| cursor with ``a`` | |
++----------------------------------------+---------+
+| Cut an entire line | ``dd`` |
++----------------------------------------+---------+
+| Copy/yank an entire line | ``yy`` |
++----------------------------------------+---------+
+
+Note: You can prefix numbers to any of the commands, to repeat them.
+
+Undo and Redo
+~~~~~~~~~~~~~
+You can undo almost anything using ``u``.
+
+To undo the undo command type ``C-r``
+
+Searching and Replacing
+~~~~~~~~~~~~~~~~~~~~~~~
+
++-----------------------------------------+---------+
+| Finding | Command |
++=========================================+=========+
+| Next occurrence of ``text``, forward |``\text``|
++-----------------------------------------+---------+
+| Next occurrence of ``text``, backward |``?text``|
++-----------------------------------------+---------+
+| Search again in the same direction | ``n`` |
++-----------------------------------------+---------+
+| Search again in the opposite direction | ``N`` |
++-----------------------------------------+---------+
+| Next occurrence of ``x`` in the line | ``fx`` |
++-----------------------------------------+---------+
+| Previous occurrence of ``x`` in the line| ``Fx`` |
++-----------------------------------------+---------+
+
++---------------------------------------+------------------+
+| Finding and Replacing | Command |
++=======================================+==================+
+| Replace the first instance of ``old`` |``:s/old/new`` |
+| with ``new`` in the current line. | |
++---------------------------------------+------------------+
+| Replace all instances of ``old`` |``:s/old/new/g`` |
+| with ``new`` in the current line. | |
++---------------------------------------+------------------+
+| Replace all instances of ``old`` |``:s/old/new/gc`` |
+| with ``new`` in the current line, | |
+| but ask for confirmation each time. | |
++---------------------------------------+------------------+
+| Replace the first instance of ``old`` |``:%s/old/new`` |
+| with ``new`` in the entire file. | |
++---------------------------------------+------------------+
+| Replace all instances of ``old`` |``:%s/old/new/g`` |
+| with ``new`` in the entire file. | |
++---------------------------------------+------------------+
+| Replace all instances of ``old`` with |``:%s/old/new/gc``|
+| ``new`` in the entire file but ask | |
+| for confirmation each time. | |
++---------------------------------------+------------------+
+
+SciTE
+-----
+
+SciTE is a *source code* editor, that has a feel similar to the commonly used GUI text editors. It has a wide range of features that are extremely useful for a programmer, editing code. Also it aims to keep configuration simple, and the user needs to edit a text file to configure SciTE to his/her liking.
+
+Opening, Saving, Editing files with SciTE is extremely simple and trivial. Knowledge of using a text editor will suffice.
+
+SciTE can syntax highlight code in various languages. It also has auto-indentation, code-folding and other such features which are useful when editing code.
+
+SciTE also gives you the option to (compile and) run your code, from within the editor.
+
+Personalizing your Environment
+==============================
+
+.bashrc
+-------
+What would you do, if you want bash to execute a particular command each time you start it up? For instance, say you want the current directory to be your Desktop instead of your home folder, each time bash starts up. How would you achieve this? Bash reads and executes commands in a whole bunch of files called start-up files, when it starts up.
+
+When bash starts up as an interactive login shell, it reads the files ``/etc/profile``, ``~/.bash_profile``, ``~/.bash_login``, and ``~/.profile`` in that order.
+
+When it is a shell that is not a login shell, ``~/.bashrc`` is read and the commands in it are executed. This can be prevented using the ``--norc`` option. To force bash to use another file, instead of the ``~/.bashrc`` file on start-up, the ``--rcfile`` option may be used.
+
+Now, you know what you should do, to change the current directory to you Desktop. Just put a ``cd ~/Desktop`` into your ``~/.bashrc`` and you are set!
+
+This example is quite a simple and lame one. The start-up files are used for a lot more complex things than this. You could set (or unset) aliases and a whole bunch of environment variables in the ``.bashrc``. We shall look at them, in the next section where we look at environment variables and ``set`` command.
+
+
+.vimrc
+------
+``.vimrc`` is a file similar to ``.bashrc`` for vim. It is a start-up file that vim reads and executes, each time it starts up. The options that you would like to be set every time you use vim, are placed in the ``.vimrc`` file, so that they are automatically set each time vim starts. The recommended place for having your ``.vimrc`` is also your home directory.
+
+The file ``/etc/vimrc`` is the global config file and shouldn't usually be edited. You can instead edit the ``~/.vimrc`` file that is present in your home folder.
+
+There are a whole bunch of variables that you could set in the ``.vimrc`` file. You can look at all the options available, using the ``:set all`` command in vim. You could use the ``:help option_name`` to get more information about the option that you want to set. Once you are comfortable with what you want to set a particular variable to, you could add it to ``.vimrc``. You should also look at ``:help vimrc`` for more info on the ``.vimrc`` file. If you already have a ``.vimrc`` file, you can edit it from within vim, using ``:e $MYVIMRC`` command. We shall look at some of the most commonly used options.
+
++----------------------------------+-----------------------------------------------------------------------------------+
+|Command | Vim action |
++==================================+===================================================================================+
+|``set nocompatible`` | Explicitly disable compatibility with vi |
++----------------------------------+-----------------------------------------------------------------------------------+
+|``set backspace=indent,eol,start``| In the insert mode, vim allows the backspace key to delete white spaces at the |
+| | start of line, line breaks and the character before which insert mode started. |
++----------------------------------+-----------------------------------------------------------------------------------+
+|set autoindent | Vim indents a new line with the same indentation of the previous line. |
++----------------------------------+-----------------------------------------------------------------------------------+
+|set backup | Vim keeps a backup copy of a file when overwriting it. |
++----------------------------------+-----------------------------------------------------------------------------------+
+|set history=50 | Vim keeps 50 commands and 50 search patterns in the history. |
++----------------------------------+-----------------------------------------------------------------------------------+
+|set ruler | Displays the current cursor position in the lower right corner of the vim window. |
++----------------------------------+-----------------------------------------------------------------------------------+
+|set showcmd | Displays the incomplete command in the lower right corner. |
++----------------------------------+-----------------------------------------------------------------------------------+
+|set incsearch | Turns on incremental searching. Displays search results while you type. |
++----------------------------------+-----------------------------------------------------------------------------------+
+
+You can see the effect of the changes made to your ``.vimrc`` file by restarting vim. If you want to see the changes that you made to your ``.vimrc`` file immediately, you could source the file from within vim.
+
+If the ``.vimrc`` file has been sourced when this instance of vim was started, you could just resource the file again::
+ :so $MYVIMRC
+
+If you just created the ``.vimrc`` file or it was not sourced when you stared this instance of vim, just replace the ``$MYVIMRC`` variable above, with the location of the ``.vimrc`` file that you created/edited.
+
+Subshells and ``source``
+========================
+
+A subshell is just a separate instance of the shell which is a child process of the shell that launches it. Bash creates a subshell in various circumstances. Creation of subshells allows the execution of various processes simultaneously.
+
+ * When an external command is executed, a new subshell is created. Any built-in commands of bash are executed with int the same shell, and no new subshell is started. When an external command is run, the bash shell copies itself (along with it's environment) creating a subshell and the process is changed to the external command executed. The subshell is a child process of this shell.
+
+ * Any pipes being used, create a subshell. The commands on the input and output ends of the pipe are run in different subshells.
+
+ * You could also, explicitly tell bash to start a subshell by enclosing a list of commands between parentheses. Each of the commands in the list is executed within a single new subshell.
+
+To avoid creating a subshell, when running a shell script, you could use the ``source`` command.
+::
+
+ $ source script.sh
+
+This will run the ``script.sh`` within the present shell without creating a subshell. The ``.`` command is an alias for the source command. ``. script.sh`` is therefore equivalent to ``source script.sh``.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/ult/ult_module_plan.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,98 @@
+Module 1: Using Linux Tools
+============================
+
+Module Objectives
+----------------------
+
+After successfully completing this module a participant will be able to:
+
+* Understand the design philosophy of \*nix {U}
+* Use Linux as their day-to-day operating system {Ap}
+* Use the text processing tools such as 'grep', 'tr' {Ap}
+* Write and execute (bash) shell scripts {Ap}
+* Use a text editor comfortably {Ap}
+
+Suggested Reading
+-----------------------
+
+(1) "In the beginning..." by Neal Stephenson
+(2) "The Unix Programming Environment" by Kerninghan and Pike
+
+**Initial Session Plan**
+
++---------+---------------------------------+---------+
+| Session | Topic | Duration|
++=========+=================================+=========+
+| 1 | Introduction to the Course | 5 mt |
+| | | |
+| | Historical background and | 10 mts |
+| | implications. Why Unix? | |
+| | | |
+| | Getting started–logging in; *ls,| 10 mts |
+| | date, who, cd, mkdir* | |
+| | | |
+| | Getting help: *apropos, man, | 10 mts |
+| | info* | |
+| | | |
+| | Basic file handling: *cp, mv, | 10 mts |
+| | rm* | |
+| | | |
+| | First session buffer | 5 mts |
++---------+---------------------------------+---------+
+| 2 | Command line arguments | 5 mts |
+| | | |
+| | Basic text processing: *head, | 15 mts |
+| | tail, cut, paste* | |
+| | | |
+| | Shell meta characters | 10 mts |
+| | | |
+| | Looking at files: *cat, less* | 5 mts |
+| | | |
+| | Directory structure: *man hier, | 5 mts |
+| | ls -l* | |
+| | | |
+| | Permissions and ownership, | 10 mts |
+| | *chmod, chown* | |
++---------+---------------------------------+---------+
+| 3 | Redirection and Piping | 10 mts |
+| | | |
+| | More text processing:*grep, tr* | 10 mts |
+| | | |
+| | Elementary regex: . ? * ^ $ [ ] | 15 mts |
+| | | |
+| | One liners: show lines n to m, | 15 mts |
+| | show directories | |
++---------+---------------------------------+---------+
+| 4 | More text processing: *join, | 10 mts |
+| | sprt, uniq* | |
+| | | |
+| | Generating a word frequency list| 10 mts |
+| | | |
+| | Basic editing and editors : vim,| 10 mts |
+| | scite | |
+| | | |
+| | Personalising your environment: | 10 mts |
+| | *.bashrc, .vimrc* | |
+| | | |
+| | Subshells and *source~* | 10 mts |
++---------+---------------------------------+---------+
+| 5 | More tools: *tar, zip, diff, | 25 mts |
+| | cmp, comm* | |
+| | | |
+| | Environment variables, *set* | 10 mts |
+| | | |
+| | Writing simple shell scripts | 15 mts |
++---------+---------------------------------+---------+
+| 6 | Control structures and | 20 mts |
+| | operators in bash | |
+| | | |
+| | Writing shell scripts | 30 mts |
++---------+---------------------------------+---------+
+| 7 | Functions in bash scripts | 20 mts |
+| | | |
+| | Assessment Test | 30 mts |
++---------+---------------------------------+---------+
+
+*total session time = 350 mts*
+
+*buffer time = 10 mts*
Binary file sttp/versionControl/clone.png has changed
Binary file sttp/versionControl/dongwoo-Hg-120dpi.png has changed
Binary file sttp/versionControl/glog-2.png has changed
Binary file sttp/versionControl/glog.png has changed
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/versionControl/handOut.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,702 @@
+===============
+Version Control
+===============
+
+Introduction
+============
+
+The following words are from a blogpost "http://karlagius.com/2009/01/09/version-control-for-the-masses/"
+
+"Version control is one of those weird, geeky things that never really gained much ground in non-geek fields, despite the fact that it’s blindingly useful.
+
+Version control (or source control) is nothing more arcane than keeping copies of ones work as one make changes to it. On the surface, it’s all straight-forward; make a copy of every file before making any changes to it. That way, if something seriously messes up, one can always fall back to something that worked before, or at least compare the broken copy with one that used to work so one can figure out where it went off kilter. Accidentally deleted half of thesis and closed the word processor? No problem – out comes the backup."
+
+Now, in the real world, it’s not so easy. One probably cooks up their own version control system without realizing it had such a geeky name. For instances files with names oldxxxxxx.py and latestxxxxxx.py. Every time to make some change in a file, one save it with different name then the original one. Luckily there are like, loads of version control systems out there to do this heavy lifting.
+
+Why Use Version Control
+=======================
+
+One of idea behind Version Control Tools was to build onto very first step which can be creating a empty file, or writing a first buggy program for assignment, rather then simply loose it. So here are some reasons why is automated version control needed:
+
+ - It will track the history and evolution of a project, so one don't have to do it manually. It allows to track what changes where made, when were they made, by whom and why.
+ - For a team of people working on same project, revision control software makes it easier to collaborate. For example, when people more or less simultaneously make potentially incompatible changes, the software will help them to identify and resolve those conflicts.
+ - It can help to recover from mistakes. If a change made at some moment of time, turns out to be in error in future, one can revert to an earlier version of one or more files. In fact, a really good revision control tool will even help in efficiently figure out exactly when a problem was introduced.
+
+Most of these reasons are equally valid for the project having one man show, or hundred people. Besides projects, even it can be used to maintain assignments related to one particular subject/course, it will help manage things in way much better way. These tools can be used for better *resources management*. All codes, documents, presentation, assignments related to one course maintained in such a inventory can help avoiding accidental lose of data(deletion) and Internet hosting for version control will make the work immune to local hard-disk crash, unless hosting crashes itself.
+
+Some of Version Control Tools available and used widely are:
+
+ - cvs (Concurrent Version System)
+ - svn (Subversion)
+ - hg (Mercurial)
+ - bzr (Bazaar)
+ - git
+
+Each of above mentioned tools have sets of feature which it offers in unique way. For this session we are going to concentrate on hg (mercurial). After covering the basics of hg, one can easily try other tools, and use what-ever he/she is most comfortable with.
+
+Learning the Lingo
+==================
+
+Each Version Control uses its own nomenclature for more or less the same features. Here are some of terms which are going to used through out the rest of session:
+
+Basic Setup
+-----------
+
+ Repository(repo):
+ The database/folder storing the files.
+ Server:
+ The computer storing the repo.
+ Client:
+ The computer connecting to the repo.
+ Working Set/Working Copy:
+ Your local directory of files, where you make changes. This is what is present on client side.
+ Trunk/Main:
+ The “primary” location for code in the repo. Think of code as a family tree — the “trunk” is the main line. This is generally what is present on server.
+
+Basic Actions
+-------------
+
+ Add:
+ Put a file into the repo for the first time, i.e. begin tracking it with Version Control.
+ Revision:
+ What version a file is on.
+ Head/Tip:
+ The latest revision of the repo.
+ Check out:
+ Initial download of repo onto machine.
+ Commit:
+ Upload a file to repository(if it has changed). The file gets a new revision number, and people can “check out” the latest one.
+ Checking Message:
+ A short message describing what was changed.
+ Change log/History:
+ A list of changes made to a file since it was created.
+ Update/Sync:
+ Synchronize local files with the latest from the repository on server. This get the latest revisions of all files.
+ Revert:
+ Throw away the local changes and reload the latest version from the repository.
+
+Advanced Actions:
+-----------------
+
+ Branch:
+ Create a separate copy of a file/folder for private use (bug fixing, testing, etc).
+ Diff/Change:
+ Finding the differences between two files. Useful for seeing what changed between revisions.
+ Merge (or patch):
+ Apply the changes from one file to another, to bring it up-to-date.
+ Conflict:
+ When pending changes to a file contradict each other (both changes cannot be applied).
+ Resolve:
+ Fixing the changes that contradict each other and checking in the correct version.
+
+Types of Version Control:
+-------------------------
+
+Based on how source/code management is carried out in a tool there are two categories of Version Control Systems(VCS):
+
+ - Centralized VCS:
+ In this kind of system all the revision control functions are performed on a shared server. If two developers try to change the same file at the same time, without some method of managing access the developers may end up overwriting each other's work. Centralized revision control systems solve this problem in one of two different "source management models": file locking and version merging. Both svn and cvs follows this kind of management.
+
+ - Distributed VCS:
+ In a distributed model, every developer has their own repo. Diffs, commits, and reverts are all done locally, one needs Internet only to share the changes with others. It makes work faster, handles branching and merging in better way, with less management. hg, bzr and git uses this work flow.
+
+Get Going with Hg:
+==================
+
+Why hg?
+-------
+
+ - It is easy to learn and use.
+ - It is lightweight.
+ - It scales excellently.
+ - It is based on Python.
+
+A small point to notice here, hg cant track binary files for changes, one can add them to repo, but wont be able to track changes made to it. And hg considers, odt, pdf files as binary.
+
+Getting Started:
+----------------
+
+Following command tells the version of hg installed on machine: ::
+
+ $hg version
+
+ Mercurial Distributed SCM (version 1.1.2)
+ Copyright (C) 2005-2008 Matt Mackall <mpm@selenic.com> and others
+ This is free software; see the source for copying conditions. There is NO
+ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+Built-in help, Mercurial provides a built-in help system. Following command will print a brief list of commands, along with a description of what each does. ::
+
+ $hg help
+
+ Mercurial Distributed SCM
+ list of commands:
+ add add the specified files on the next commit
+ addremove -----------------------
+
+For specific command, just follow the command name after the help. ::
+
+ $hg help diff
+ hg diff [OPTION]... [-r REV1 [-r REV2]] [FILE]...
+
+ diff repository (or selected files)
+ Show differences between revisions for the specified files.
+ Differences between files are shown using the unified diff format.
+ NOTE:____________
+
+Let there be Repository:
+------------------------
+
+In Mercurial, everything happens inside a repository. The repository for a project contains all of the files that “belong to” that project, along with a historical record of the project's files. A repository is simply a directory tree in file-system that Mercurial treats as special.
+
+There can be two ways to create a repo, either getting local copy for existing repo available on Internet or machine, or creating a new repo. For getting already existing repo hg uses command *"clone"* ::
+
+ $hg clone http://hg.serpentine.com/tutorial/hello localCopyhello
+
+ requesting all changes
+ adding changesets
+ adding manifests
+ adding file changes
+ added 5 changesets with 5 changes to 2 files
+ updating working directory
+ 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+
+If clone succeeded, there would be a local directory called localCopyhello, with some files: ::
+
+ $ls localCopyhello/
+ hello.c Makefile
+
+Every Mercurial repository is complete, self-contained, and independent. It contains its own private copy of a project's files and history.
+
+To start a new repository use *hg init*: ::
+
+ $ mkdir Fevicol
+ $ cd Fevicol/
+ $ echo "print 'Yeh Fevicol ka Majboot jod hai'" > feviStick.py
+ $ ls -a
+ . .. feviStick.py
+ $ hg init
+ $ ls -a
+ . .. feviStick.py .hg
+
+*.hg* directory indicates that this new dir is now a repo.This is where Mercurial keeps all of its metadata for the repository.The contents of the .hg directory and its subdirectories are private to Mercurial. Rest all files are for the user to use them as they pleases.
+
+Creating a branch of existing local repo is very easy via hg using clone command: ::
+
+ $ hg clone localCopyhello newCopy
+ updating working directory
+ 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+
+newCopy is exact copy of already existing repo. And this command can be used to create branch of locally created repo also: ::
+
+ $ hg clone Fevicol Fevicol-pull
+ updating working directory
+ 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+
+These local branches can prove really handy at times. It allows keep multiple copies of local branch for different purposes, say for debugging, testing, working version.
+
+History or Logs:
+----------------
+
+For the new repo created, first thing which can be tried is to check the logs/history. What changes were made and when and why, answers to all those questions are stored in logs safely. So for the the cloned repo the history can be viewed using command *"log"* (following commands are wrt localCopyhello repo). ::
+
+ $hg log
+ changeset: 4:2278160e78d4
+ tag: tip
+ user: Bryan O'Sullivan <bos@serpentine.com>
+ date: Sat Aug 16 22:16:53 2008 +0200
+ summary: Trim comments.
+
+ changeset: 3:0272e0d5a517
+ user: Bryan O'Sullivan <bos@serpentine.com>
+ date: Sat Aug 16 22:08:02 2008 +0200
+ summary: Get make to generate the final binary from a .o file.
+
+ changeset: 2:fef857204a0c
+ user: Bryan O'Sullivan <bos@serpentine.com>
+ date: Sat Aug 16 22:05:04 2008 +0200
+ summary: Introduce a typo into hello.c.
+
+ changeset: 1:82e55d328c8c
+ user: mpm@selenic.com
+ date: Fri Aug 26 01:21:28 2005 -0700
+ summary: Create a makefile
+
+ changeset: 0:0a04b987be5a
+ user: mpm@selenic.com
+ date: Fri Aug 26 01:20:50 2005 -0700
+ summary: Create a standard "hello, world" program
+
+By default, this command prints a brief paragraph of output for each change to the project that was recorded.The fields in a record of output from hg log are as follows:
+
+ - changeset: This field has the format of a number, followed by a colon, followed by a hexadecimal (or hex) string. These are identifiers for the changeset. The hex string is a unique identifier: the same hex string will always refer to the same changeset in every copy of this repository.
+ - user: The identity of the person who created the changeset.
+ - date: The date and time on which the changeset was created, and the timezone in which it was created.
+ - summary: The first line of the text message that the creator of the changeset entered to describe the changeset.
+ - tag: A tag is another way to identify a changeset, by giving it an easy-to-remember name.
+
+To narrow the output of hg log down to a single revision, use the -r (or --rev) option. ::
+
+ $hg log -r 3
+ changeset: 3:0272e0d5a517
+ user: Bryan O'Sullivan <bos@serpentine.com>
+ date: Sat Aug 16 22:08:02 2008 +0200
+ summary: Get make to generate the final binary from a .o file.
+
+*range notation* can be used to get history of several revisions without having to list each one. ::
+
+ $ hg log -r 2:4
+ changeset: 2:fef857204a0c
+ user: Bryan O'Sullivan <bos@serpentine.com>
+ date: Sat Aug 16 22:05:04 2008 +0200
+ summary: Introduce a typo into hello.c.
+
+ changeset: 3:0272e0d5a517
+ user: Bryan O'Sullivan <bos@serpentine.com>
+ date: Sat Aug 16 22:08:02 2008 +0200
+ summary: Get make to generate the final binary from a .o file.
+
+ changeset: 4:2278160e78d4
+ tag: tip
+ user: Bryan O'Sullivan <bos@serpentine.com>
+ date: Sat Aug 16 22:16:53 2008 +0200
+ summary: Trim comments.
+
+The hg log command's -v (or --verbose) option gives you this extra detail. ::
+
+ $ hg log -v -r 3
+ changeset: 3:0272e0d5a517
+ user: Bryan O'Sullivan <bos@serpentine.com>
+ date: Sat Aug 16 22:08:02 2008 +0200
+ files: Makefile
+ description:
+ Get make to generate the final binary from a .o file.
+
+Making Changes:
+---------------
+
+There is feviStick.py file in repo created above with name Fevicol. *status(alias st)* command prints the revision history of the specified files or the entire project::
+
+ $ cd Fevicol
+ $ hg log
+ $ hg status
+ ? feviStick.py
+
+"?" sign in front of file indicates that this file is not yet part of track record. *add* command is used to add new files to repo. ::
+
+ $ hg add feviStick.py
+ $ hg st
+ A feviStick.py
+
+So file is now part of repository(A symbol). Use *commit (alias ci)* command to make changes effective(this command would be explained in more details in later parts). ::
+
+ $ hg ci -u "Shantanu <shantanu@fossee.in>" -m "First commit."
+ $ hg log
+ changeset: 0:84f5e91f4de1
+ tag: tip
+ user: Shantanu <shantanu@fossee.in>
+ date: Fri Aug 21 23:37:13 2009 +0530
+ summary: First commit.
+
+Similar to add there are other commands available for file management in repo. *copy (alias cp)* command is used to mark files as copied for the next commit. ::
+
+ $ hg cp feviStick.py pidiLite.py
+ $ hg st
+ A pidiLite.py
+
+*rename(alias mv)* rename files; equivalent of copy + remove. *tip* command shows newest revision in the repository. ::
+
+ $ hg rename pidiLite.py feviCol.py
+ $ hg st
+ A feviCol.py
+ $ hg ci -u "Shantanu <shantanu@fossee.in>" -m "Renamed pidiLite.py."
+ $ hg tip
+ changeset: 1:d948fb4137c5
+ tag: tip
+ user: Shantanu <shantanu@fossee.in>
+ date: Sat Aug 22 00:11:25 2009 +0530
+ summary: Renamed pidiLite.py.
+
+*remove* command is used to remove files from a repo. ::
+
+ $ hg remove feviCol.py
+ $ hg st
+ R feviCol.py
+
+R status of files denotes, file is marked as to be removed by the previous command *remove*. To add the file again to repo, one can use *revert* command, which restore individual files or dirs to an earlier state. ::
+
+ $ ls
+ feviStick.py
+ $ hg revert feviCol.py
+ $ ls
+ feviCol.py feviStick.py
+
+Sharing Changes:
+----------------
+
+Pulling from repo:
+~~~~~~~~~~~~~~~~~~
+
+As mentioned earlier that repositories in Mercurial are self-contained. This means that the changeset just created exists only in Fevicol repository and not in previously cloned Fevicol-pull. There are a few ways that can be used to propagate this change into other repositories. ::
+
+ $ hg clone Fevicol Fevicol-clone
+ updating working directory
+ 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+
+Or traverse into the any dir which is a working hg repo(using hg init) and pull command will download all changeset from main repo. ::
+
+ $ mkdir Fevicol-pull
+ $ cd Fevicol-pull
+ $ hg init
+ $ hg pull ../Fevicol
+ pulling from ../Fevicol
+ requesting all changes
+ adding changesets
+ adding manifests
+ adding file changes
+ added 2 changesets with 2 changes to 2 files
+ (run 'hg update' to get a working copy)
+
+*changeset* means a list of changes made to a file. In words of *hg help*, pull command is: ::
+
+ pull changes from the specified source
+
+ Pull changes from a remote repository to a local one.
+
+ This finds all changes from the repository at the specified path
+ or URL and adds them to the local repository. By default, this
+ does not update the copy of the project in the working directory.
+
+Some times, even before pulling changesets, one may need to see what changes would be pulled, Mercurial provides *hg incoming* to tell what changes *hg pull* would pull into repo, without actually pulling the changes. This command is really handy in case of avoiding unwanted changesets into the repo.
+
+With Mercurial, *hg pull* does not(by default) touch the working directory. Instead there is *hg up (alias update, co, checkout)* command to do this. ::
+
+ $ cd Fevicol-pull
+ $ ls -a
+ . .. .hg
+ $ hg up
+ 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+ $ ls -a
+ . .. feviCol.py feviStick.py .hg
+
+To update to specific version, give a version number to the *hg update* command. ::
+
+ $ hg update 0
+ 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
+ $ hg parent
+ changeset: 0:84f5e91f4de1
+ user: Shantanu <shantanu@fossee.in>
+ date: Fri Aug 21 23:37:13 2009 +0530
+ summary: First commit.
+
+If no version number is specified *hg up* will update to the tip version. Version number of hg starts from 0. Compare *hg parent* output to the one before doing update to see the difference.
+
+Making Changes:
+~~~~~~~~~~~~~~~
+
+After getting the desired version of local repo, one can make changes as he/she needs and then make them available(share) for others. For these operations we will be working in Fevicol-clone repo which we created earlier. It's often good practice to keep a “pristine” copy of a remote repository around, which you can then make temporary clones of to create sandboxes for each task you want to work on. ::
+
+ $ cd Fevicol-clone/
+ $ cat feviStick.py
+ print 'Yeh Fevicol ka Majboot jod hai'
+
+This tagline is correct for feviCol.py but for feviStick.py it should be different. ::
+
+ $ echo "print 'Ab no more Chip Chip'" > feviStick.py
+ $ cat feviStick.py
+ print 'Ab no more Chip Chip'
+ $ hg st
+ M feviStick.py
+
+Mercurial's hg status command will tell us what Mercurial knows about the files in the repository. 'M' sign in front of feviStick.py indicates that Mercurial has noticed change.
+
+It's somewhat helpful to know that feviStick.py was modified, but one might prefer to know exactly what changes were made to it. To do this, use the *hg diff* command. ::
+
+ $ hg diff
+ diff -r a7912d45f47c feviStick.py
+ --- a/feviStick.py Sun Aug 23 22:34:35 2009 +0530
+ +++ b/feviStick.py Sun Aug 23 22:47:49 2009 +0530
+ @@ -1,1 +1,1 @@
+ -print 'Yeh Fevicol ka Majboot jod hai'
+ +print 'Ab no more Chip Chip'
+
+We can modify files, build and test our changes, and use hg status and hg diff to review our changes, until we're satisfied with what we've done and arrive at a natural stopping point where we want to record our work in a new changeset. All the diffs prior to committing the changes would be done wrt earlier marked record.The hg commit command lets us create a new changeset.
+
+Mercurial records your name and address with each change that you commit, so that you and others will later be able to tell who made each change. Mercurial tries to automatically figure out a sensible username to commit the change with. When we try to use *hg commit* there are various ways by which one can specify User name, some of those are:
+
+ - Specify a -u option to the hg commit command on the command line, followed by a username.
+ - set HGUSER environment variable.
+ - Edit hgrc file present in .hg folder to set this property, add following lines to that file and Mercurial will read those parameters from that location. ::
+
+ [ui]
+ username = Firstname Lastname <email.address@example.net>
+
+For me the hgrc file looks like this: ::
+
+ [paths]
+ default = /home/baali/Fevicol
+ [ui]
+ username = Shantanu Choudhary <shantanu@fossee.in>
+
+Once this parameter is set, *hg commit* command drops us into a text editor, to enter a message that will describe the modifications we've made in this changeset. This is called the commit message. It will be a record for readers of what we did and why, and it will be printed by hg log after we've finished committing. ::
+
+ Changed tagline for feviStick.py.
+ HG: Enter commit message. Lines beginning with 'HG:' are removed.
+ HG: --
+ HG: user: Shantanu Choudhary <shantanu@fossee.in>
+ HG: branch 'default'
+ HG: changed feviStick.py
+
+This would be your default system editor(for me it is vim, one can set it also), where you can enter the log message in first line, once you are done with log message quit the editor using *[ESC] key ":wq"*.Once we've finished the commit, we can use the hg tip command to display the changeset we just created. ::
+
+ $ hg tip
+ changeset: 3:e1ab2aff4ddd
+ tag: tip
+ user: Shantanu Choudhary <shantanu@fossee.in>
+ date: Sun Aug 23 23:32:01 2009 +0530
+ summary: Changed tagline for feviStick.py.
+
+One can do above mentioned procedure using following one line command: ::
+
+ $ hg ci -u "Shantanu <shantanu@fossee.in>" -m "Changed tagline for feviStick.py."
+
+Sharing Changes:
+~~~~~~~~~~~~~~~~
+
+The *hg outgoing* command tells us what changes would be pushed into another repository. ::
+
+ $ hg outgoing ../Fevicol
+ comparing with ../Fevicol
+ searching for changes
+ changeset: 3:e1ab2aff4ddd
+ tag: tip
+ user: Shantanu Choudhary <shantanu@fossee.in>
+ date: Sun Aug 23 23:32:01 2009 +0530
+ summary: Changed tagline for feviStick.py.
+
+And the *hg push* command does the actual push. ::
+
+ $ hg push ../Fevicol
+ pushing to ../Fevicol
+ searching for changes
+ adding changesets
+ adding manifests
+ adding file changes
+ added 1 changesets with 1 changes to 1 files
+
+As with hg pull, the hg push command does not update the working directory in the repository that it's pushing changes into. One has to use hg update to populate the changes in desired repo. ::
+
+ $ cd ../Fevicol
+ $ hg tip
+ changeset: 3:e1ab2aff4ddd
+ tag: tip
+ user: Shantanu Choudhary <shantanu@fossee.in>
+ date: Sun Aug 23 23:32:01 2009 +0530
+ summary: Changed tagline for feviStick.py.
+ $ cat feviStick.py
+ print 'Yeh Fevicol ka Majboot jod hai'
+
+changesets are imported, but update is yet to be done. ::
+
+ $ hg up tip
+ 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+ $ $ cat feviStick.py
+ print 'Ab no more Chip Chip'
+
+Merging the Work:
+~~~~~~~~~~~~~~~~~
+
+This is next aspect of any version control, how to merge work done by various participants of project in a way that no one looses changes being made, and still remains updated. Here is simple case study which can help understanding why merging is required:
+
+Two persons, A and B are contributing on same project. Both starts from cloning the same online repo(lets say present state X), so that both have a working local repo. Now A edits one of file, commits the changes and pushes to the repo, hence changing the state of repo to Y, but B, have not updated his repo, makes a change in one of files and reaches to a different state Z. Now when A pulls repo from B, his repo will have multiple heads. This stage is clearly ambiguous, the repo of A is not consistent, it has multiple heads, and from here, whatever changes he makes can take whatsoever direction if it is not fixed, and hence A will have to merge changes so that everything becomes consistent again.
+
+Lets see how this work with working repo, we will use Fevicol and Fevicol-clone repositories created earlier. For now, the status of both repo is: ::
+
+ $ cd Fevicol-clone
+ $ hg tip
+ changeset: 3:e1ab2aff4ddd
+ tag: tip
+ user: Shantanu Choudhary <shantanu@fossee.in>
+ date: Sun Aug 23 23:32:01 2009 +0530
+ summary: Changed tagline for feviStick.py.
+
+The tagline for feviCol.py is not complete, so we make changes in that file in this repo. ::
+
+ $ echo "print 'Yeh Fevicol ka Majboot jod hai, tootega nahin'" > feviStick.py
+ $ hg st
+ M feviStick.py
+
+And commit the changes made ::
+
+ $ hg ci -u "Shantanu <shantanu@fossee.in>" -m "Updated tag line for feviCol.py."
+ $ hg st
+ $ hg tip
+ changeset: 4:caf986b15e05
+ tag: tip
+ user: Shantanu <shantanu@fossee.in>
+ date: Tue Aug 25 16:28:24 2009 +0530
+ summary: Updated tag line for feviCol.py.
+
+Now we will make some changes on Fevicol repo. We will add new file here ::
+
+ $ cd Fevicol
+ $ echo "print 'Jor laga ke hayyiya'" > firstAdd.py
+ $ hg st
+ ? firstAdd.py
+ $ hg add firstAdd.py
+ $ hg st
+ A firstAdd.py
+ $ hg ci -u "Shantanu <shantanu@fossee.in>" -m "Added firsAdd.py."
+ $ hg tip
+ changeset: 4:fadbd6492cc4
+ tag: tip
+ user: Shantanu <shantanu@fossee.in>
+ date: Tue Aug 25 16:46:24 2009 +0530
+ summary: Added firsAdd.py.
+
+So now we have two repo, who have different commit history and tree, now if we try to pull changes from one to another, this is how it goes(we are still in Fevicol repo): ::
+
+ $ hg pull ../Fevicol-clone
+ pulling from ../Fevicol-clone
+ searching for changes
+ adding changesets
+ adding manifests
+ adding file changes
+ added 1 changesets with 1 changes to 1 files (+1 heads)
+ (run 'hg heads' to see heads, 'hg merge' to merge)
+
+There we go, since both repo were on different track, hg pull command in last line gives some heading from here. *hg heads* command show current repository heads or show branch heads. ::
+
+ $ hg heads
+ changeset: 5:caf986b15e05
+ tag: tip
+ parent: 3:e1ab2aff4ddd
+ user: Shantanu <shantanu@fossee.in>
+ date: Tue Aug 25 16:28:24 2009 +0530
+ summary: Updated tag line for feviCol.py.
+
+ changeset: 4:fadbd6492cc4
+ user: Shantanu <shantanu@fossee.in>
+ date: Tue Aug 25 16:46:24 2009 +0530
+ summary: Added firsAdd.py.
+
+To get better understanding of what is going on hg have a tool known as *glog* which shows revision history alongside an ASCII revision graph. ::
+
+ $ hg glog
+ o changeset: 5:caf986b15e05
+ | tag: tip
+ | parent: 3:e1ab2aff4ddd
+ | user: Shantanu <shantanu@fossee.in>
+ | date: Tue Aug 25 16:28:24 2009 +0530
+ | summary: Updated tag line for feviCol.py.
+ |
+ | @ changeset: 4:fadbd6492cc4
+ |/ user: Shantanu <shantanu@fossee.in>
+ | date: Tue Aug 25 16:46:24 2009 +0530
+ | summary: Added firsAdd.py.
+ |
+ o changeset: 3:e1ab2aff4ddd
+ | user: Shantanu Choudhary <shantanu@fossee.in>
+ | date: Sun Aug 23 23:32:01 2009 +0530
+ | summary: Changed tagline for feviStick.py.
+ |
+ o changeset: 2:a7912d45f47c
+ | user: Shantanu <shantanu@fossee.in>
+ | date: Sun Aug 23 22:34:35 2009 +0530
+ | summary: Updated Content.
+ |
+ o changeset: 1:d948fb4137c5
+ | user: Shantanu <shantanu@fossee.in>
+ | date: Sat Aug 22 00:11:25 2009 +0530
+ | summary: Renamed pidiLite.py.
+ |
+ o changeset: 0:84f5e91f4de1
+ user: Shantanu <shantanu@fossee.in>
+ date: Fri Aug 21 23:37:13 2009 +0530
+ summary: First commit.
+
+To bring repo on single track/branch once again we will have to merge these two branches. Without merging them even hg update wont work for obvious reason of confusing track record. ::
+
+ $ hg up
+ abort: crosses branches (use 'hg merge' or 'hg update -C')
+
+*hg merge* command merge working directory with another revision. ::
+
+ $ hg merge
+ 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+ (branch merge, don't forget to commit)
+ $ hg tip
+ changeset: 5:caf986b15e05
+ tag: tip
+ parent: 3:e1ab2aff4ddd
+ user: Shantanu <shantanu@fossee.in>
+ date: Tue Aug 25 16:28:24 2009 +0530
+ summary: Updated tag line for feviCol.py.
+
+After merging two branches, until we commit the results of merge it will keep on showing two heads. ::
+
+ $ hg ci -u "Shantanu <shantanu@fossee.in>" -m "Merged branches of add and tag line."
+ $ hg heads
+ changeset: 6:edbe97209954
+ tag: tip
+ parent: 4:fadbd6492cc4
+ parent: 5:caf986b15e05
+ user: Shantanu <shantanu@fossee.in>
+ date: Tue Aug 25 17:06:03 2009 +0530
+ summary: Merged branches of add and tag line.
+
+Here is brief and meaningful output of glog ::
+
+ $ hg glog
+ @ changeset: 6:edbe97209954
+ |\ tag: tip
+ | | parent: 4:fadbd6492cc4
+ | | parent: 5:caf986b15e05
+ | | user: Shantanu <shantanu@fossee.in>
+ | | date: Tue Aug 25 17:06:03 2009 +0530
+ | | summary: Merged branches of add and tag line.
+ | |
+ | o changeset: 5:caf986b15e05
+ | | parent: 3:e1ab2aff4ddd
+ | | user: Shantanu <shantanu@fossee.in>
+ | | date: Tue Aug 25 16:28:24 2009 +0530
+ | | summary: Updated tag line for feviCol.py.
+ | |
+ o | changeset: 4:fadbd6492cc4
+ |/ user: Shantanu <shantanu@fossee.in>
+ | date: Tue Aug 25 16:46:24 2009 +0530
+ | summary: Added firsAdd.py.
+
+And we are back on track.
+
+Workflow:
+=========
+
+This is chain of steps which can be followed for working against a project that has a centralized copy, you may want to make sure you're up to date first. This means pulling its changes and then updating.
+
+For example: ::
+
+ $ hg pull
+ $ hg update
+
+This will grab the remote changes from the location you first cloned from. Then it will apply the changes. You can do this in one go with: ::
+
+ $ hg pull -u
+
+Now let's say you make some changes. You edit a file and you want to commit your change. You can do this with: ::
+
+ $ hg commit
+
+An editor will pop-up asking you to write a message describing your change. When you're done for the day, and you have required changesets sitting in your repository. Before pushing to upstream make sure to pull and update and merge branches if required, once everything looks okay and you have single track, push the changes, ::
+
+ $ hg push
+
+Suggested Reading:
+==================
+
+ * http://karlagius.com/2009/01/09/version-control-for-the-masses/
+ * http://betterexplained.com/articles/a-visual-guide-to-version-control/
+ * http://en.wikipedia.org/wiki/Revision_control
+ * http://hgbook.red-bean.com/
+ * http://betterexplained.com/articles/intro-to-distributed-version-control-illustrated/
+ * http://wiki.alliedmods.net/Mercurial_Tutorial
Binary file sttp/versionControl/main.png has changed
Binary file sttp/versionControl/mario.png has changed
Binary file sttp/versionControl/mercurial.jpeg has changed
Binary file sttp/versionControl/scenario.png has changed
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/versionControl/vcs.tex Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,786 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Version Control Systems
+%
+% Author: FOSSEE
+% Copyright (c) 2009, FOSSEE, IIT Bombay
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+\documentclass[14pt,compress]{beamer}
+
+\mode<presentation>
+{
+ \usetheme{Warsaw}
+ \useoutertheme{infolines}
+ \setbeamercovered{transparent}
+}
+
+\usepackage[english]{babel}
+\usepackage[latin1]{inputenc}
+%\usepackage{times}
+\usepackage[T1]{fontenc}
+
+% Taken from Fernando's slides.
+\usepackage{ae,aecompl}
+\usepackage{mathpazo,courier,euler}
+\usepackage[scaled=.95]{helvet}
+
+\definecolor{darkgreen}{rgb}{0,0.5,0}
+
+\usepackage{listings}
+\lstset{language=Python,
+ basicstyle=\ttfamily\bfseries,
+ commentstyle=\color{red}\itshape,
+ stringstyle=\color{darkgreen},
+ showstringspaces=false,
+ keywordstyle=\color{blue}\bfseries}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Macros
+\setbeamercolor{emphbar}{bg=blue!20, fg=black}
+\newcommand{\emphbar}[1]
+{\begin{beamercolorbox}[rounded=true]{emphbar}
+ {#1}
+ \end{beamercolorbox}
+}
+\newcounter{time}
+\setcounter{time}{0}
+\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}}
+
+\newcommand{\typ}[1]{\lstinline{#1}}
+
+\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} }
+
+%%% This is from Fernando's setup.
+% \usepackage{color}
+% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
+% % Use and configure listings package for nicely formatted code
+% \usepackage{listings}
+% \lstset{
+% language=Python,
+% basicstyle=\small\ttfamily,
+% commentstyle=\ttfamily\color{blue},
+% stringstyle=\ttfamily\color{orange},
+% showstringspaces=false,
+% breaklines=true,
+% postbreak = \space\dots
+% }
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Title page
+\title[Version Control Systems]{SEES: Version Control Systems}
+
+\author[FOSSEE] {FOSSEE}
+
+\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay}
+\date[]{}
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo}
+%\logo{\pgfuseimage{iitmlogo}}
+
+
+%% Delete this, if you do not want the table of contents to pop up at
+%% the beginning of each subsection:
+\AtBeginSubsection[]
+{
+ \begin{frame}<beamer>
+ \frametitle{Outline}
+ \tableofcontents[currentsection,currentsubsection]
+ \end{frame}
+}
+
+\AtBeginSection[]
+{
+ \begin{frame}<beamer>
+ \frametitle{Outline}
+ \tableofcontents[currentsection,currentsubsection]
+ \end{frame}
+}
+
+% If you wish to uncover everything in a step-wise fashion, uncomment
+% the following command:
+%\beamerdefaultoverlayspecification{<+->}
+
+%%\includeonlyframes{current,current1,current2,current3,current4,current5,current6}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DOCUMENT STARTS
+\begin{document}
+
+\begin{frame}
+ \maketitle
+\end{frame}
+
+% CREATING TOC
+\begin{frame}
+ \frametitle{Outline}
+ \tableofcontents
+ % You might wish to add the option [pausesections]
+\end{frame}
+
+%% There are some %$ used just to minimise the effect of $ sign used in lstlisting. In emacs it looks unhealthy.
+
+% Introduction to course-need of version control, history, options available.
+\section{Introduction}
+
+\begin{frame}
+ \frametitle{What is Version Control?}
+ \begin{block}{From a blog post}
+ ``Version control (or source control) is nothing more arcane than keeping copies of ones work as one make changes to it.''
+ \end{block}
+ \pause
+ \begin{block}{}
+ It is better to use these tools rather than wasting creativity to invent VCS which have files with names like \begin{color}{red}{prog1.py, prog2.py}\end{color} or \begin{color}{red}prog-old.py, prog.py.\end{color}
+ \end{block}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Motivation behind such tools}
+ \begin{itemize}
+ \item Track the history and evolution of a program.
+ \item To collaborate effectively on a project.
+ \item \begin{color}{red}``To err is Human''\end{color} \pause for recovery we have ``Version Control''
+ \end{itemize}
+\end{frame}
+
+%% Introduction to how logs are managed in VCS.
+%% A analogy in logs and day-to-day life?
+\begin{frame}[fragile]
+ \frametitle{How does it work?}
+ It can roughly be related to Computer/Video Games.
+ \begin{itemize}
+ \item We play games in stages.
+ \item We pass a stage/task- \begin{color}{red}we SAVE the game.\end{color}
+ \item We resume playing from there onwards.
+ \item In-case we want to replay or revisit some particular stage, we start from position we saved earlier.
+ \item Even we can change the course of play henceforth.
+ \end{itemize}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Better way to say:}
+ \begin{center}
+ \includegraphics[height=2.5in,width=2.5in, interpolate=true]{mario}
+ \end{center}
+ \emphbar{VCS provides power to save and resume from a stage.}
+\end{frame}
+
+\begin{frame}
+ \frametitle{How is it done?}
+ \begin{itemize}
+ \item It keeps track of changes you make to a file. You can improvise, revisit, and amend.
+ \item All procedure is logged/recorded, so you and others can follow the development cycle.
+ \end{itemize}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Do we really need this?}
+ \emphbar{For team of people working remotely(even different computers/machines) on a project, use of version control is inevitable!}
+ \vspace{0.15in}
+ \emphbar{For single person: managing projects and assignments becomes easy}
+ \vspace{0.15in}
+ \pause
+ \emphbar{\color{red}{It is a good habit!}}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Whats on the menu!}
+ \begin{itemize}
+ \item cvs (Concurrent Version System)
+ \item svn (Subversion)
+ \item hg (Mercurial)
+ \item bzr (Bazaar)
+ \item git
+ \end{itemize}
+ \inctime{10}
+\end{frame}
+
+% Introduction to jargon
+\section{Learning the Lingo!}
+
+\begin{frame}
+ \frametitle{Common jargon: Basic setup}
+ \begin{itemize}
+ \item Repository(repo):\\
+ The folder with all files.
+ \item Server:\\
+ Machine with main inventory/repo.
+ \item Client:\\
+ Local machines with copy of main repo.
+ \end{itemize}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Actions}
+ \begin{itemize}
+ \item Add:\\
+ Adding file into the repo for the first time.
+ \item Version:\\
+ Version number(Die Hard 4.0).
+ \item Head/Tip:\\
+ Most recent revision/stage.
+ \item Check out/Clone:\\
+ Initial download of working copy.
+ \item Commit:\\
+ Saving(recording) a change.
+ \item Change log/History:\\
+ List of all past changes.
+ \end{itemize}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Actions cont...}
+ \begin{itemize}
+ \item Branch:\\
+ Separate local copy for bug fixing, testing.
+ \item Diff/Change:\\
+ Changes made in a file in two different versions.
+ \item Merge (or patch):\\
+ Appling the changes to file, to make it up-to-date.
+ \item Conflict:\\
+ When merging a file is not obvious.
+ \item Resolve:\\
+ Fixing the conflict manually.
+ \end{itemize}
+\end{frame}
+
+% Types of Version Controls
+\section{Types of VCS}
+
+\begin{frame}
+ \frametitle{Types:}
+ Based on ways of managing the repo there are two types of VCS:
+ \begin{itemize}
+ \item Centralized VCS\\
+ cvs, svn fall under this category.
+ \item Distributed VCS\\
+ hg, bzr, git follows this methodology.
+ \end{itemize}
+ \emphbar{We would be covering \typ{hg}}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Why hg?}
+ \includegraphics[height=.75in, interpolate=true]{mercurial}
+ \begin{itemize}
+ \item Easy to learn and use.
+ \item Lightweight.
+ \item Scales excellently.
+ \item Written in Python.
+ \end{itemize}
+ \inctime{10}
+\end{frame}
+
+% Initializing the repo, cloning, committing changes, pushing, pulling to repo.
+\section{Getting Started}
+
+\begin{frame}[fragile]
+ \frametitle{Getting comfortable:}
+ For checking \typ{hg} installation and its version try:
+ \begin{lstlisting}
+ $ hg version
+ \end{lstlisting}
+ To get broad help on \typ{hg} and commands available:
+ \begin{lstlisting}
+ $ man hg
+ $ hg help
+ \end{lstlisting}
+ To get help on particular \typ{hg} related option try:
+ \begin{lstlisting}
+ $ hg help diff
+ \end{lstlisting} %$
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Getting working/existing code base}
+ \typ{clone} is used to make a copy of an existing repository. It can be both local or remote.
+ \begin{lstlisting}
+$ hg clone
+ http://hg.serpentine.com/tutorial/hello
+ localCopyhello
+ \end{lstlisting}
+ And we get a local copy of this repository.
+ \begin{lstlisting}
+$ ls localCopyhello/
+hello.c Makefile
+ \end{lstlisting}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{To start track-record on existing files}
+ I have some files which I want to bring under version control. \typ{hg} provides \typ{init} command for this:
+ \begin{lstlisting}
+$ ls -a circulate/
+. .. lena.png pendulum.txt points.txt pos.txt sslc1.py sslc1.txt
+$ cd circulate/
+$ hg init
+$ ls -a
+. .. .hg lena.png pendulum.txt points.txt pos.txt sslc1.py sslc1.txt
+ \end{lstlisting}
+ \emphbar{\typ{.hg} directory keeps log of changes made henceforth.}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Starting fresh}
+ We can use \typ{init} to start a new repository also
+ \begin{lstlisting}
+$ mkdir Fevicol
+$ cd Fevicol/
+$ echo "print 'Yeh Fevicol ka majboot
+ jod hai'" > feviStick.py
+$ ls -a
+. .. feviStick.py
+$ hg init
+$ ls -a
+. .. feviStick.py .hg
+ \end{lstlisting}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Making copies: Branching}
+ All \typ{hg} repositories are self-contained, and independent which can be copied(cloned):
+ \begin{lstlisting}
+$ hg clone localCopyhello newCopy
+updating working directory
+2 files updated, 0 files merged,
+0 files removed, 0 files unresolved
+ \end{lstlisting}
+ or
+ \begin{lstlisting}
+$ hg clone Fevicol Fevicol-pull
+updating working directory
+0 files updated, 0 files merged,
+0 files removed, 0 files unresolved
+ \end{lstlisting}
+ \inctime{20}
+\end{frame}
+
+%% Should we here stress on how are distribute VCS have
+%% different approach then centralized ones? Maybe a pic
+%% or some other graphical representation.
+\begin{frame}[fragile]
+ \frametitle{Revisiting saved points:history/logs}
+ In \typ{hg}, the difference between consecutive stages is termed as changeset.\\
+ Once we have saved stages, we need a mechanism to review and access them, for that use \typ{log} command.
+ \begin{lstlisting}
+$ cd localCopyhello
+$ hg log
+ \end{lstlisting}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Understanding output}
+ The output provides following information:
+ \begin{itemize}
+ \item changeset: Identifiers for the changeset.
+ \item user: Person who created the changeset.
+ \item date: Date and time of creation of changeset.
+ \item summary: One line description.
+ \end{itemize}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{History/Logs cont...}
+ By default \typ{log} returns complete list of all changes. \\
+ For selective view try:
+\begin{lstlisting}
+$ hg log -r 3
+$ hg log -r 2:4
+\end{lstlisting}
+ tip/latest changes can be seen via:
+ \begin{lstlisting}
+$ hg tip
+ \end{lstlisting} %%$
+ \inctime{5}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Advancing through a stage:status}
+ We often need to add/delete some files from directory(repo). The structure keeps on evolving, and tools for handling them are needed.\\
+ We will use the Fevicol repo we created earlier.
+ \begin{lstlisting}
+$ cd Fevicol
+$ hg log
+$ hg st
+? feviStick.py
+ \end{lstlisting} %%$
+ \typ{st} (aka status) is command to show changed files in the working directory.\\
+\end{frame}
+
+%% track record is confusing for some. Duma have some doubts :(
+\begin{frame}[fragile]
+ \frametitle{Adding files}
+ "?" indicates that these file are aliens to track record.\\
+ \typ{add} command is available to add new files to present structure.
+ \begin{lstlisting}
+$ hg add feviStick.py
+$ hg st
+A feviStick.py
+ \end{lstlisting}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Saving present stage: committing}
+ \emphbar{This is equivalent to completing tasks, before reaching a stage where you want to save.}
+ \typ{hg} uses \typ{ci}(aka \typ{commit}) command to save changes. So after adding file, we have to commit it also:
+ \begin{lstlisting}
+$ hg ci -u "Shantanu <shantanu@fossee.in>"
+ -m "First commit."
+$ hg log
+changeset: 0:84f5e91f4de1
+tag: tip
+user: Shantanu <shantanu@fossee.in>
+date: Fri Aug 21 23:37:13 2009 +0530
+summary: First commit.
+ \end{lstlisting}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Other operations}
+ \typ{hg} supports basic file-management functions like copy, remove, rename etc.
+ \begin{lstlisting}
+$ hg cp feviStick.py pidiLite.py
+$ hg rename pidiLite.py feviCol.py
+$ hg st
+A feviCol.py
+$ hg ci -u "Shantanu <shantanu@fossee.in>"
+ -m "Added feviCol.py."
+$ hg tip| grep summary
+summary: Added feviCol.py.
+ \end{lstlisting} %$
+%% Other commands which can be handy are \typ{remove}, \typ{revert} etc.
+ \inctime{10}
+\end{frame}
+
+% Introduction to concepts of branches, merging patch?
+\section{Sharing and Collaborating}
+
+\begin{frame}[fragile]
+ \frametitle{Distributing changes}
+ \begin{itemize}
+ \item All directory-structure(repo) are self-contained.
+ \item Changes created are local.
+ \begin{itemize}
+ \item Until we sync. previously cloned repos.
+ \end{itemize}
+ \end{itemize}
+ \begin{lstlisting}
+$ hg pull
+pulling from /home/baali/Fevicol
+requesting all changes
+adding changesets
+adding manifests
+adding file changes
+added 2 changesets with 2 changes to 2 files
+(run 'hg update' to get a working copy)
+ \end{lstlisting} %$
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Pulling changesets cont...}
+ \typ{pull} command doesn't update current directory, it just imports changesets. To add all these changes, use \typ{up}:
+ \begin{lstlisting}
+$ cd Fevicol-pull
+$ ls -a
+. .. .hg
+$ hg up
+2 files updated, 0 files merged,
+0 files removed, 0 files unresolved
+$ ls -a
+. .. feviCol.py feviStick.py .hg
+ \end{lstlisting}
+ \pause
+ \emphbar{Why \typ{pull} and \typ{up} are needed separately?}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Making changes across branches}
+ \begin{lstlisting}
+$ cd Fevicol-pull/
+ \end{lstlisting} %$
+ Lets edit and correct the feviStick.py
+\begin{lstlisting}
+$ echo "print 'Ab no more Chip Chip'"
+ > feviStick.py
+$ hg st
+M feviStick.py
+\end{lstlisting}
+ 'M' sign indicates that \typ{hg} has noticed change.\\
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Revisiting changes}
+ To view changes made \typ{hg} provides \typ{diff}:
+\begin{lstlisting}
+$ hg diff
+diff -r a7912d45f47c feviStick.py
+--- a/feviStick.py Sun Aug 23 22:34:35 2009 +0530
++++ b/feviStick.py Sun Aug 23 22:47:49 2009 +0530
+@@ -1,1 +1,1 @@
+-print 'Yeh Fevicol ka Majboot jod hai'
++print 'Ab no more Chip Chip'
+ \end{lstlisting} %$
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Saving the changes}
+ We have to commit these changes.
+ \begin{lstlisting}
+$ hg ci -u "Shantanu <shantanu@fossee.in>"
+ -m "Changed tagline for feviStick.py."
+ \end{lstlisting} %$
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Syncing two repos}
+ To bring both the repos at same stage we have to \typ{push} differences.
+ \begin{lstlisting}
+$ hg push
+pushing to /home/baali/Fevicol
+searching for changes
+adding changesets
+adding manifests
+adding file changes
+added 1 changesets with 1 changes to 1 files
+ \end{lstlisting} %$
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Syncing cont...}
+ Same as pulling, pushing wont update the main directory by default.
+ \begin{lstlisting}
+$ cd Fevicol
+$ hg tip
+$ cat feviStick.py
+ \end{lstlisting}
+ \typ{tip} shows latest changeset, but content of file are not updated. We have to use \typ{up} on main branch
+ \begin{lstlisting}
+$ hg up
+1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+ \end{lstlisting} %$
+ \inctime{15}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Merging: Scenario}
+ One very useful feature is merging work of different peers working on same project.\\
+ We consider scenario, two person on one project, both have local copies, and one among them is main branch.\\
+ \begin{center}
+ \includegraphics[height=1in, interpolate=true]{scenario}
+ \end{center}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Making changes to one of repo}
+ \begin{lstlisting}
+$ cd Fevicol-pull
+$ echo "print 'Yeh Fevicol ka Majboot jod
+ hai, tootega nahin'" > feviCol.py
+$ hg st
+M feviStick.py
+$ hg ci -u "Shantanu <shantanu@fossee.in>"
+ -m "Updated tag line for feviCol.py."
+$ hg tip| grep changeset
+changeset: 3:caf986b15e05
+ \end{lstlisting} %$
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{In the meanwhile, other repo is ...}
+ \begin{lstlisting}
+$ cd Fevicol
+$ echo "print 'Jor laga ke hayyiya'"
+ > firstAdd.py
+$ hg add
+$ hg st
+A firstAdd.py
+$ hg ci -u "Shantanu <shantanu@fossee.in>"
+ -m "Added firsAdd.py."
+$ hg tip|grep changeset
+changeset: 3:fadbd6492cc4
+ \end{lstlisting}
+\end{frame}
+
+%%\hspace*{-0.5in}
+
+\begin{frame}[fragile]
+ \frametitle{Situation}
+ \begin{columns}
+ \column{0.5\textwidth}
+ \begin{block}{\center{main directory}}
+ \includegraphics[height=2in, interpolate=true]{main}
+ \end{block}
+ \column{0.5\textwidth}
+ \begin{block}{\center{cloned directory}}
+ \includegraphics[height=2in, interpolate=true]{clone}
+ \end{block}
+ \end{columns}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Merging}
+ \emphbar{Lets sync both these branches!}
+ \begin{lstlisting}
+$ hg pull ../Fevicol-pull
+pulling from ../Fevicol-pull
+searching for changes
+adding changesets
+adding manifests
+adding file changes
+added 1 changesets with 1 changes to 1 files (+1 heads)
+(run 'hg heads' to see heads, 'hg merge' to merge)
+ \end{lstlisting} %$
+ \begin{itemize}
+ \item \typ{pull} can be done from a branch explicitly also.
+ \item Output is already suggesting something!
+ \end{itemize}
+\end{frame}
+
+%% Here one can mention the point of having push and pull separate. Because of this policy, changes made are not lost.
+\begin{frame}[fragile]
+ \frametitle{Analyzing events in detail}
+ Since hg \typ{pull} don't update the files directly, our changes are still safe. \typ{hg} provides some commands to help understand such problems.
+\begin{tiny}
+ \begin{lstlisting}
+$ hg heads
+changeset: 4:c5f40fda69cf
+tag: tip
+parent: 2:0b8286c48e88
+user: Shantanu <shantanuc@fosse.in>
+date: Fri Jan 22 19:43:46 2010 +0530
+summary: Updated tagline for feviCol.py.
+
+changeset: 3:60edf0e499e7
+user: Shantanu <shantanuc@fosse.in>
+date: Fri Jan 22 19:47:58 2010 +0530
+summary: Added firstAdd.py.
+ \end{lstlisting} %%$
+\end{tiny}
+ It shows current repository heads or show branch head
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{What went wrong: Analysis}
+ \begin{lstlisting}
+$ hg glog
+ \end{lstlisting} %%$
+ \begin{center}
+ \includegraphics[height=2in]{glog}
+ \end{center}
+ It shows history alongside an ASCII revision graph.
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{What went wrong: Analysis cont...}
+ Because of different 'pasts', \typ{up} command fails.
+ \begin{lstlisting}
+$ hg up
+abort: crosses branches (use 'hg merge' or 'hg update -C')
+ \end{lstlisting} %$
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{Merging}
+ To deal such situations \typ{hg merge} command merge working directory with another revision.
+ \begin{lstlisting}
+$ hg merge
+ 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+(branch merge, don't forget to commit)
+ \end{lstlisting} %$
+ After merging two branches, we have to commit the results to create a common head.
+ \begin{lstlisting}
+$ hg ci -u "Shantanu <shantanu@fossee.in>"
+ -m "Merged branches."
+ \end{lstlisting} %$
+ \inctime{15}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{\typ{glog}}
+ \begin{center}
+ \includegraphics[height=2.8in]{glog-2}
+ \end{center}
+\end{frame}
+
+\begin{frame}[fragile]
+ \frametitle{More information}
+ \begin{itemize}
+ \item \typ{merge} fails if there are conflicting changes.
+ \begin{itemize}
+ \item Like two persons editing same file, same line and pushing it upstream.
+ \end{itemize}
+ \item In conflicts, one have to perform \typ{merge} manually.
+ \item \typ{hg} provides \typ{incoming} command, which checks the would-be imported changes
+ \begin{itemize}
+ \item To avoid conflicting changes before importing.
+ \end{itemize}
+ \end{itemize}
+\end{frame}
+
+% Steps to follow to make life easier. How to avoid/handle manual merges.
+\section{Work flow: DOS and DON'Ts}
+
+\begin{frame}
+ \frametitle{Motto behind hg}
+ \begin{center}
+ \color{red}{``Commit Early Commit Often.''}
+ \end{center}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Cheat Sheet}
+ \begin{center}
+ \includegraphics[height=2.8in]{mod}
+ \end{center}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Steps to be followed}
+ \begin{itemize}
+ \item Make changes.
+ \item Commit.
+ \item Pull changesets.
+ \item Merge(if required).
+ \item Push.
+ \end{itemize}
+ \inctime{20}
+\end{frame}
+
+\begin{frame}
+ \frametitle{Suggested Readings:}
+ \begin{itemize}
+ \item \url{http://mercurial.selenic.com/guide/}
+ \item \url{http://hgbook.red-bean.com/}
+ \item \url{http://karlagius.com/2009/01/09/version-control-for-the-masses/}
+ \item Articles related to version control available on \url{http://betterexplained.com/}
+ \item \url{http://en.wikipedia.org/wiki/Revision_control}
+ \item \url{http://wiki.alliedmods.net/Mercurial_Tutorial}
+ \item Mario game images are taken from wikipedia.
+ \end{itemize}
+\end{frame}
+\end{document}
+
+Notes
+-----
+
+From http://mercurial.selenic.com/
+
+Quick Start
+
+Clone a project and push changes
+
+$ hg clone http://selenic.com/repo/hello
+$ cd hello
+$ (edit files)
+$ hg add (new files)
+$ hg commit -m 'My changes'
+$ hg push
+
+
+Create a project and commit
+
+$ hg init (project-directory)
+$ cd (project-directory)
+$ (add some files)
+$ hg add
+$ hg commit -m 'Initial commit'
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sttp/versionControl/versionControl.rst Tue Mar 02 18:43:02 2010 +0530
@@ -0,0 +1,66 @@
+
+Module 4: Version Control
+=========================
+
+Module Objectives
+-----------------
+
+After successfully completing this module a participant will be able to: ::
+
+ - Understand use of Version Control tools U
+ - Create and use repository for daily use of assignments/projects Ap
+ - Browse exsiting repo, make changes and commit back Ap
+ - Work collaboratively with a team on live project Ap
+
+Suggested Reading:
+------------------
+"http://mercurial.selenic.com/wiki/Tutorial"
+
+**Initial Session Plan**
+
++---------+---------------------------------+---------+
+| Session | Topic | Duration|
++=========+=================================+=========+
+| 1 | Introduction to Course | 5 mts |
++---------+---------------------------------+---------+
+| 2 | Why Revision Control? | 5 mts |
+| | - Use case: for team | |
+| | - Use case: for single dev | |
++---------+---------------------------------+---------+
+| 3 | Learning the Lingo | 5 mts |
++---------+---------------------------------+---------+
+| 4 | Let there be Repository... | 15 mts |
+| | - Creating Repositpry. | |
+| | - Cloning existing Repo. | |
+| | - Branches concept | |
++---------+---------------------------------+---------+
+| 5 | Navigating through history logs | 5 mts |
++---------+---------------------------------+---------+
+| 6 | Making changes in local branch | 15 mts |
+| | - add | |
+| | - cp | |
+| | - rename | |
+| | - rm | |
++---------+---------------------------------+---------+
+| 7 | Sharing the changes | 10 mts |
+| | - status | |
+| | - pull | |
+| | - update | |
++---------+---------------------------------+---------+
+| 8 | Merging the changes | 20 mts |
+| | - commit | |
+| | - glog | |
+| | - push | |
+| | - merge | |
++---------+---------------------------------+---------+
+| 9 | Handling conflicts during merge | 20 mts |
++---------+---------------------------------+---------+
+| 10 | Exporting the changes: getting | |
+| | patch, diff | 10 mts |
++---------+---------------------------------+---------+
+
+*total session time = 110 mts*
+
+*buffer time = 10 mts*
+
+*For this course, working LAN is needed if Internet is not available.*