Commit e68fc132 authored by Klaus-Uwe Mitterer's avatar Klaus-Uwe Mitterer

Check everything in

parents
__pycache__
*.swp
*.png
[settings]
length=5
special=1234567890$-%%&()!?
#!/usr/bin/env python3
import configparser
import random
class PasswordMaker():
def __init__(self, config = "fh_passphrase.ini", length = None, special = None):
if config:
self.read_config(config)
if length:
self.length = length
if special:
self.special = special
def read_config(self, config):
parser = configparser.ConfigParser()
parser.read(config)
try:
self.length = int(parser["settings"]["length"])
except:
self.length = 1
try:
self.special = parser["settings"]["special"]
except:
raise
self.special = [""]
def generate_password(self, sentence):
words = sentence.split()
if len(words) < self.length:
raise ValueError("Sentence must have at least %i words. " % self.length)
letters = [word[0] for word in words]
password = letters[0]
for letter in letters[1:]:
password += random.SystemRandom().choice(self.special)
password += letter
return password
def get_input(length = PasswordMaker().length):
return input("Enter a sentence with at least %i words: " % length)
if __name__ == "__main__":
print(PasswordMaker().generate_password(get_input()))
from fh_passphrase import PasswordMaker
from pytest import raises
def split_password(password):
letters = []
special = []
for i in range(len(password)):
if not i % 2:
letters += password[i]
else:
special += password[i]
return letters, special
def test_passwordmaker():
maker = PasswordMaker()
with raises(ValueError):
maker.generate_password("Short sentence.")
sentence = "This is a longer sentence."
password = maker.generate_password(sentence)
letters, special = split_password(password)
assert letters == [word[0] for word in sentence.split()]
assert len(special) == len(letters) - 1
for char in special:
assert char in maker.special
#!/usr/bin/env python3
import random
import time
import argparse
import matplotlib.pyplot
def draw_sample(limit = 45, count = 7, system = False):
rand = random.SystemRandom() if system else random
return rand.sample(range(1, limit + 1), count)
def generate_stats(results):
numbers = {}
for result in results:
for number in result:
try:
numbers[number] += 1
except KeyError:
numbers[number] = 1
return numbers
def run_draws(draws = 1, benchmark = False, statistics = False, *args, **kwargs):
results = []
start = time.time()
for __ in range(0, draws):
results += [draw_sample(*args, **kwargs)]
end = time.time()
if statistics:
results = generate_stats(results)
return (end - start) if benchmark else results
def generate_plot(results, outfile):
matplotlib.pyplot.bar(list(results.keys()), results.values())
matplotlib.pyplot.savefig(outfile)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--count", "-c", type=int, help="number of numbers per draw", default=7)
parser.add_argument("--draws", "-d", type=int, help="number of draws to simulate", default=1)
parser.add_argument("--limit", "-l", type=int, help="highest number to be drawn (lowest is always 1)", default=45)
parser.add_argument("--system", "-s", action="store_true", help="use more secure source of randomness (considerably slower)")
formats = parser.add_mutually_exclusive_group()
formats.add_argument("--benchmark", "-b", action="store_true", help="output time needed to process draws instead of numbers drawn")
formats.add_argument("--analysis", "-a", action="store_true", help="output statistics about draws instead of numbers drawn")
formats.add_argument("--graph", "-g", type=str, help="generate chart in file with statistics about draws instead of numbers drawn", metavar="FILE")
args = parser.parse_args()
output = run_draws(args.draws, args.benchmark, args.analysis or not not args.graph, args.limit, args.count, args.system)
if args.graph:
generate_plot(output, args.graph)
else:
print(output)
import lotto
def test_lotto():
no_system = lotto.run_draws(100000, True)
print("100,000 draws with default settings: %fs" % no_system)
system = lotto.run_draws(100000, True, system = True)
print("100,000 draws with system randomness: %fs" % system)
assert no_system < system
single_draw = lotto.run_draws()
assert len(single_draw) == 1
assert len(single_draw[0]) == 7
stats = lotto.run_draws(100000, statistics = True)
assert type(stats) == dict
lotto.generate_plot(stats, "lotto_histogramm.png")
print("Generated histogram as lotto_histogramm.png")
{}
\ No newline at end of file
[tax0]
above=11000
rate=25
[tax1]
above=18000
rate=35
[tax2]
above=31000
rate=42
[tax3]
above=60000
rate=48
[tax4]
above=90000
rate=50
[tax5]
above=1000000
rate=55
#!/usr/bin/env python3
import configparser
import argparse
class TaxRates:
def __init__(self, config = "einkommenssteuer.ini"):
self.rates = {}
if config:
self.read_file(config)
def read_file(self, config, replace = True):
if replace:
self.rates = {}
parser = configparser.ConfigParser()
parser.read(config)
levels = [level for level in parser.sections() if level.startswith("tax")]
for level in levels:
self.add_rate(parser[level]["above"], parser[level]["rate"])
def add_rate(self, above, rate):
self.rates[int(above)] = int(rate)
def get_rate(self, income):
rate = 0
for level in sorted(self.rates.items()):
if level[0] < income:
rate = level[1]
else:
break
return rate
def get_taxes(self, income):
return income / 100 * self.get_rate(income)
def get_taxes(income):
return TaxRates().get_taxes(income)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("income", help="income to calculate taxes for", type=float)
args = parser.parse_args()
print(get_taxes(args.income))
from einkommenssteuer import get_taxes
def test_get_taxes():
assert get_taxes(5000) == 0
assert get_taxes(1000000) == 500000
assert get_taxes(31500) == 31500 * 42 / 100
assert "nobody needs 10 fucking tests for this"
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment