Looping with LaTeX — Generating Name Cards

Today I had to generate a few name cards, LaTeX and the pgffor command came very handy doing that. I am not entirely satisfied with this solution, since the margins are hardwired, so if you have a better way just tell me.


\foreach \x in {Manfred Mustermann, Gabi Mustermann, Manuela Mustermann}{
[mybox/.style={rectangle,black,xshift=0cm,yshift=0cm,minimum width=0.975\textwidth,font=\bfseries,draw=black,very thick,align=center, minimum height=0.475\textheight}]
\node at (0,0) [mybox] {\x};
\node at (0,0.475\textheight) [mybox] {};



Reading CSV files with LaTeX

Reading CSV files is pretty easy in LaTeX, thanks to Nicola Talbot’s datatool package.

When you have an Excel file like the following Schueler.xlsx, simply save it as CSV (Comma-Separated Value).


If you open the CSV file “Schueler.csv” in a text editor you get the following:


We start by loading the datatool package. Since the German Excel uses semicolons as column separator, we are required to manually set the delimiter. In the next line we tell LaTeX to use our Schueler.csv file and to reference it as “scores”. In the DTLforeach commands the magic happens. The command has three parameters:

  • the file reference
  • the assignment of the file headers to LaTeX commands
  • the loop where the output for each row is defined




\bfseries Name &
\bfseries Aufgabe A &
\bfseries Aufgabe B %
\name & \aufgabea & \aufgabeb }


\name\ hat in Aufgabe A  \aufgabea~Punkte erzielt, in Aufgabe B \aufgabeb~Punkte.}



Simple looping with LaTeX

Here’s a fairly easy example how to loop through a LaTeX collection/list with the help of the pgffor package


\foreach \x in {Donald,Dagobert,Gustav,Goofy} {\item \x}



Ostern mit Python bestimmen

Die Oster-Formel der Wikipedia kann man recht einfach in einem Python-Algorithmus nutzen:

import datetime
def calcEaster(jahr):
	a = jahr % 19 
	b = jahr % 4  
	c = jahr % 7  
	k = jahr / 100
	p = (8 * k  + 13) / 25
	q = k / 4
	M = (15 + k - p - q) % 30
	d = (19 * a + M) % 30
	N = (4 + k - q) % 7
	e = (2 * b + 4 * c + 6 * d + N) % 7
	Ostermontag = (22 + d + e) - 1
	start = datetime.datetime.strptime("01.03." + str(jahr), "%d.%m.%Y")
	easter = start + datetime.timedelta(days=round(Ostermontag))
	return easter.strftime('%d.%m.%Y')
for i in range(2014,2050):

Deutsches Beispiel für die “exam” Dokumentenklasse

Hier ein eingedeutschtes Beispiel für die exam Klasse, mit der sich recht einfach Klausuren setzen lassen.

Edit 30.12.2014: Nach Hinweisen von Axel Kielhorn habe ich das Beispiel noch erweitert.

\chbpword{Bonus Punkte} 
\firstpageheader{Links oben}{Mitte oben}{\today}
\runningheader{Links oben}{Mitte oben}{\today}
\firstpagefooter{Links unten}{Mitte unten}{\thepage\,/\,\numpages}
\runningfooter{Links unten}{Mitte unten}{\thepage\,/\,\numpages}
\question[4] Warum gibt es Luft?
Damit wir atmen können.
\bonusquestion[2] Wieviel Luft gibt es?
Ziemlich viel.
\question[5] Warum gibt es Sauerstoff?
\question Was wäre, wenn es keine Luft gäbe?
\part[5] Was würde mit Luftballons geschehen? 
\bonuspart[6] Wie könnten Fluggesellschaften damit umgehen?
\question [100] Wird es morgen schneien?
\CorrectChoice Ja
\choice Nein
\choice Vielleicht
\question Ein Name der folgenden Reihe passt nicht zu den anderen. Welcher?
\choice Donald
\choice Dagobert
\choice Daisy
\choice Micky
\CorrectChoice Balu


Checking TeX files for cite-errors

Today I had to TeX a longer file with numerous \cite[somestuff]{citekey} sequences, of which some had hard-to-spot errors (some ‘]’ were missing). The following Python script checks if each \cite command has matching '[]' and '{}' sequences. I’ll probably extend this script to accept simple \cite{citekey} sequences that have no optional parameter.

import re
with open('filetocheck.tex') as f:
	content = f.readlines()
index = 0
for a in content:
	index = index + 1
	if "cite"  in a: # check only lines that contain 'cite'
		matches = re.search(r'(.*)\[(.*)\]\{(.*)\}',a) # search for <sometext>[<sometext>]{<sometext>}
		if not matches:
			print (">>> Fail in row" , str(index), a)

Beamer Slides Template using Source Sans Fonts

Here’s a short example for a Beamer slide template using the Adobe Source Sans fonts.

    basicstyle=\ttfamily\footnotesize, %
    identifierstyle=\color{colIdentifier}, %
    keywordstyle=\color{colKeys}, %
    stringstyle=\color{colString}, %
    commentstyle=\color{colComments}, %
    columns=flexible, %
    tabsize=2, %
    frame=single, %
    extendedchars=true, %
    showspaces=false, %
    showstringspaces=false, %
    numbers=left, %
    numberstyle=\tiny, %
    breaklines=true, %
    backgroundcolor=\color{colBack}, %
    breakautoindent=true, %
\author{Uwe Ziegenhagen}
\title{Titel der Präsentation}
\frametitle{Titel der Folie}
\framesubtitle{Untertitel der Folie}
\item Erstes Item
\item Zweites Item
\item Drittes Item
\lstinputlisting[language={[LaTeX]TeX},basicstyle=\ttfamily\tiny,linerange={1-12},caption={Auszug aus der Präambel dieser Präsentation},label={lis:tex01}]{\jobname.tex}



Creating MD5 files with Python

Here’s the probably last part of this series, the missing piece showing the calculation of MD5 files with Python:

# http://www.pythoncentral.io/hashing-files-with-python/
import hashlib
import os
import codecs
hasher = hashlib.md5()
def calcHash(filename):
	print("Filename:   " + filename)
	with open(filename, 'rb') as afile:
		buf = afile.read()
		print("Calculated: " + hasher.hexdigest())
		md5file = (os.path.splitext(filename)[0]) + ".md5"
		writeMD5 = codecs.open(md5file, "wb", "utf-8-sig")

Using Powershell to create MD5 files

Following up on an article a few days ago here’s a script that creates a MD5 file.

# Uwe Ziegenhagen, 12.11.2014
# Reference: http://onlinemd5.com/
### Step A: Get the name of the file
# http://blogs.technet.com/b/heyscriptingguy/archive/2009/09/01/hey-scripting-guy-september-1.aspx
Function Get-FileName($initialDirectory)
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "All files (*.*)| *.*"
$OpenFileDialog.ShowDialog() | Out-Null
} #end function Get-FileName
# *** Entry Point to Script ***
$file =  Get-FileName -initialDirectory "C:\"
# write-host "file: " $file
### Step B: Create a file handle from this string and calculate the MD5 sum
$filehandle = Get-ChildItem $file
write-host "Filename: " $filehandle.Name
# http://stackoverflow.com/questions/10521061/how-to-get-an-md5-checksum-in-powershell
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($filehandle))).ToLower().Replace("-","")
write-host "Calculated Hashsum: "  $hash
### Step C: Write the MD5 sum from the MD5 sum file matching the other filename
$hash | out-file -FilePath $($filehandle.DirectoryName + "\" + $filehandle.BaseName + ".md5")

SQL: Splitting a Bitmask into separate columns

Today I needed to split an integer (representing a bitmask) into its components, each component in a separate column. The following code from http://www.sqlservercentral.com/Forums/Topic1101943-392-1.aspx did the trick.

   SIGN(N & 1) AS Bit1,
   SIGN(N & 2) AS Bit2,
   SIGN(N & 4) AS Bit3,
   SIGN(N & 8) AS Bit4,
   SIGN(N & 16) AS Bit5,
   SIGN(N & 32) AS Bit6,
   SIGN(N & 64) AS Bit7,
   SIGN(N & 128) AS Bit8
   SELECT 511
) TestData(N)