Author Archive

Ein einfaches Python-Beispiel für Klassen und Funktionen

Hier noch ein einfaches Python-Beispiel für Klassen und Funktionen, das ich vor ein paar Tagen geschrieben habe. Die Punkt-Klasse erhält eine entsprechende Funktion, um die Euklidische Distanz zu einem anderen Punkt zu bestimmen.

# -*- coding: utf-8 -*-
import math as m
 
class Point:
 
    def __init__(self,x,y):
        self.x = x
        self.y = y
 
    def calcEuclidDistanceToPoint(self,x,y):
        return m.sqrt(m.pow(self.x-x,2) + m.pow(self.y-y,2))
 
p1 = Point(0,0)
p2 = Point(1,1)
print(p2.calcEuclidDistanceToPoint(p1.x,p1.y))
runfile('euclidDistance.py', wdir='E:/Python')
1.4142135623730951

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Lineare Gleichungen lösen mit numpy

Hier ein kurzes Beispiel aus der numpy-Dokumentation, wie man mit Hilfe von numpy lineare Gleichungssysteme lösen kann:

Zu lösen sind folgende Gleichungen:

  • 3 * x0 + 1 * x1 = 9
  • 1 * x0 + 2 * x1 = 8

Die Koeffizienten kommen in die entsprechenden numpy-Arrays, dann ruft man linalg.solve auf:

import numpy as np
 
a = np.array([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(a, b)
print(x) # gibt [ 2.  3.]

pff

Den Plot habe ich mit LaTeX erstellt, siehe http://uweziegenhagen.de/?p=3516.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Plots mit pgfplots

Hier ein kleines Beispiel für pgfplots, das ich aus diversen TSX Beiträgen für einen Python Artikel zusammengebaut habe:

\documentclass[12pt,english]{standalone}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\pagestyle{empty}
 
\begin{document}
\begin{tikzpicture}
\begin{axis}[
    domain=0:9,
    axis lines = center,
    xlabel = {$x$},
    ylabel = {$y = f(x)$},
    height=8cm, width=11cm, grid=major,grid style={dashed, gray!30},
    xmin=-1, xmax=10, ymin=-1, ymax=7,xtick={1,2,...,10},ytick={1,2,...,6}]
 
\addplot[draw=red,domain=0:8]{-0.5*x+4};
\addplot[draw=blue,domain=1:3]{-3*x+9};
\end{axis}
\end{tikzpicture}
\end{document}

pff

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Parallel LaTeXing with Python Threads

Based on an example from stackexchange I have created a small example on parallel TeX compilation.

# -*- coding: utf-8 -*-
"""
Created on 2016-07-06
Uwe Ziegenhagen
based on http://stackoverflow.com/questions/16181121/python-very-simple-multithreading-parallel-url-fetching-without-queue
"""
 
from multiprocessing.pool import ThreadPool
from time import time as timer
import os
 
files = ['test-01.tex','test-02.tex','test-03.tex','test-04.tex','test-05.tex',
'test-06.tex','test-07.tex','test-08.tex','test-09.tex','test-10.tex']
 
def compile_file(cfile):
	try:
		result = os.system('pdflatex -interaction=batchmode ' + cfile)
		return cfile, None
	except Exception as e:
		return cfile, e	
 
start = timer()
results = ThreadPool(8).imap_unordered(compile_file, files)
for cfile, error in results:
	if error is None:
		print("%r compiled in %ss" % (cfile, timer() - start))
	else:
		print("Error compiling %r: %s" % (cfile, error))
		print("Elapsed Time: %s" % (timer() - start,))
 
print('Gesamtzeit',timer() - start)

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Fokussiertes Arbeiten mit Emacs / Distraction-free Emacs

Editoren, die minimales Design statt Mengen von Menüs und Buttons aufweisen, sind in den letzten Jahren sehr modern geworden. IA Writer für Mac OS X und iOS, Writemonkey für Windows sind nur einige Beispiele. Mit Emacs geht das natürlich auch… Hier ein paar Codeschnipsel mit den entsprechenden URLs.

;; distraction-free
;;  https://nickhigham.wordpress.com/2016/01/14/distraction-free-editing-with-emacs/
(scroll-bar-mode 0)    ; Turn off scrollbars.
(tool-bar-mode 0)      ; Turn off toolbars.
(fringe-mode 0)        ; Turn off left and right fringe cols.
(menu-bar-mode 0)      ; Turn off menus.
;; bind fullscreen toggle to f9 key
(global-set-key (kbd "") 'toggle-frame-fullscreen)

;; http://emacs.stackexchange.com/questions/2999/how-to-maximize-my-emacs-frame-on-start-up
;; Start fullscreen (cross-platf)
(add-hook 'window-setup-hook 'toggle-frame-fullscreen t)
; emacs-doctor.com/emacs-strip-tease.html
;; Prevent the cursor from blinking
(blink-cursor-mode 0)
;; Don't use messages that you don't read
(setq initial-scratch-message "")
(setq inhibit-startup-message t)
;; Don't let Emacs hurt your ears
(setq visible-bell t)
(custom-set-faces
  '(default ((t (:background "black" :foreground "darkgrey"))))
  '(fringe ((t (:background "black")))))

distrfree_emacs

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Das „Currentfile“ Paket

Hier ein Beispiel für das currentfile Paket. Während \jobname auch bei eingebundenen Dateien nur den Namen der Hauptdatei ausspuckt, kann man mit den Befehlen des currentfile Pakets auf die einzelnen Dateien zugreifen.

\documentclass{scrartcl}
\usepackage{filecontents}
\usepackage{currfile}
 
\begin{filecontents}{curr02.tex}
 
Ich bin der Inhalt einer Datei, die eingebunden wird. \verb|\jobname| enthält: \jobname
 
	\begin{itemize}
		\item \verb|\currfilebase|: \currfilebase
		\item \verb|\currfilename|: \currfilename
		\item \verb|\currfileext|: \currfileext
		\item \verb|\currfiledir|: \currfiledir
		\item \verb|\currfilepath|: \currfilepath
	\end{itemize}
 
\end{filecontents}
 
\begin{document}
 
	\begin{itemize}
		\item \verb|\currfilebase|: \currfilebase
		\item \verb|\currfilename|: \currfilename
		\item \verb|\currfileext|: \currfileext
		\item \verb|\currfiledir|: \currfiledir
		\item \verb|\currfilepath|: \currfilepath
	\end{itemize}
 
\input{curr02}
 
\end{document}

currfile

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Excel: Formel nur auf die x-te Zeile anwenden

Hier ein kurzes Beispiel für die Nutzung der Rest() Funktion, um Formeln in Excel nur auf jede x-te Zeile anzuwenden.

  1. Mit zeile() erhält man die Zeilennummer des aktuellen Bezugs
  2. Rest() gibt den Rest bei der ganzzahligen Teilung zurück
  3. Wenn() prüft einfach die Bedingung, ob Rest() einen bestimmten Wert hat

Man kann nicht nur gerade/ungerade prüfen (oberes Beispiel), auch bei anderen Zeilensprüngen klappt das.

excel

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Vortragsfolien „Klausurerstellung mit LaTeX“, Dante-Frühjahrstagung in Wuppertal

Hier meine Folien zum Vortrag in Wuppertal, zusammen mit den entsprechenden Quellen (auch für die Beamer Folien)

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Spalte aus Text-Datei extrahieren mit Python

Hier ein Quick & Dirty Code, um eine Spalte aus einer Text-Datei zu extrahieren. Geht auch mit AWK, aber wenn man nur Python hat…

def splitFileOneColumn(inputFile,outputFile,columnSeparator,column):
    with open(inputFile, 'r') as infile:
        with open(outputFile, 'w') as outfile:
            for line in infile:
                s = line.split(columnSeparator)
                outfile.write(s[column]+os.linesep) # '\r\n' on Windows, '\n' on Unix/Linux/Mac
            outfile.close()
    infile.close()

Bei Gelegenheit muss ich das mal um die Möglichkeit erweitern, n Spalten zu extrahieren.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Excel VBA: Blatt in Liste von Excel Dateien kopieren

Eine Aufgabe für zwischendurch: Wie kann man ein bestehendes Excel-Blatt in eine Anzahl von anderen Excel-Dateien kopieren?

  • Definiere eine benannte Zell-Range, hier „Workbooks“ genannt
  • In dieser Liste trage alle Excel-Dateien ein, in die das Muster-Blatt (hier „Template“ genannt) kopiert werden soll.
    Hinweis: Ich habe diese Liste mit dir /b *.xlsx erzeugt.
  • Setze einen Button in das Sheet und hinterlege als Code das folgende
  • Wichtig: Die aktuelle Arbeitsmappe mit dem Button und der Liste liegt im selben Verzeichnis wie die Ziel-Dateien. Wenn nicht, dann muss der Pfad angepasst werden.
Sub Schaltfläche1_Klicken()
 
Dim c As Range
For Each c In Range("Workbooks")
    MsgBox (c.Value)
    Set kopiereWas = ThisWorkbook.Sheets("Template")
    Set kopiereWohin = Workbooks.Open(Application.ActiveWorkbook.Path + "\\" + c.Value)
    kopiereWas.Copy kopiereWohin.Sheets(1)
Next c
End Sub

Hinweis: Die Ziel-Arbeitsmappe wird hier nicht geschlossen, werde ich zusammen mit Screenshots nachliefern.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website