Stilforbedringer+

This commit is contained in:
Trygve 2022-06-27 14:26:32 +02:00
parent d3c6b6977a
commit 38cc7c7672

313
otime.py
View File

@ -10,49 +10,19 @@ from fpdf import FPDF
# The event object stores all the event data. # The event object stores all the event data.
# A .otime file is more or less just a json dump of the Event object. # A .otime file is more or less just a json dump of the Event object.
class Event: class Event:
def __init__(self, eventid, name, **kwargs): def __init__(self, eventid, name, start_time=None, end_time=None,
organiser=None, courses=[], o_classes=[], runners=[],
card_dumps=[], fees=[]):
self.id = eventid self.id = eventid
self.name = name self.name = name
self.start_time = start_time
try: self.end_time = end_time
self.start_time = kwargs['start_time'] self.organiser = organiser
except KeyError: self.courses = courses
self.start_time = None self.o_classes = o_classes
self.runners = runners
try: self.card_dumps = card_dumps
self.end_time = kwargs['end_time'] self.fees = fees
except KeyError:
self.end_time = None
try:
self.organiser = kwargs['organiser']
except KeyError:
self.organiser = None
try:
self.courses = kwargs['courses']
except KeyError:
self.courses = []
try:
self.o_classes = kwargs['o_classes']
except KeyError:
self.o_classes = []
try:
self.runners = kwargs['runners']
except KeyError:
self.runners = []
try:
self.card_dumps = kwargs['card_dumps']
except KeyError:
self.card_dumps = []
try:
self.fees = kwargs['fees']
except KeyError:
self.fees = []
def add_course(self, *args): def add_course(self, *args):
for n in args: for n in args:
@ -78,24 +48,25 @@ class Event:
tree = ET.parse(xml_file) tree = ET.parse(xml_file)
root = tree.getroot() root = tree.getroot()
event_el = root.find('./{http://www.orienteering.org/datastandard/3.0}Event') url = '{http://www.orienteering.org/datastandard/3.0}'
event_id = int(event_el.find('./{http://www.orienteering.org/datastandard/3.0}Id').text) event_el = root.find(f'./{url}Event')
name = event_el.find('./{http://www.orienteering.org/datastandard/3.0}Name').text event_id = int(event_el.find(f'./{url}Id').text)
organiser = event_el.find('./{http://www.orienteering.org/datastandard/3.0}Organiser/{http://www.orienteering.org/datastandard/3.0}Name').text name = event_el.find(f'./{url}Name').text
organiser = event_el.find(f'./{url}Organiser/{url}Name').text
start_ds = event_el.find('./{http://www.orienteering.org/datastandard/3.0}StartTime/{http://www.orienteering.org/datastandard/3.0}Date').text start_ds = event_el.find(f'./{url}StartTime/{url}Date').text
start_ts = event_el.find('./{http://www.orienteering.org/datastandard/3.0}StartTime/{http://www.orienteering.org/datastandard/3.0}Time').text[:-1] start_ts = event_el.find(f'./{url}StartTime/{url}Time').text[:-1]
start_time = datetime.datetime.fromisoformat(f'{start_ds}T{start_ts}') start_time = datetime.datetime.fromisoformat(f'{start_ds}T{start_ts}')
end_ds = event_el.find('./{http://www.orienteering.org/datastandard/3.0}EndTime/{http://www.orienteering.org/datastandard/3.0}Date').text end_ds = event_el.find(f'./{url}EndTime/{url}Date').text
end_ts = event_el.find('./{http://www.orienteering.org/datastandard/3.0}EndTime/{http://www.orienteering.org/datastandard/3.0}Time').text[:-1] end_ts = event_el.find(f'./{url}EndTime/{url}Time').text[:-1]
end_time = datetime.datetime.fromisoformat(f'{end_ds}T{end_ts}') end_time = datetime.datetime.fromisoformat(f'{end_ds}T{end_ts}')
runners = runners_from_xml_entries(xml_file) runners = runners_from_xml_entries(xml_file)
fees = fees_from_xml_entries(xml_file) fees = fees_from_xml_entries(xml_file)
return Event(event_id, name, organiser=organiser, runners=runners, return Event(event_id, name, organiser=organiser, runners=runners,
fees=fees, start_time=start_time, end_time=end_time) fees=fees, start_time=start_time, end_time=end_time)
def import_ttime_cnf(self, ttime_file): def import_ttime_cnf(self, ttime_file):
self.add_course(*courses_from_ttime_conf(ttime_file)) self.add_course(*courses_from_ttime_conf(ttime_file))
@ -119,6 +90,7 @@ class Event:
for d in self.card_dumps: for d in self.card_dumps:
if r.card == d.card: if r.card == d.card:
r.card_r = d r.card_r = d
def match_runners_o_classes(self): def match_runners_o_classes(self):
for r in self.runners: for r in self.runners:
for c in self.o_classes: for c in self.o_classes:
@ -136,6 +108,7 @@ class Event:
for f in self.fees: for f in self.fees:
if r.fee_id == f.id: if r.fee_id == f.id:
r.fee = f r.fee = f
def match_all(self): def match_all(self):
self.match_runners_cards() self.match_runners_cards()
self.match_runners_o_classes() self.match_runners_o_classes()
@ -214,13 +187,10 @@ class Event:
# </SplitTime> # </SplitTime>
elif n.status() == 'Disqualified': elif n.status() == 'Disqualified':
xml_child(result, 'Status', n.status()) xml_child(result, 'Status', n.status())
controls = copy(n.card_r.controls)
splits = copy(n.card_r.splits)
for code, split in zip(n.res_codes(), n.res_splits()): for code, split in zip(n.res_codes(), n.res_splits()):
st = ET.SubElement(result, 'SplitTime') st = ET.SubElement(result, 'SplitTime')
xml_child(st, 'ControlCode', code) xml_child(st, 'ControlCode', code)
if split != None: if split is not None:
xml_child(st, 'Time', split) xml_child(st, 'Time', split)
else: else:
xml_child(result, 'Status', n.status()) xml_child(result, 'Status', n.status())
@ -256,6 +226,9 @@ class Event:
json_data = { json_data = {
'id': self.id, 'id': self.id,
'name': self.name, 'name': self.name,
'orginser': self.organiser,
'start_time': self.start_time.isoformat(),
'end_time': self.end_time.isoformat(),
'runners': rdicts, 'runners': rdicts,
'courses': cdicts, 'courses': cdicts,
'o_classes': ocdicts, 'o_classes': ocdicts,
@ -269,11 +242,15 @@ class Event:
data = json.load(f) data = json.load(f)
runners = [] runners = []
for r in data['runners']: for r in data['runners']:
runners.append(Runner(r['id'], r['first'], r['last'], club_id=r['club_id'], club=r['club'], country=r['country'], card=r['card'], o_class_str=r['o_class_str'], fork=r['fork'],start_time=r['start_time'])) runners.append(Runner(r['id'], r['first'], r['last'], club_id=r['club_id'],
club=r['club'], country=r['country'], card=r['card'],
o_class_str=r['o_class_str'], fork=r['fork'],
start_time=r['start_time'], fee_id=int(r['fee_id'])))
courses = [] courses = []
for c in data['courses']: for c in data['courses']:
courses.append(Course(c['name'], c['codes'], forked=c['forked'], variations=c['variations'])) courses.append(Course(c['name'], c['codes'], forked=c['forked'],
variations=c['variations']))
o_classes = [] o_classes = []
for c in data['o_classes']: for c in data['o_classes']:
@ -281,13 +258,22 @@ class Event:
card_dumps = [] card_dumps = []
for d in data['card_dumps']: for d in data['card_dumps']:
card_dumps.append(CardDump(d['card'], d['controls'], d['splits'], datetime.datetime.fromisoformat(d['read_time']), datetime.datetime.fromisoformat(d['s_time']), datetime.datetime.fromisoformat(d['f_time']))) card_dumps.append(CardDump(d['card'], d['controls'], d['splits'],
datetime.datetime.fromisoformat(d['read_time']),
datetime.datetime.fromisoformat(d['s_time']),
datetime.datetime.fromisoformat(d['f_time'])))
fees = [] fees = []
for f in data['fees']: for f in data['fees']:
fees.append(Fee(f['id'], f['name'], f['currency'], f['amount'], from_birth_date=f['from_birth_date'], to_birth_date=f['to_birth_date'])) fees.append(Fee(f['id'], f['name'], f['currency'], f['amount'],
from_birth_date=f['from_birth_date'],
to_birth_date=f['to_birth_date']))
return Event(data['id'], data['name'], runners=runners, courses=courses, o_classes=o_classes, card_dumps=card_dumps) return Event(data['id'], data['name'], organiser=data['orginiser'],
start_time=datetime.datetime.fromisoformat(data['start_time']),
end_time=datetime.datetime.fromisoformat(data['end_time']),
runners=runners, courses=courses, o_classes=o_classes,
card_dumps=card_dumps, fees=fees)
def create_start_list_pdf(self, file_name): def create_start_list_pdf(self, file_name):
pdf = FPDF() pdf = FPDF()
@ -300,7 +286,7 @@ class Event:
pdf.multi_cell(col_width, line_height, runner.fullname(), border=1, ln=3, max_line_height=pdf.font_size, align='L') pdf.multi_cell(col_width, line_height, runner.fullname(), border=1, ln=3, max_line_height=pdf.font_size, align='L')
pdf.multi_cell(col_width, line_height, runner.o_class_str, border=1, ln=3, max_line_height=pdf.font_size) pdf.multi_cell(col_width, line_height, runner.o_class_str, border=1, ln=3, max_line_height=pdf.font_size)
pdf.multi_cell(col_width, line_height, str(runner.card), border=1, ln=3, max_line_height=pdf.font_size) pdf.multi_cell(col_width, line_height, str(runner.card), border=1, ln=3, max_line_height=pdf.font_size)
if runner.start_time != None: if runner.start_time is not None:
pdf.multi_cell(col_width, line_height, str(runner.start_time), border=1, ln=3, max_line_height=pdf.font_size) pdf.multi_cell(col_width, line_height, str(runner.start_time), border=1, ln=3, max_line_height=pdf.font_size)
else: else:
pdf.multi_cell(col_width, line_height, '', border=1, ln=3, max_line_height=pdf.font_size) pdf.multi_cell(col_width, line_height, '', border=1, ln=3, max_line_height=pdf.font_size)
@ -308,7 +294,7 @@ class Event:
pdf.output(file_name) pdf.output(file_name)
def create_all_invoices(self, filename_prefix): def create_all_invoices(self, filename_prefix):
clubs = [x.club for x in self.runners if x.club != self.runners[self.runners.index(x)-1].club] clubs = [x.club for x in self.runners if x.club != self.runners[self.runners.index(x)-1].club and x.club is not None]
for club in clubs: for club in clubs:
self.create_club_invoice(club, filename_prefix + club + '.pdf') self.create_club_invoice(club, filename_prefix + club + '.pdf')
@ -318,7 +304,6 @@ class Event:
payments = [x.fee.amount for x in runners_ic] payments = [x.fee.amount for x in runners_ic]
subtotal = sum(payments) subtotal = sum(payments)
# Dict of runners in each fee # Dict of runners in each fee
fee_dict = {} fee_dict = {}
for fee in self.fees: for fee in self.fees:
@ -333,7 +318,6 @@ class Event:
pdf.set_creator('oTime 0.0.1') pdf.set_creator('oTime 0.0.1')
pdf.set_creation_date() pdf.set_creation_date()
pdf.add_page() pdf.add_page()
pdf.add_font("LiberationSans", fname="data/fonts/LiberationSans-Regular.ttf") pdf.add_font("LiberationSans", fname="data/fonts/LiberationSans-Regular.ttf")
pdf.add_font("LiberationSans-Bold", fname="data/fonts/LiberationSans-Bold.ttf") pdf.add_font("LiberationSans-Bold", fname="data/fonts/LiberationSans-Bold.ttf")
@ -396,19 +380,19 @@ class Event:
pdf.set_font("LiberationSans", size=10) pdf.set_font("LiberationSans", size=10)
# Tabell # Tabell
line_height = pdf.font_size * 2 line_height = pdf.font_size * 2
col_width = pdf.epw / 9 # distribute content evenly col_width = pdf.epw / 8 # distribute content evenly
#Top row # Top row
pdf.set_fill_color(191, 191, 191) pdf.set_fill_color(191, 191, 191)
pdf.set_draw_color(191, 191, 191) pdf.set_draw_color(191, 191, 191)
pdf.set_font("LiberationSans-Bold", size=10) pdf.set_font("LiberationSans-Bold", size=10)
pdf.multi_cell(col_width, line_height, 'Startnr', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) pdf.multi_cell(col_width, line_height, 'Startnr', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width*2, line_height, 'Navn', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) pdf.multi_cell(col_width*2, line_height, 'Navn', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Klasse', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) pdf.multi_cell(col_width, line_height, 'Klasse', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Brikke', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) pdf.multi_cell(col_width, line_height, 'Brikke', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Starttid', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) # pdf.multi_cell(col_width, line_height, 'Starttid', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Resultat', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) pdf.multi_cell(col_width, line_height, 'Resultat', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Plass', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) pdf.multi_cell(col_width, line_height, 'Plass', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Kontigent', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) pdf.multi_cell(col_width, line_height, 'Kontigent', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.ln() pdf.ln()
pdf.set_draw_color(0, 0, 0) pdf.set_draw_color(0, 0, 0)
for runners in fee_dict.values(): for runners in fee_dict.values():
@ -418,15 +402,15 @@ class Event:
line_height = pdf.font_size * 1.6 line_height = pdf.font_size * 1.6
pdf.ln() pdf.ln()
for runner in runners: for runner in runners:
pdf.multi_cell(col_width, line_height, runner.id, ln=3,max_line_height=pdf.font_size, align='L') # Start Number pdf.multi_cell(col_width, line_height, runner.id, ln=3, max_line_height=pdf.font_size, align='L') # Start Number
pdf.multi_cell(col_width*2, line_height, f'{runner.last}, {runner.first}', ln=3, max_line_height=pdf.font_size, align='L') # Name pdf.multi_cell(col_width*2, line_height, f'{runner.last}, {runner.first}', ln=3, max_line_height=pdf.font_size, align='L') # Name
pdf.multi_cell(col_width, line_height, runner.o_class_str, ln=3, max_line_height=pdf.font_size, align='L') # Class pdf.multi_cell(col_width, line_height, runner.o_class_str, ln=3, max_line_height=pdf.font_size, align='L') # Class
pdf.multi_cell(col_width, line_height, str(runner.card), ln=3, max_line_height=pdf.font_size) # card pdf.multi_cell(col_width, line_height, str(runner.card), ln=3, max_line_height=pdf.font_size) # card
# Starttime: # Starttime:
if runner.start_time != None: #if runner.start_time != None:
pdf.multi_cell(col_width, line_height, str(runner.start_time), ln=3, max_line_height=pdf.font_size) # pdf.multi_cell(col_width, line_height, str(runner.start_time), ln=3, max_line_height=pdf.font_size)
else: #else:
pdf.multi_cell(col_width, line_height, 'Fristart', ln=3, max_line_height=pdf.font_size) # pdf.multi_cell(col_width, line_height, 'Fristart', ln=3, max_line_height=pdf.font_size)
# Time used: # Time used:
if runner.status() == 'OK': if runner.status() == 'OK':
pdf.multi_cell(col_width, line_height, str(datetime.timedelta(seconds=runner.totaltime())), ln=3, max_line_height=pdf.font_size) pdf.multi_cell(col_width, line_height, str(datetime.timedelta(seconds=runner.totaltime())), ln=3, max_line_height=pdf.font_size)
@ -450,7 +434,7 @@ class Event:
# sum # sum
pdf.set_font("LiberationSans-Bold", size=10) pdf.set_font("LiberationSans-Bold", size=10)
pdf.set_x(col_width*8) pdf.set_x(col_width*8)
pdf.multi_cell(0, line_height, 'Sum ' + str(subtotal), border='TB', ln=3, max_line_height=pdf.font_size, align='R') pdf.cell(0, line_height, 'Sum ' + str(subtotal), border='TB', align='R')
pdf.set_font("LiberationSans", size=10) pdf.set_font("LiberationSans", size=10)
line_height = pdf.font_size * 1.5 line_height = pdf.font_size * 1.5
@ -486,63 +470,22 @@ class PDF(FPDF):
# The runner object stores all the data specific to a runner. # The runner object stores all the data specific to a runner.
class Runner: class Runner:
def __init__(self, runner_id, first, last, **kwargs): def __init__(self, runner_id, first, last, club=None, club_id=None,
country=None, card=None, o_class_str=None, o_class=None,
fork=0, start_time=None, fee_id=None, fee=None):
self.id = runner_id self.id = runner_id
self.first = first self.first = first
self.last = last self.last = last
try: self.club = club
self.club = kwargs['club'] self.club_id = club_id
except KeyError: self.country = country
self.club = None self.card = card
self.o_class_str = o_class_str
try: self.o_class = o_class
self.club_id = kwargs['club_id'] self.fork = fork
except KeyError: self.start_time = start_time
self.club_id = None self.fee_id = fee_id
self.fee = fee
try:
self.country = kwargs['country']
except KeyError:
self.country = None
try:
self.card = kwargs['card']
except KeyError:
self.card = 0
try:
self.o_class_str = kwargs['o_class_str']
except KeyError:
self.o_class = None
try:
self.o_class = kwargs['o_class']
except KeyError:
self.o_class = None
try:
self.fork = kwargs['fork']
except KeyError:
self.fork = 0
try:
self.start_time = kwargs['start_time']
except KeyError:
self.start_time = None
try:
self.fee_id = kwargs['fee_id']
except KeyError:
self.fee_id = None
try:
self.fee = kwargs['fee']
self.fee_id = kwargs['fee'].id
except KeyError:
self.fee = None
#self.o_class = o_class
#self.start_time = start_time
def from_string(tt_line, o_classes): def from_string(tt_line, o_classes):
#https://web.archive.org/web/20191229124046/http://wiki.ttime.no/index.php/Developer #https://web.archive.org/web/20191229124046/http://wiki.ttime.no/index.php/Developer
@ -605,11 +548,11 @@ class Runner:
return 0 return 0
def status(self): def status(self):
if hasattr(self, 'card_r') == False or self.o_class == None: if hasattr(self, 'card_r') is False or self.o_class is None:
return 'Active' return 'Active'
elif self.check_codes(): elif self.check_codes():
return 'OK' return 'OK'
elif self.check_codes() == False: elif self.check_codes() is False:
return 'Disqualified' return 'Disqualified'
# TODO: må forbedres # TODO: må forbedres
@ -621,7 +564,7 @@ class Runner:
return None return None
def res_codes(self): def res_codes(self):
if self.o_class.course.forked == False: if self.o_class.course.forked is False:
return self.o_class.course.codes return self.o_class.course.codes
else: else:
return self.o_class.course.variations[self.fork] return self.o_class.course.variations[self.fork]
@ -672,6 +615,7 @@ class Runner:
'fee_id': self.fee_id 'fee_id': self.fee_id
} }
class CardDump: class CardDump:
def __init__(self, card, controls, splits, read_time, s_time, f_time): def __init__(self, card, controls, splits, read_time, s_time, f_time):
self.card = card self.card = card
@ -714,7 +658,7 @@ class CardDump:
read_time = datetime.datetime(year, month, day, hours, minutes, seconds, milliseconds) read_time = datetime.datetime(year, month, day, hours, minutes, seconds, milliseconds)
if len(controls) > 2: if len(controls) > 2:
s_time = read_time - datetime.timedelta(seconds = splits[-1]) s_time = read_time - datetime.timedelta(seconds=splits[-1])
f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2])) f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2]))
else: else:
s_time = read_time s_time = read_time
@ -760,8 +704,8 @@ class CardDump:
tl[1] = list(map(int, tl[1])) tl[1] = list(map(int, tl[1]))
read_time = datetime.datetime(tl[0][2], tl[0][1], tl[0][0], tl[1][0], tl[1][1], tl[1][2]) read_time = datetime.datetime(tl[0][2], tl[0][1], tl[0][0], tl[1][0], tl[1][1], tl[1][2])
if len(controls) > 2 and len(splits) > 2: if len(controls) > 2 and len(splits) > 2:
s_time = read_time - datetime.timedelta(seconds = splits[-1]) s_time = read_time - datetime.timedelta(seconds=splits[-1])
f_time = read_time - (datetime.timedelta(seconds = splits[-1]) + datetime.timedelta(seconds = splits[-2])) f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2]))
else: else:
s_time = read_time s_time = read_time
f_time = read_time f_time = read_time
@ -780,19 +724,11 @@ class CardDump:
# Stored in Event.courses # Stored in Event.courses
class Course: class Course:
def __init__(self, name, codes, **kwargs): def __init__(self, name, codes, forked=False, variations=None):
self.name = name self.name = name
self.codes = codes self.codes = codes
self.forked = forked
try: self.variations = variations
self.forked = kwargs['forked']
except KeyError:
self.forked = False
try:
self.variations = kwargs['variations']
except KeyError:
self.variations = None
def __repr__(self): def __repr__(self):
return f'name({self.name})' return f'name({self.name})'
@ -822,21 +758,14 @@ class OClass:
} }
class Fee: class Fee:
def __init__(self, fee_id, name, currency, amount, **kwargs): def __init__(self, fee_id, name, currency, amount, from_birth_date=None,
to_birth_date=None):
self.id = fee_id self.id = fee_id
self.name = name self.name = name
self.currency = currency self.currency = currency
self.amount = amount self.amount = amount
self.from_birth_date = from_birth_date
try: self.to_birth_date = to_birth_date
self.from_birth_date = kwargs['from_birth_date']
except KeyError:
self.from_birth_date = None
try:
self.to_birth_date = kwargs['to_birth_date']
except KeyError:
self.to_birth_date = None
def asdict(self): def asdict(self):
return { return {
@ -880,78 +809,83 @@ def classes_from_ttime_conf(ttime_file, courses):
def runners_from_xml_entries(xml_file): def runners_from_xml_entries(xml_file):
tree = ET.parse(xml_file) tree = ET.parse(xml_file)
root = tree.getroot() root = tree.getroot()
runners = []
person_entries = root.findall('./{http://www.orienteering.org/datastandard/3.0}PersonEntry') url = '{http://www.orienteering.org/datastandard/3.0}'
runners = []
person_entries = root.findall(f'./{url}PersonEntry')
for p_entry in person_entries: for p_entry in person_entries:
rid = p_entry[1][0].text rid = p_entry[1][0].text
person = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Person') person = p_entry.find(f'./{url}Person')
name = person.find('./{http://www.orienteering.org/datastandard/3.0}Name') name = person.find(f'./{url}Name')
first = name.find('./{http://www.orienteering.org/datastandard/3.0}Given').text first = name.find(f'./{url}Given').text
last = name.find('./{http://www.orienteering.org/datastandard/3.0}Family').text last = name.find(f'./{url}Family').text
organisation = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Organisation') organisation = p_entry.find(f'./{url}Organisation')
if organisation is not None: if organisation is not None:
club_id = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Id').text club_id = organisation.find(f'./{url}Id').text
club_name = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Name').text club_name = organisation.find(f'./{url}Name').text
club_name_short = organisation.find('./{http://www.orienteering.org/datastandard/3.0}ShortName').text club_name_short = organisation.find(f'./{url}ShortName').text
country = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Country').attrib['code'] country = organisation.find(f'./{url}Country').attrib['code']
else: else:
club_id = club_name = club_name_short = country = None club_id = club_name = club_name_short = country = None
class_el = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Class') class_el = p_entry.find(f'./{url}Class')
class_str = class_el.find('./{http://www.orienteering.org/datastandard/3.0}Name').text class_str = class_el.find(f'./{url}Name').text
fee_id = int(p_entry.find('./{http://www.orienteering.org/datastandard/3.0}AssignedFee/{http://www.orienteering.org/datastandard/3.0}Fee/{http://www.orienteering.org/datastandard/3.0}Id').text) fee_id = int(p_entry.find(f'./{url}AssignedFee/{url}Fee/{url}Id').text)
try: try:
card = int(p_entry.find('./{http://www.orienteering.org/datastandard/3.0}ControlCard').text) card = int(p_entry.find(f'./{url}ControlCard').text)
except AttributeError: except AttributeError:
card = None card = None
start_time = None start_time = None
runners.append(Runner(rid, first, last, club=club_name, club_id=club_id, runners.append(Runner(rid, first, last, club=club_name, club_id=club_id,
country=country,card=card, o_class_str=class_str, country=country,card=card, o_class_str=class_str,
start_time=start_time, fee_id=fee_id)) start_time=start_time, fee_id=fee_id))
return runners return runners
def fees_from_xml_entries(xml_file): def fees_from_xml_entries(xml_file):
tree = ET.parse(xml_file) tree = ET.parse(xml_file)
root = tree.getroot() root = tree.getroot()
allfees = root.findall('.//{http://www.orienteering.org/datastandard/3.0}Fee') url = '{http://www.orienteering.org/datastandard/3.0}'
allfees = root.findall(f'.//{url}Fee')
added_ids = [] added_ids = []
fee_objs = [] fee_objs = []
for fee in allfees: for fee in allfees:
f_id = int(fee.find('./{http://www.orienteering.org/datastandard/3.0}Id').text) f_id = int(fee.find(f'./{url}Id').text)
if f_id not in added_ids: if f_id not in added_ids:
added_ids.append(f_id) added_ids.append(f_id)
fee_id = f_id fee_id = f_id
name = fee.find('./{http://www.orienteering.org/datastandard/3.0}Name').text name = fee.find(f'./{url}Name').text
currency = fee.find('./{http://www.orienteering.org/datastandard/3.0}Amount').attrib['currency'] currency = fee.find(f'./{url}Amount').attrib['currency']
amount = int(fee.find('./{http://www.orienteering.org/datastandard/3.0}Amount').text) amount = int(fee.find(f'./{url}Amount').text)
try: try:
from_birth_date = fee.find('./{http://www.orienteering.org/datastandard/3.0}FromDateOfBirth').text from_birth_date = fee.find(f'./{url}FromDateOfBirth').text
except AttributeError: except AttributeError:
from_birth_date = None from_birth_date = None
try: try:
to_birth_date = fee.find('./{http://www.orienteering.org/datastandard/3.0}ToDateOfBirth').text to_birth_date = fee.find(f'./{url}ToDateOfBirth').text
except AttributeError: except AttributeError:
to_birth_date = None to_birth_date = None
fee_objs.append(Fee(fee_id, name, currency, amount, from_birth_date=from_birth_date, to_birth_date=to_birth_date)) fee_objs.append(Fee(fee_id, name, currency, amount,
from_birth_date=from_birth_date, to_birth_date=to_birth_date))
return fee_objs return fee_objs
# Checks if small list is in big list # Checks if small list is in big list
def contains(small, big): def contains(small, big):
valid = True valid = True
mark = 0 mark = 0
map_bl = [] map_bl = []
for i in small: for i in small:
for n,control in enumerate(big[mark:]): for n, control in enumerate(big[mark:]):
if i == control: if i == control:
mark += n mark += n
map_bl.append(mark) map_bl.append(mark)
@ -963,15 +897,16 @@ def contains(small, big):
else: else:
return False return False
def get_runners_in_class(runners, o_class): def get_runners_in_class(runners, o_class):
# Filters out runner objects that dont have the correct o_class # Filters out runner objects that dont have the correct o_class
list_filtrd = [] list_filtrd = []
for i in runners: for i in runners:
marker = 0
if i.o_class == o_class: if i.o_class == o_class:
list_filtrd.append(i) list_filtrd.append(i)
return list_filtrd return list_filtrd
def rank_runners(allrunners, o_class): def rank_runners(allrunners, o_class):
runners = get_runners_in_class(allrunners, o_class) runners = get_runners_in_class(allrunners, o_class)
runners_ranked = [] runners_ranked = []
@ -981,8 +916,8 @@ def rank_runners(allrunners, o_class):
runners_ranked.sort(key=lambda x: x.totaltime()) runners_ranked.sort(key=lambda x: x.totaltime())
return runners_ranked return runners_ranked
# Used to make creating xml files easier # Used to make creating xml files easier
def xml_child(parent, tag, content): def xml_child(parent, tag, content):
e = ET.SubElement(parent, tag) e = ET.SubElement(parent, tag)
e.text = str(content) e.text = str(content)