This tutorial is for those who have gone through the first and second LaTeX tutorials, and should give you the knowledge required to understand more specific LaTeX tips both on this site and on other websites. This tutorial will cover Packages and the basics of math mode.


Packages


Much like in programming, additional functionality can be added to LaTeX though the use of packages. Using packages may change the way the document looks (fonts, page orientation, etc) or make additional calls available to the user. Think of them as add-ons. Packages are included with the \usepackage{package-name} call.

I will illustrate this with an example. Let’s say that we wanted the document to be rendered in Times New Roman, and we want web addresses (URLs) to be displayed differently and for them to be clickable. A fairly common request. This can be achieved by including three packages; url, hyperref and times. url will provide you with a new command, \url{insert url here}, which makes the web addresses appear differently from the rest of the text. hyperref will make these URLs (and any other references within the document) clickable and times will change the font to Times New Roman. You can include the packages separately:

\usepackage{hyperref}
\usepackage{times}
\usepackage{url}

or in one line:

\usepackage{hyperref, times, url}

I personally prefer to include the packages individually, in alphabetical order, to make the code easier to work with.

From here, simply put any web address in a \url{} tag to make it a link. For example:

\documentclass{article}
\usepackage{url}
\usepackage{times}
\usepackage{hyperref}

\begin{document}
This font is in Times New Roman. To see how to change it to other fonts, see \url{http://timmurphy.org/2009/07/28/changing-fonts-in-latex/}.
\end{document}

will produce this document


Math Mode

Possibly the most common reasons for using LaTeX over, say, Microsoft Word is the math mode. LaTeX has the ability to draw mathematical symbols and fractions within the document without too much messing around. All the math stuff needs to be defined within the math mode. This mode may be defined in the following ways:

$x = 1$ will place x = 1 inline with the rest of the text.
$$x = 1$$ or \[x = 1\] will place x = 1 on a new line, centered.
\begin{equation}x = 1\end{equation} will also place x = 1 centered and numbered, on a new line, with the advantage of being able to be referenced. See this post to learn more about referencing.

Within the math mode, certain math commands can be used. For example, \frac{numerator}{denominator} will produce a fraction. There are way too many math commands available to mention here, but some of the most common are the summation symbol and integrals and limits. If you’re looking for a particular math symbol, google is your friend.

For example,

\documentclass{article}
\begin{document}
Math mode may inline, such as $1\frac{1}{2} = \frac{3}{2}$ or on a separate line such as:
$$1\frac{1}{2} = \frac{3}{2}$$
\[
1\frac{1}{2} = \frac{3}{2}
\]
\begin{equation}
1\frac{1}{2} = \frac{3}{2}
\end{equation}
\end{document}

will produce this document

This information, together with the first two tutorials, should give you enough background to understand the way LaTeX works and to go on to create your own documents. If you don’t know how to do something in LaTeX then do a google search – there’s probably someone out there who has explained how. If you can put it on paper, you can LaTeX it.

LaTeX has the ability to draw images out of the box. The drawing functionality is pretty basic — lines, circles, boxes and the like — but perfect for most simple diagrams.

This tutorial will be split into three sections: configuring the environment, different ways of drawing shapes, and a description of the shapes themselves.


Configuring the Environment

Before we get started on the environment, we need to think about what we are drawing and how we want to set up the coordinates. We need to define a unit length, which is the length between each coordinate in the picture. It is also used to define the size of the canvas. This is set using \setlength{\unitlength}{length} (see this post for a list of available unit lengths).

Note that the default unit length is 1pt, which is not overly useful for drawing in most cases.

Once the unit length is set, we can create the picture canvas like so:

\begin{picture}(width, height)[(x-offset, y-offset)]

What are all of those parameters? The first parameter, (width, height) defines the height and width of the canvas. This is a number with no units, setting the width according to the unitlength set previously. For example, if the unitlength is set to 5mm, setting the width as 10 will create a canvas of width 50mm. Similarly for height.

Note that the canvas size is not an absolute boundary. It is possible to draw past the boundaries of the canvas – even off the page.

The (x-offset, y-offset) setting is optional, as indicated by the square brackets, and defines the coordinates of the bottom left corner. By default. this corner will have the coordinates (0, 0).

Now that all sounds confusing, so let’s look at an example.

\setlength{\unitlength}{1cm}
\begin{picture}(10, 5)(-1, -1)
...
\end{picture}

This will create a 10cm x 5cm canvas, with the bottom left corner at (-1, -1) and the top right corner at (9, 4).

The line thickness can also be set, though be aware that it only really works for straight lines. If you set the line thickness to, say, 2pt and draw an oval, then the straight lines of the oval will be 2pt but the curves will be much thinner. Best to avoid line thickness unless using it for straight lines only.

To set the line thickness, use the \linethickness{thickness} command. This can be set many times throughout the document.


Different Ways of Drawing Shapes

\put(x, y){shape}
Draws the shape on the picture at position (x, y). eg:

\begin{picture}(2,2)
\put(1,1){\circle{1}}
\end{picture}

put

\multiput(x, y)(x-diff, y-diff){num-shapes}{shape}
Draws num-shapes shapes on the picture, starting at (x, y). Each shape is shifted x-diff units to the right and y units up. eg:

\begin{picture}(5,5)
\multiput(0,0)(0.5,1){5}{\line(1,0){0.5}}
\end{picture}

multiput

\shortstack[position]{shape \\ shape \\ …)
Draws a stack of objects. position may be r, l or c to stack the objects to the right, left or center, respectively. eg:

\begin{picture}(5,5)
\shortstack{\circle{1}\\\circle{1}\\\circle{1}}
\end{picture}

shortstack

Note: shape in these commands may be any of the shapes below, or another \put, \multiput or \shortstack command.


Description of Available Shapes

\circle{radius}
Draws the outline of a circle, of radius radius. eg:

\begin{picture}(2,2)
\put(1,1){\circle{1}}
\end{picture}

circle

\circle*{radius}
Draws a solid circle, of radius raduis. eg:

\begin{picture}(2,2)
\put(1,1){\circle*{1}}
\end{picture}

circle_star

\dashbox{dash_len}(width, height)[pos]{text}
Draws a box with a dashed outline, with dashes of length dash_len, around text. The pos argument, if used, is identical to the pos argument in \framebox eg:

\begin{picture}(2,2)
\put(0,0){\dashbox{0.2}(2,2)[s]{Boo}}
\end{picture}

dashbox

\frame{object}
Draws a rectangle around object with no spaces between the frame and the object. eg:

\begin{picture}(2,2)
\put(1,1){\frame{Boo}}
\end{picture}

frame

\framebox(width,height)[pos]{text}
Draws a box around text, with the specified width. pos, if specified, defines where the text is positioned in the box. pos may be l (left), r (right), s (space added between words so that text fills the box) or, if omitted, centered. eg:

\begin{picture}(2,2)
\put(0,0){\framebox(2,2){Boo}}
\end{picture}

framebox

\line(x-slope,y-slope){len}
Draws a line of length len with the specified slope. The slope is defined as two coprime numbers between -6 and 6 inclusive. ie: two numbers with no common factors other than one. len defines the horizontal length, unless the line is vertical where len defines the vertical height. eg:

\begin{picture}{3,1}
\put(0,0){\line(3,1){3}}
\end{picture}

line

\makebox[width][pos]{text}
Draws an invisible box with text inside. This is the same as \framebox without the outline. eg:

\begin{picture}(2,2)
\put(0,0){\makebox{Boo}}
\end{picture}

makebox

\oval(width,height)[section]
Draws a rectangle with rounded corners. If section is defined, only part of the oval is drawn. section may be t (top), b (bottom), r (right) or l (left). eg:

\begin{picture}(2,2)
\put(1,1){\oval(2,1)}
\end{picture}

oval

\vector(x-slope,y-slope){len}
Draws a line with an arrow on the end. This is exactly the same as the \line object with an arrow. eg:

\begin{picture}{3,1}
\put(0,0){\vector(3,1){3}}
\end{picture}

vector

An Example

% set in the preamble - makes changing the image size easier
\def\gridspace{20}
\def\doublegridspace{40}
\def\griddiagonal{10}
\def\griddot{\circle*{2}}

...

\setlength{\unitlength}{1mm}
\begin{picture}(80,70)
        \linethickness{1.5pt}

        % dots
        \multiput(20, 10)(5, 5){3}{
                \multiput(0, 0)(0, \gridspace){3}{
                        \multiput(0, 0)(\gridspace, 0){3}{\griddot}
                }
        }

        % straight lines
        \multiput(20, 10)(5, 5){3}{
                \multiput(0, 0)(0, \gridspace){3}{\line(1, 0){\doublegridspace}}
                \multiput(0, 0)(\gridspace, 0){3}{\line(0, 1){\doublegridspace}}
        }

        % diagonal lines
        \multiput(20, 10)(0, \gridspace){3}{
                \multiput(0, 0)(\gridspace, 0){3}{\line(1, 1){\griddiagonal}}
        }

        \linethickness{1pt}

        % arrows
        \put(20, 10){\vector(-1, -1){5}}
        \put(30, 60){\vector(0, 1){10}}
        \put(70, 20){\vector(1, 0){10}}

        % labels
        \put(18, 12){\makebox(0, 0){$2$}}
        \put(28, 62){\makebox(0, 0){$2$}}
        \put(72, 22){\makebox(0, 0){$2$}}
        \put(17, 4){\makebox(0, 0){$x$}}
        \put(80, 18){\makebox(0, 0){$y$}}
        \put(28, 70){\makebox(0, 0){$z$}}
\end{picture}

Will produce the following image:

Picture environment example

A common question amongst coders new to C or C++ relates to the difference between stack and heap memory allocation. The answer lies in how the code is executed at the very lowest level.

When a program is executed, each thread is allocated a limited amount of stack space. The stack holds information used by the program, including the raw byte code executed on the processor.

Variables allocated on the stack, or automatic variables, are stored directly to this memory. Access to this memory is very fast, and it’s allocation is dealt with when the program is compiled. Large chunks of memory, such as very large arrays, should not be allocated on the stack to avoid overfilling the stack memory (known as stack overflow). Stack variables only exist in the block of code in which they were declared. For example:


void a()
{
    if(true) {
        int x = 0;
    }
    x = 1;
}

In this code, x is allocated on the stack. This value is not available outside of the if() block, so attempting to access the variable outside of the block, as above, result in a compilation error.

Variables allocated on the heap, or dynamic variables, have their memory allocated at run time (ie: as the program is executing). Accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory (ie: RAM and swap space). This memory remains allocated until explicitly freed by the program and, as a result, may be accessed outside of the block in which it was allocated. For example:

int *x;
void b()
{
    if(true) {
        x = malloc(sizeof(int));
    }
    *x = 1;
}

void c()
{
    free(x);
}

In this example, memory for the variable x is allocated when b() is called, and remains in memory until c() is called. Notice how we can set the value of x outside of the if() block in which it is allocated.

In summary, temporary variables should be allocated on the stack. It’s less mucking around with memory allocation, the code is easier to read, the memory is accessed faster and the program does not need to allocate the memory on the fly. For large variables or arrays whose size may vary, heap memory allocation is your friend. Just remember to free all of the memory allocated or you’ll end up with memory leaks.

There are a number of ways to change the document header and footer styles in LaTeX. One of the easiest and most flexible options is to use the fancyhdr package.

fancyhdr is a massive package with a crazy number of tweaks and modifications available for your document’s header and footer styles. This tutorial will only brush over the basic capabilities of the package, describing the most common styling choices.

We tell LaTeX to use fancyhdr by adding the following to the preamble (the top of the document before the \begin{document} call):

\usepackage{fancyhdr}
\pagestyle{fancy}

fancyhdr allows the content of the left, middle and right parts of both the header and footer to be changed. By default, the header contains the chapter name on the left, the section name and number on the right and has a black line separating the header from the document. The footer contains the page number in the middle.

To clear the header and footer contents, add \fancyhf{} to the preamble below the pagestyle line. You can now set the contents of the header and footer using the following calls in the preamble:

\lhead{left header content}
\chead{middle header content}
\rhead{right header content}
\lfoot{left footer content}
\cfoot{middle footer content}
\rfoot{right footer content}

If you don’t want the line underneath the header, or if you want to change the thickness, you can use the \renewcommand{\headrulewidth}{width} command. Setting the width to zero (ie: 0mm, 0pt, 0in, etc) will remove the line. Similarly, you may add a line above the footer with the \renewcommand{\footrulewidth}{width} command. This width is set to zero by default.

There are a few commands you can use to put dynamic content in the header and footer:

\today – the current day. ie: August 6, 2010
\thepage – the current page number
\thesection – the current section number
\leftmark – current chapter name in uppercase. ie: CHAPTER 1. TITLE OF THE FIRST CHAPTER
\rightmark – current section name in uppercase. ie: 1.1. TITLE OF THE FIRST SECTION

We can also use information from other packages, like the lastpage package which gives the number of the last page.

That’s a lot of detail, so let’s look at an example:

\documentclass{article}

\usepackage{lastpage} % for the number of the last page in the document
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\lhead{--- DRAFT ---}
\rhead{Section \thesection}
\lfoot{\today}
\rfoot{Page \thepage\ of \pageref{LastPage}

\begin{document}
\section{\LaTeX headers and footers}
Headers and footers can be set with the fancyhdr package.
\end{document}

Will produce this document

Note: remember to compile this document twice so that all the reference work properly.

Converting CDs to MP3s in Ubuntu

Posted: 25th July 2010 by Tim in Ubuntu
Tags: , , , , , ,

There are a number of ways to convert CDs into MP3s in Ubuntu. For me, the best choice is Sound Juicer because of it’s filename flexibility and ability to deal with compilations. Setting it all up is also very simple.

Only two packages are required from the repository. They can be installed with the following command:

sudo apt-get install sound-juicer gstreamer0.10-lame

The first package will install the ripping software, and the second package allows the music to be converted to MP3s. Next, we want to tell Sound Juicer to convert the files at 320kbps to keep the sound quality as high as possible. To do this, start Sound Juicer, go to Edit -> Preferences and at the bottom of the page, change the Output Format to CD Quality, MP3 (.mp3 type). Next, click Edit Profiles, select CD Quality, MP3, click Edit and change the GStreamer Pipeline setting to audio/x-raw-int,rate=44100,channels=2 ! lame name=enc bitrate=320 mode=0 ! id3v2mux.

Once that’s done, you’re set. Simply insert a CD, wait for the program to fetch the song details and click the Extract button. Voila, MP3s on your computer.

301 Redirects in PHP

Posted: 9th July 2010 by Tim in PHP
Tags: , , , , , , , , , ,

If you have a web page which has been moved to another URL, or if the page has been completely removed, chances are people will have that address saved in their bookmarks, or they will try to access the page via a search engine and get a 404 - Page Not Found error. Not only does this look bad to your visitors, but search engines will also view your website less favorably.

That’s where the 301 - Moved Permanently redirection comes in handy. Not only does it redirect your visitors to the new page, but search engines can update their links without thinking your site is unreliable.

There are a number of ways to redirect traffic. In PHP, this can be done with the following code:

<?PHP
Header("HTTP/1.1 301 Moved Permanently");
Header("Location: http://timmurphy.org");
?>

Add this code to the webpage you are redirecting. For example, if you have moved http://example.com/old.php to http://example.com/new.php, then write the code above (replacing http://timmurphy.org with the new URL) into old.php.

Note that there are other, nicer ways of doing redirection (such as through .htaccess files as described here), and I would recommend doing the above only when no other options are available.

If you have a web page which has been moved to another URL, or if the page has been completely removed, chances are people will have that address saved in their bookmarks, or they will try to access the page via a search engine and get a 404 - Page Not Found error. Not only does this look bad to your visitors, but search engines will also view your website less favorably.

That’s where the 301 - Moved Permanently redirection comes in handy. Not only does it redirect your visitors to the new page, but search engines can update their links without thinking your site is unreliable.

If you are using apache, you can set up 301 redirects (as well as many other things) using the .htaccess file. This file lives in the root directory of your website (ie: where your index.html or index.php file is saved). If this file does not exist then create it. Then add the following code to a new line in the file:

redirect 301 /old.php http://example.com/new.php

where /old.php is the relative address of the old webpage, and http://example.com/new.php is where you would like to redirect your visitors. Once this is done, save the file and you should be good to go. No restart of Apache is required.

Latex allows the creation of itemized (unordered) lists up to four deep. The numbering styles for each depth can be styled to suit your needs using the \renewcommand{label}{style} command, where label is the list depth being styled and style is how you want that number to be shown.

label may be any of the following:

  • \labelitemi: first level
  • \labelitemii: second level
  • \labelitemiii: third level
  • \labelitemiv: fourth level

style may be any character or combination of characters, including math characters. So if we want top level items to have square bullets, then we would style the list like so:

\usepackage{amssymb}
\renewcommand{\labelitemi}{\tiny$\blacksquare$}

This would be added to the top of the document, before \begin{document}.

Latex allows the creation of enumerated (ordered) lists up to four deep. The numbering styles for each depth can be styled to suit your needs using the \renewcommand{label}{style} command, where label is the list depth being styled and style is how you want that number to be shown.

label may be any of the following:

  • \labelenumi: first level
  • \labelenumii: second level
  • \labelenumiii: third level
  • \labelenumiv: fourth level

style may be any combination of characters and numbers. The item number for each list may be printed using by using any of the following (from first depth to fourth depth):

  • enumi
  • enumii
  • enumiii
  • enumiv

These numbers may be styled with the following macros:

  • \alph{number}: lowercase letters
  • \Alph{number}: uppercase letters
  • \arabic{number}: numbers
  • \roman{number}: lowercase roman numerals
  • \Roman{number}: uppercase roman numerals

That’s a lot to take in, so let’s look at an example. If we want to generate a list which is numbered a style like this:

1. First level
1. a) Second level
1. a) i: Third level

Then we would style the list like so:

\renewcommand{\labelenumi}{\arabic{enumi}. }
\renewcommand{\labelenumii}{\labelenumi\alph{enumii}) }
\renewcommand{\labelenumiii}{\labelenumii\roman{enumiii}: }

This would be added to the top of the document, before \begin{document}.

There are times when you want to have multiple columns on part of a page. You could use tables to get such a layout, but that’s a bit dirty. A nice, clean method is to use the minipage environment.

Minipages are defined with a width parameter. If you have multiple minipages defined immediately after each other, they will appear next to each other (as long as the sum of the widths does not exceed \textwidth). For example, to produce a two-column layout, you could use the following:

% first column
\begin{minipage}[t]{0.5\textwidth}
This is the first column.\\

This is still in the first column.
\end{minipage}

%second column
\begin{minipage}[t]{0.5\textwidth}
This is the second column.
\end{minipage}

The widths can be changed by modifying the last argument in the \begin{minipage} call (ie: to make the first column twice as wide as the second, make the width of the first 0.6\textwidth and the second 0.3\textwidth). Also note the [t] – this tells LaTeX to make each column vertically aligned to the top.

It’s often useful to concatenate two fields together in an SQL query. In PostgreSQL, fields may be concatenated using the || operator. The syntax is really simple. Just place the double bar between the fields you want to join, and (optionally) give a label to that new field. Strings can also be concatenated with the fields.

For example, let’s say you have a person table with first_name and surname fields, and you wanted to return the full name of each person. This could be done with the following:

SELECT first_name || ' ' || surname AS name
FROM person

This will give you a result set similar to:

     name
---------------
 Bob Dylan
 Stevie Wonder
 Bob Marley
 Elvis Presley
(4 rows)

Note that this syntax will only work with PostgreSQL – other database servers may use different syntax.

Ever jumped onto an Ubuntu server somewhere without knowing which operating system version it’s running? You can find this out with one simple command:

lsb_release -a

This will provide output like:

Distributor ID: Ubuntu
Description: Ubuntu 9.10
Release: 9.10
Codename: karmic

PostgreSQL, unfortunately, does not provide an inline IF statement like some other SQL servers. CASE statements, however, can be run inline which can be quite handy.

Let’s say you have a user table with a num_heads field. You want to know if the user is a zombie, human or alien with one query. This could be done with the following:

SELECT CASE
    WHEN num_heads=0 THEN 'zombie'
    WHEN num_heads=1 THEN 'human'
    ELSE 'alien'
END AS race
FROM "user";

Notice how the syntax is different from MySQL inline CASE statements and other SQL servers, so be careful if you intend on making the script portable.

Pausing processes in ubuntu

Posted: 6th June 2010 by Tim in Ubuntu
Tags: , , , , , ,

There are times when you want to pause a process and continue it later. For example, when a process is using all the computer’s resources and you need to access something or execute something else. This can all be done via the kill -STOP and kill -CONT commands.

First you need to grap the pid (process ID) of the process which you want to pause. You can do this using ps aux, or top (or a bunch of other means). Once you have the pid (12345, for example), pause the process by typing:

kill -STOP 12345

You can then resume the process at any time after that by typing:

kill -CONT 12345

(be sure to replace 12345 with the actual pid)

It’s that easy.

LaTeX length units

Posted: 26th May 2010 by Tim in LaTeX
Tags: , , , , , , , , , , ,

There are many configurations and commands in LaTeX which require lengths to be set. The following length units can be used:

  • in – imperial inch
  • pt – point (1/72 of an inch)
  • cm – metric centimeter
  • mm – metric millimeter
  • em – width of a capital “M” in the current font settings
  • ex – width of a lower-case “x” in the current font settings

Note that if you want to set the length as zero, you still need to specify the unit. ie: “0″ will not work, but “0mm” will.

Union (∪) and Intersection (∩) symbols in LaTeX can be produced via the \cup and \cap definitions while in math mode. No extra packages are required to use these symbols.

For example:

Let $L_C = L_A \cap (L_B \cup L_C)$

will produce:

In Bash you quite often need to check to see if a variable has been set or has a value other than an empty string. This can be done using the -n or -z string comparison operators.

The -n operator checks whether the string is not null. Effectively, this will return true for every case except where the string contains no characters. ie:

VAR="hello"
if [ -n "$VAR" ]; then
    echo "VAR is not empty"
fi

Similarly, the -z operator checks whether the string is null. ie:

VAR=""
if [ -z "$VAR" ]; then
    echo "VAR is empty"
fi

Note the spaces around the square brackets. Bash will complain if the spaces are not there.

This tutorial is for those who have gone through the first tutorial. Here we will cover new lines and paragraphs, comments, font decoration (bold, italic and underline) and sections. Fun.


New lines and paragraphs

First we will look at paragraphs. In LaTeX, having a new line in your .tex file (which we will refer to as the source code from now on) does not necessarily mean that a new line will appear in your compiled document. This may seem a bit strange to most beginners, but it allows you to format you source code to make it more readable without affecting the resulting document. The advantages of this will become apparent when you start working with big documents.

So how do we tell LaTeX to put stuff on a new line? This can be done using two backslashes (ie: \\). To signal the end of a paragraph, we can place an empty line between the first and second paragraph in the souce code (this will start the second paragraph directly under the first) or put a double slash at the end of the first paragraph AND leave an empty line between the paragraphs in the source code. Confusing? Let’s look at an example then.

\documentclass[11pt,a4paper]{article}
\begin{document}
1. There are three types of people.\\
Those who learn by reading,\\
those who learn by observation\\
and those who need to touch the fire to see if it really is hot.

2. The best contraceptive for old people is nudity.\\

3. Stealing from one source is plagiarism. Stealing from multiple sources is research.
\end{document}

This code will produce the following document (the PDF produced can be downloaded from here):

    1. There are three types of people.
Those who learn by reading,
those who learn by observation
and those who need to touch the fire to see if it really is hot.
    2. The best contraceptive for old people is nudity.

    3. Stealing from one source is plagiarism. Stealing from multiple sources is
research.

From this you can see the differences in line breaks. New paragraphs are indented by default (see this post for how to remove this). Keep this in mind when writing your documents.


Comments

Like any other programming or markup language, LaTeX source code can contain comments. A comment is text that the compiler ignores when generating the document. A comment is any text on a line which has a percent sign (%) before it.

For example, in the code below all text in grey is a comment:

% this text is a comment
\documentclass[11pt,a4paper]{article} % this is a comment too

Comments are used for adding notes to the source to explain what code is doing, for leaving notes for other developers and that sort of thing.


Font Decorations

Any text in LaTeX can be made bold, italic, underline or any combination of the three.

To make text bold, surround the text in \textbf{...}.

To make text italic, surround the text in \emph{...}.

To underline the text, surround the text in \underline{...}.

These tags can be used with one another. For example:

Text in LaTeX can be \textbf{bold}, \emph{italic}, \underline{underline} or any combination such as \emph{\textbf{bold and italic}}.


Sections

LaTeX articles can be organized into sections, sub-sections and sub-sub-sections via the \section{section name}, \subsection{sub-section name} and \subsubsection{sub-sub-section name} tags, respectively. You don’t have to number the sections manually – LaTeX will do this for you. If you want to add an un-numbered section, use the \section*{section name}, \subsection*{sub-section name} and \subsubsection*{sub-sub-section} tags.

For example:

\documentclass[11pt,a4paper]{article}
\begin{document}


\section{The first section}
This text is in section 1


\subsection{The first sub-section}
This text is in section 1.1


\section{The second section}
This text is in section 2


\subsection{Another sub section}
This text is in section 2.1


\subsubsection{A sub-sub-section}

This text is in section 2.1.1
\subsubsection{Another sub-sub-section}
This text is in section 2.1.2


\section*{Another section?}
This section does not have a number


\end{document}

Will produce the following (view the actual document here):

1 The first section
This text is in section 1
1.1 The first sub-section
This text is in section 1.1

2 The second section
This text is in section 2
2.1 Another sub section
This text is in section 2.1
2.1.1 A sub-sub-section
This text is in section 2.1.1
2.1.2 Another sub-sub-section
This text is in section 2.1.2

Another section?
This section does not have a number

pthreads in C – a minimal working example

Posted: 4th May 2010 by Tim in C

Pthreads are a simple and effective way of creating a multi-threaded application. This introduction to pthreads shows the basic functionality – executing two tasks in parallel and merging back into a single thread when the work has been done.

First I’ll run through the basics of threading applications with pthreads. Multi-threaded applications allow two or more tasks to be executed concurrently (ie: at the same time). When a thread is created using pthread_create, both the original thread and the new thread share the same code base and the same memory – it’s just like making two function calls at the same time. Multi-threaded applications come with a whole host of concurrency issues, which will be discussed further in a future post.

All C programs using pthreads need to include the pthread.h header file (ie: #include <pthread.h>). There are four steps to creating a basic threaded program:

1: Define thread reference variables

The variable type pthread_t is a means of referencing threads. There needs to be a pthread_t variable in existence for every thread being created. Something like pthread_t thread0; will do the trick.

2: Create an entry point for the thread

When creating a thread using pthreads, you need to point it to a function for it to start execution. The function must return void * and take a single void * argument. For example, if you want the function to take an integer argument, you will need to pass the address of the integer and dereference it later. This may sound complicated but, as is shown below, it’s pretty simple. An example function signature would be void *my_entry_function(void *param);

3: Create the thread

Once the pthread_t variable has been defined and the entry point function created, we can create the thread using pthread_create. This method takes four arguments: a pointer to the pthread_t variable, any extra attributes (don’t worry about this for now – just set it to NULL), a pointer to the function to call (ie: the name of the entry point) and the pointer being passed as the argument to the function. Now there’s a lot of pointers in that call, but don’t stress – it’s not as tricky as it sounds. This call will look something like pthread_create(&thread0, NULL, my_entry_function, &parameter);

4: Join everything back up

When the newly-created thread has finished doing it’s bits, we need to join everything back up. This is done by the pthread_join function which takes two parameters: the pthread_t variable used when pthread_create was called (not a pointer this time) and a pointer to the return value pointer (don’t worry about this for now – just set it to NULL). This call will look something like pthread_join(thread0, NULL);

And that’s all there is to it. The function used as the thread entry point can call other functions, create variables or do anything any other function can do. It can also use the variables set by the other thread.

When compiling the program, you will also need to add -lpthread to the compile command. ie: gcc program.c -o program -lpthread

Below is a minimum example of a threaded application. It creates two numbers, x and y, and creates a second thread. The first thread increments y until it has the value of 100, while the second thread increments x until it has the value of 100 at the same time. When this is done, it joins the second thread back with the main program and prints the results. Note how, even though x was changed by the second thread, it has been changed for the main program too!

#include <pthread.h>
#include <stdio.h>

/* this function is run by the second thread */
void *inc_x(void *x_void_ptr)
{

/* increment x to 100 */
int *x_ptr = (int *)x_void_ptr;
while(++(*x_ptr) < 100);

printf("x increment finished\n");

/* the function must return something - NULL will do */
return NULL;

}

int main()
{

int x = 0, y = 0;

/* show the initial values of x and y */
printf("x: %d, y: %d\n", x, y);

/* this variable is our reference to the second thread */
pthread_t inc_x_thread;

/* create a second thread which executes count_x(&x) */
if(pthread_create(&inc_x_thread, NULL, inc_x, &x)) {

fprintf(stderr, "Error creating thread\n");
return 1;

}
/* increment y to 100 in the first thread */
while(++y < 100);

printf("y increment finished\n");

/* wait for the second thread to finish */
if(pthread_join(inc_x_thread, NULL)) {

fprintf(stderr, "Error joining thread\n");
return 2;

}

/* show the results - x is now 100 thanks to the second thread */
printf("x: %d, y: %d\n", x, y);

return 0;

}

This code will print something like:

x: 0, y:0
y increment finished
x increment finished
x: 100, y: 100

Some mail servers require you to connect on a certain port. Evolution (the default mail client for the gnome desktop environment) doesn’t have a setting for the server port number. You can set this by adding :[port_no] to the end of the server address.

For example, to use the mail server mail.example.com on port 587, set the server path as mail.example.com:587.

In math, certain blackboard (double-barred) letters Z, N, R, etc. represent sets of numbers (integers, natural numbers, rational numbers, etc). These can be included in a LaTeX document using the \mathbb{[letter]} tag from within the math environment.

Note that this requires the amssymb package to be included (ie: add \usepackage{amssymb} to the top of the document).

For example, we could use the following code:

$\forall a,b \in \mathbb{N}: ab > 0$

To produce:

Forall symbol LaTeX example

Mounting ISO files in Linux

Posted: 24th April 2010 by Tim in Ubuntu
Tags: , , , , , , ,

One of the niceties of linux distros like Ubuntu is that you can ‘mount’ ISO files. An ISO file, or ISO image, is an archive of a CD or DVD. By mounting an ISO file, you can read the data as though you inserted the CD into your computer. Ubuntu will even regard it as a CD (or DVD) so that games, video players, etc. think that they are reading from an actual CD (or DVD).

To mount the ISO, you first need a directory to mount to. Create this directory anywhere on your file system. ie:

sudo mkdir /media/iso

Once that’s done, we mount the ISO:

sudo mount -o loop [/path/to/iso/image/file] /media/iso

And voila, your ISO image is mounted. Your programs should now see a new CD/DVD device for you to use.

When you’re done with the iso, you can unmount it by typing:

sudo umount /media/iso

Note that you can mount as many ISO files at a time as you like – useful if you’re playing a game which requires multiple CDs.

Let’s say you have a file type whose contents are in XML format but have a different file extension such as .tim . If you want to edit these files with Vim with syntax highlighting, simply add the following to ~/.vimrc (affects only your Vim environment) or /etc/vim/vimrc (affects everyone’s Vim environment):

au BufNewFile,BufRead *.tim set filetype=xml

This can be done for any file type. To give another example, if you’re storing PostgreSQL code in a file called setup.psql and want SQL syntax highlighting in Vim, add the following line:

au BufNewFile,BufRead *.psql set filetype=sql

Often times you want to add entries to the references section of a LaTeX document without actualy citing them. The \nocite{reference} may be used to add the record to the references, but writing \nocite for each reference can get tedious.

Luckily, adding \nocite{*} to the document will ensure that everything is added to the references.

If you’re getting a FATAL: Ident authentication failed for user [username] Error when attempting to connect to postgres as a specific user, chances are you need to change some security settings.

Postgresql, by default, only allows you to connect to postgres if the postgres username is the same as your username on the operating system. In other words, if you’re logged in to your computer as frank, you can, in general, only connect to the postgres server as the frank user.

To allow connection as any existing postgres user, the following lines need to be added to the pg_hba.conf:

local all all trust
host all all 127.0.0.1/32 trust

Note that if there is a line in the file like:

local all all ident sameuser

Then the extra lines you add need to be above this line.

If you don’t know where to find this file, on ubuntu it can be found at:

/etc/postgresql/[version]/main/pg_hba.conf

This path should be similar on other linux distributions.