Archive for the ‘Tutorials and Guides’ Category

3
Aug

How To Build a .tex File to .pdf on Linux

Most of the guides I came across were just wildly all over the place, so I figured a short and simple guide that gets right to the point would be useful. Here’s how to set up Fedora 15 to build (compile might be another word) a .tex file into a .pdf file from the command line. It can be applied to other Linux distributions as well. There are GUIs to help with this, but it’s best to start with the basics. So, fire up a terminal and let’s get started.

Step 1: Install the TexLive Package

The first thing we need to do is install the texlive package.

su -c 'yum install -y texlive'

Step 2: Prepare a .tex Document

Next, we’ll create a “hello world” type .tex file. Fire up your favorite text editor and copy/paste the following (I enjoy using vim since I can stay in the command line while building the LaTeX file). When you’re finished, save the file (I’ve saved it as “hello.tex”).

documentclass{book}

usepackage{lipsum}

begin{document}
chapter{Sample}

lipsum[1-4]
end{document}

Step 3: Build the .tex Document Into a PDF File

Finally, we’ll build (compile) the .tex source into a pretty PDF document using the command below:

pdflatex hello.tex

You’ll see something similar to this:

[dhildreth@drh hello_world]$ pdflatex hello.tex
This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6)
 %&-line parsing enabled.
entering extended mode
(./hello.tex
LaTeX2e <2005/12/01>
Babel <v3.8h> and hyphenation patterns for english, usenglishmax, dumylang, noh
yphenation, arabic, basque, bulgarian, coptic, welsh, czech, slovak, german, ng
erman, danish, esperanto, spanish, catalan, galician, estonian, farsi, finnish,
 french, greek, monogreek, ancientgreek, croatian, hungarian, interlingua, ibyc
us, indonesian, icelandic, italian, latin, mongolian, dutch, norsk, polish, por
tuguese, pinyin, romanian, russian, slovenian, uppersorbian, serbian, swedish,
turkish, ukenglish, ukrainian, loaded.
(/usr/share/texmf/tex/latex/base/book.cls
Document Class: book 2005/09/16 v1.4f Standard LaTeX document class
(/usr/share/texmf/tex/latex/base/bk10.clo))
(/usr/share/texmf/tex/latex/lipsum/lipsum.sty)
No file hello.aux.
Chapter 1.
[1{/usr/share/texmf/fonts/map/pdftex/updmap/pdftex.map}] [2] (./hello.aux) )</u
sr/share/texmf/fonts/type1/bluesky/cm/cmbx12.pfb></usr/share/texmf/fonts/type1/
bluesky/cm/cmr10.pfb></usr/share/texmf/fonts/type1/bluesky/cm/cmsl10.pfb>
Output written on hello.pdf (2 pages, 22507 bytes).
Transcript written on hello.log.
[dhildreth@drh hello_world]$

Notice the text “Output written on hello.pdf (2 pages, 22507 bytes).”. That means it worked.

Step 4: View the New PDF File

Now, all you need to do is view the generated PDF document. Run the following command:

evince hello.pdf

Note, if you’re like me, you constantly flip between the source and the pdf. If that’s the case, evince will automatically update the pdf every time you re-build using pdflatex. Simply add “&” on the end of the command above:

evince hello.pdf &

This is what you should be seeing when completed:

Alternative: Rubber

I’d like to make a special note about the ‘rubber’ utility. It can take a lot of the guess work out of building LaTeX files and I strongly recommend using it over pdftex or pdflatex as mentioned above. You can install and run the ‘rubber’ utility with the following commands:

su -c 'yum install -y rubber'
rubber --pdf hello.tex

Conclusions

I hope this helps you get started moving quickly in the right direction. Comments and feedback are welcome.

A few difficulties I had when doing this for the first time were:

1
Aug

Installing lxml for Python and Run an Example

The goal of this guide is to install the lxml Python package and run the example cssutils Python script that uses the lxml package. This guide was written while running Ubuntu, but can be applied to any Linux distribution. Open up the terminal and let’s get started.

Step 1: Install easy_install For Python

The easy_install binary is a Python package manager that makes it easy to install cssutils. The following steps will get this installed:

sudo apt-get install curl
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py

Step 2: Install Required Linux Packages for lxml

Now, we install the required Linux packages for installing lxml Python package.

sudo apt-get install libxml2-dev libxslt-dev python-dev

Step 3: Install the lxml and cssutils Python Packages

Next, install the lxml and cssutils Python packages using easy_install.

sudo easy_install lxml
sudo easy_install cssutils

Step 4: Prepare lxml Example

The following is a script copy/pasted from http://cssutils.googlecode.com/svn/trunk/examples/style.py. Copy paste this to your favorite text editor and save it. I named it lxml_test.py.

# -*- coding: utf-8 -*-
"""
example renderer

moves infos from external stylesheet "css" to internal @style attributes
and for debugging also in @title attributes.

adds css as text to html
"""
from pprint import pprint
import codecs
import cssutils
import os
import sys
import webbrowser

# lxml egg may be in a lib dir below this file (not in SVN though)
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
try:
    import pkg_resources
    pkg_resources.require('lxml')
except pkg_resources.DistributionNotFound, e:
    pass

try:
    from lxml import etree
    from lxml.builder import E
    from lxml.cssselect import CSSSelector
except ImportError, e:
    print 'You need lxml for this example:', e
    sys.exit(1)

def log(level, *msg):
    """print '%s- %s' % (level * 't ',
                      ' '.join((str(m) for m in msg)))"""

def getDocument(html, css=None):
    """
    returns a DOM of html, if css is given it is appended to html/body as
    pre.cssutils
    """
    document = etree.HTML(html)
    if css:
        # prepare document (add css for debugging)
        e = etree.Element('pre', {'class': 'cssutils'})
        e.text = css
        document.find('body').append(e)
    return document

def styleattribute(element):
    "returns css.CSSStyleDeclaration of inline styles, for html: @style"
    cssText = element.get('style')
    if cssText:
        return cssutils.css.CSSStyleDeclaration(cssText=cssText)
    else:
        return None

def getView(document, css, media='all', name=None,
            styleCallback=lambda element: None):
    """
    document
        a DOM document, currently an lxml HTML document
    css
        a CSS StyleSheet string
    media: optional
        TODO: view for which media it should be
    name: optional
        TODO: names of sheets only
    styleCallback: optional
        should return css.CSSStyleDeclaration of inline styles, for html
        a style declaration for ``element@style``. Gets one parameter
        ``element`` which is the relevant DOMElement

    returns style view
        a dict of {DOMElement: css.CSSStyleDeclaration} for html
    """
    sheet = cssutils.parseString(css)

    view = {}
    specificities = {} # needed temporarily 

    # TODO: filter rules simpler?, add @media
    rules = (rule for rule in sheet if rule.type == rule.STYLE_RULE)
    for rule in rules:
        for selector in rule.selectorList:
            log(0, 'SELECTOR', selector.selectorText)
            # TODO: make this a callback to be able to use other stuff than lxml
            cssselector = CSSSelector(selector.selectorText)
            matching = cssselector.evaluate(document)
            for element in matching:
                #if element.tag in ('div',):
                    # add styles for all matching DOM elements
                    log(1, 'ELEMENT', id(element), element.text)

                    if element not in view:
                        # add initial empty style declatation
                        view[element] = cssutils.css.CSSStyleDeclaration()
                        specificities[element] = {}                    

                        # and add inline @style if present
                        inlinestyle = styleCallback(element)
                        if inlinestyle:
                            for p in inlinestyle:
                                # set inline style specificity
                                view[element].setProperty(p)
                                specificities[element][p.name] = (1,0,0,0)

                    for p in rule.style:
                        # update style declaration
                        if p not in view[element]:
                            # setProperty needs a new Property object and
                            # MUST NOT reuse the existing Property
                            # which would be the same for all elements!
                            # see Issue #23
                            view[element].setProperty(p.name, p.value, p.priority)
                            specificities[element][p.name] = selector.specificity
                            log(2, view[element].getProperty('color'))

                        else:
                            log(2, view[element].getProperty('color'))
                            sameprio = (p.priority ==
                                        view[element].getPropertyPriority(p.name))
                            if not sameprio and bool(p.priority) or (
                               sameprio and selector.specificity >=
                                            specificities[element][p.name]):
                                # later, more specific or higher prio
                                view[element].setProperty(p.name, p.value, p.priority)

    #pprint(view)
    return view                        

def render2style(document, view):
    """
    - add style into @style attribute
    - add style into @title attribute (for debugging)
    """
    for element, style in view.items():
        v = style.getCssText(separator=u'')
        element.set('style', v)
        element.set('title', v)

def render2content(document, view, css):
    """
    - add css as <style> element to be rendered by browser
    - replace elements content with actual style

    result is a HTML which the browser renders itself from the original css
    cssutils only writes debugging, useful to compare with render2style
    """
    e = etree.Element('style', {'type': 'text/css'})
    e.text = css
    document.find('head').append(e)
    for element, style in view.items():
        v = style.getCssText(separator=u'')
        element.text = v

def show(text, name, encoding='utf-8'):
    "saves text to file with name and encoding"
    f = codecs.open(name, 'w', encoding=encoding)
    f.write(text)
    f.close()
    webbrowser.open(name)

def main():
    tpl = '''<html><head><title>style test</title></head><body>%s</body></html>'''
    html = tpl % '''
            <h1>Style example 1</h1>
            <p>&lt;p></p>
            <p style="color: red;">&lt;p> with inline style: "color: red"</p>
            <p id="x" style="color: red;">p#x with inline style: "color: red"</p>
            <div>a &lt;div> green?</div>
            <div id="y">#y pink?</div>
        '''
    css = r'''
        * {
            margin: 0;
            }
        body {
            color: blue !important;
            font: normal 100% sans-serif;
        }
        p {
            color: green;
            font-size: 2em;
        }
        p#x {
            color: black !important;
        }
        div {
            color: green;
            font-size: 1.5em;
            }
        #y {
            color: #f0f;
            }
        .cssutils {
            font: 1em "Lucida Console", monospace;
            border: 1px outset;
            padding: 5px;
        }
    '''
    # TODO:
    #defaultsheet = cssutils.parseFile('sheets/default_html4.css')

    # adds style to @style
    document = getDocument(html, css)
    view = getView(document, css, styleCallback=styleattribute)
    render2style(document, view)
    text = etree.tostring(document, pretty_print=True)
    show(text, '__tempinline.html')

    # replaces elements content with style
    document = getDocument(html)
    view = getView(document, css, styleCallback=styleattribute)
    render2content(document, view, css)
    text = etree.tostring(document, pretty_print=True)
    show(text, '__tempbrowser.html')

if __name__ == '__main__':
    import sys
    sys.exit(main())

Step 5: Run lxml Example

Finally, run the example program.

python lxml_test.py

Conclusions

I’m hoping this guide met the goal of teaching you how to install lxml and run an example Python script to demonstrate some capabilities of lxml and cssutils. Feedback is welcomed and appreciated.

29
Jul

Installing cssutils for Python and Run an Example

The goal of this guide is to show you how to install and run the example Python script for cssutils from start to finsih. This was created while running Ubuntu, but can be applied and modified to any distribution. Open up a terminal and let’s get to it!

Step 1: Install easy_install For Python

The easy_install binary is a Python package manager that makes it easy to install cssutils. The following steps will get this installed:

sudo apt-get install curl
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py

Step 2: Install cssutils Python Package

Now we’ll install the cssutils package for Python using easy_install.

sudo easy_install cssutils

Step 3: Prepare cssutils Example

Next, you can copy/paste the following example into your favorite text editor and save it (I saved it as cssutils_test.py).

import cssutils

css = u'''/* a comment with umlaut � */
     @namespace html "http://www.w3.org/1999/xhtml";
     @variables { BG: #fff }
     html|a { color:red; background: var(BG) }'''
sheet = cssutils.parseString(css)

for rule in sheet:
    if rule.type == rule.STYLE_RULE:
        # find property
        for property in rule.style:
            if property.name == 'color':
                property.value = 'green'
                property.priority = 'IMPORTANT'
                break
        # or simply:
        rule.style['margin'] = '01.0eM' # or: ('1em', 'important')

sheet.encoding = 'ascii'
sheet.namespaces['xhtml'] = 'http://www.w3.org/1999/xhtml'
sheet.namespaces['atom'] = 'http://www.w3.org/2005/Atom'
sheet.add('atom|title {color: #000000 !important}')
sheet.add('@import "sheets/import.css";')

# cssutils.ser.prefs.resolveVariables == True since 0.9.7b2
print sheet.cssText

Step 4: Run cssutils Example

Finally, we can run the example.

python cssutils_test.py

Conclusions

I’m hoping this guide met the goal of teaching you how to install cssutils and run an example Python script to demonstrate some capabilities of cssutils. Feedback is welcomed and appreciated.

27
Jul

How To Install and Use Selenium Server in Linux

Selenium is a suite of tools to automate web browsers across many platforms in which you can write your tests in your preferred language. This guide intends on showing you how to install and run a Selenium test on a Linux box. Specifically, this guide was written using a default Fedora 15 installation and using Python as the preferred language. It can easily be applied to other distributions or other preferred languages. Now, open a terminal window and let’s get to it!

Step 1: Install the Selenium Server Package and Python Setup Tools

First, we need to install the selenium-server and python-setuptools packages. The first is obvious: we need the server. The second is for easy_install so we can install the Selenium Python package. Open the terminal and paste the following command.

su -c 'yum install -y selenium-server python-setuptools'

Step 2: Install the Selenium Server Package

Now, we need to install the Python selenium package.

su -c 'easy_install selenium'

Step 3: Startup Selenium Server

Next is starting the selenium server. This is done simply by running the following command as a normal user. I suggest opening in a new terminal window or add “&” to the end to push it to the background so you can continue working in the current terminal.

selenium-server

Step 4: Create a Selenium Test

You can then create a test from scratch or by using the Selenium IDE via Firefox plugin that you can download here: http://seleniumhq.org/download/. Read more about it here: http://seleniumhq.org/projects/ide/.

A note about using the Firefox plugin while running Linux (at the time of this writing). You must enable the experimental features before you can export the created test to Python (or any) code. To do this, open the preferences of the plugin and then make the following changes:

Options -> Options.... -> Enable Experimental Features
Options -> Format -> Python 2

Now, you should be able to copy/paste the output into your favorite editor and save it as a python script.

To get you going, here’s a working script that you can copy/paste into your favorite text editor:

from selenium import selenium
import unittest, time, re

class Google(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*chrome", "http://www.google.com/")
        self.selenium.start()

    def test_google(self):
        sel = self.selenium
        sel.open("/#hl=en&xhr=t&q=Selenium+IDE+Download&cp=14&pf=p&sclient=psy&biw=1920&bih=866&source=hp&aq=0&aqi=&aql=&oq=Selenium+IDE+D&pbx=1&bav=on.2,or.r_gc.r_pw.&fp=fce33a84b0764b22")
        sel.type("lst-ib", "Selenium IDE Download")

# Uncomment to close the server when finished with test.
#    def tearDown(self):
#        self.selenium.stop()
#        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

Step 5: Run a Selenium Test

Now, we’ll run the test. After running the following command, you should see Firefox open, navigate to http://www.google.com, and perform a search.

python google_test.py

Conclusions

If you’re wondering where to go next or looking for other useful tools, check out the following page from the NetBeans webpage: http://netbeans.org/kb/docs/php/phpunit.html.

17
Jun

How To: Install VirtualBox 4.0 on Fedora 15

This is a step by step tutorial on how to get VirtualBox 4.0 up and running on Fedora 15 (Lovelock). Specifically, this guide was written using the VirtualBox 4.0 (32-bit) version (Package: kernel-devel.i686 0:2.6.38.8-32.fc15). It can be adapted to upcoming versions and different CPUs (64-bit). The folks at VirtualBox have made it easy to install for Fedora users and I’m going to show you how in a few easy steps. Open a terminal window and let’s get to it…
[Read more →]

1
Jun

Fedora 15 Lovelock on MacBook Aluminum [Guide]

This is a guide to get Fedora 15 running on a MacBook Aluminium. Specifically, it was written for the MacBook 5,1 generation, but I believe this should work on more recent generations as well. As with Fedora 14, there were many things that worked out of the box. The differences between Fedora 14 and Fedora 15 are: 1) bluetooth required a set of commands to be ran before it worked and 2) the keyboard backlight works out of the box. I have created this guide to help others get Fedora 15 installed on their MacBook Aluminum quickly. I hope to gain a lot of feedback so it can benefit other users who wish to use Fedora on a MacBook. I would also like to add that I used the live CD to install, not the DVD.

Notable frustrations:

[Read more →]

2
Nov

Fedora 14 Laughlin on MacBook Aluminum [Guide]

This is a guide to getting Fedora 14 Laughlin running on a MacBook Aluminium. Specifically, it was written for the MacBook 5,1 generation, but I believe this should work on more recent generations as well. As with Fedora 13, there were many things that worked out of the box. I have created this guide to help others get Fedora 14 installed on their MacBook Aluminum.
[Read more →]

2
Nov

How To: Install VirtualBox 3.2 on Fedora 14

This is a step by step tutorial on how to get VirtualBox 3.2 up and running on Fedora 14. Specifically, this guide was written using the VirtualBox 3.2.10 (32-bit) version. It can be adapted to upcoming versions and different CPUs (64-bit). The folks at VirtualBox have made it easy to install for Fedora users and I’m going to show you how in a few easy steps. Right, open a terminal window and let’s get to it…
[Read more →]

23
Aug

How To: Install shell-fm to Play last.fm Radio via Terminal

Here’s how to install shell-fm as tested on Fedora 14. shell-fm is a great little command line tool that will play last.fm radio and even has some features that last.fm doesn’t have (artist autoban, no advertisements, and more). You can read more about it here. Alright, let’s get to the install instructions!
[Read more →]

25
May

How To: Install VirtualBox 3.2 on Fedora 13

This is a step by step tutorial on how to get VirtualBox 3.2 up and running on Fedora 13. Specifically, this guide was written using the VirtualBox 3.2.0 (32-bit) version. It can be adapted to upcoming versions and different CPUs (64-bit). The folks at VirtualBox have made it easy to install for Fedora users and I’m going to show you how in a few easy steps. Right, open a terminal window and let’s get to it…
[Read more →]

Next Page »