Example #1
0
 def __init__(self, categories=None):
     wx.Printout.__init__(self)
     if not categories:
         with UnstartedRaceWrapper():
             self.categories = Model.race.getCategories(startWaveOnly=False,
                                                        publishOnly=True)
     else:
         self.categories = categories
     self.pageInfo = {}
Example #2
0
def getRaceCategories():
    # Get all the categories available to print.
    with UnstartedRaceWrapper():
        with Model.LockRace() as race:
            if race is None:
                return []
            categories = [(c.fullname, c)
                          for c in race.getCategories(startWaveOnly=False,
                                                      publishOnly=True)
                          if race.hasCategory(c)]
        categories.append(('All', None))
    return categories
Example #3
0
 def prepareGrid(self, page):
     exportGrid = ExportGrid()
     try:
         with UnstartedRaceWrapper():
             if self.pageInfo[page][0] == 'Primes':
                 exportGrid = ExportGrid(**Primes.GetGrid())
             else:
                 exportGrid.setResultsOneList(self.pageInfo[page][0],
                                              True,
                                              showLapTimes=False)
     except KeyError:
         return ExportGrid()
     exportGrid.title = u'\n'.join(
         [_('Podium Results'), u'', exportGrid.title])
     return exportGrid
Example #4
0
 def prepareGrid(self, page):
     showLapTimes = (not Model.race) or getattr(
         Model.race, 'includeLapTimesInPrintout', True)
     try:
         with UnstartedRaceWrapper():
             if self.pageInfo[page][0] == 'Primes':
                 exportGrid = ExportGrid(**Primes.GetGrid())
             else:
                 exportGrid = ExportGrid()
                 exportGrid.setResultsOneList(self.pageInfo[page][0],
                                              True,
                                              showLapTimes=showLapTimes)
     except KeyError:
         return ExportGrid()
     return exportGrid
Example #5
0
def getCatCountImagesCategoryList(parent):
    il = wx.ImageList(16, 16)
    sm_rt = il.Add(
        wx.Bitmap(os.path.join(Utils.getImageFolder(), 'SmallRightArrow.png'),
                  wx.BITMAP_TYPE_PNG))
    sm_up = il.Add(
        wx.Bitmap(os.path.join(Utils.getImageFolder(), 'SmallUpArrow.png'),
                  wx.BITMAP_TYPE_PNG))
    sm_dn = il.Add(
        wx.Bitmap(os.path.join(Utils.getImageFolder(), 'SmallDownArrow.png'),
                  wx.BITMAP_TYPE_PNG))

    list = AutoWidthListCtrl(parent,
                             style=wx.LC_REPORT
                             | wx.BORDER_SUNKEN
                             | wx.LC_HRULES)
    list.SetImageList(il, wx.IMAGE_LIST_SMALL)

    list.InsertColumn(0, _("Name"))
    list.InsertColumn(1, _("Gender"))
    list.InsertColumn(2, _("Type"))
    list.InsertColumn(3, _("Count"), wx.LIST_FORMAT_RIGHT)
    list.InsertColumn(4, '')

    catCount = {}
    race = Model.race
    if race:
        with UnstartedRaceWrapper():
            SyncExcelLink(race)
            for c in race.getCategories(startWaveOnly=False, publishOnly=True):
                catCount[c] = race.catCount(c)
                if catCount[c] == 0:
                    continue
                index = list.InsertStringItem(sys.maxint, c.name, sm_rt)
                list.SetStringItem(index, 1, getattr(c, 'gender', 'Open'))
                list.SetStringItem(
                    index, 2, [_('Start Wave'),
                               _('Component'),
                               _('Custom')][c.catType])
                list.SetStringItem(index, 3, u'{}'.format(catCount[c]))

    for col in xrange(4 + 1):
        list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
    list.SetColumnWidth(1, 64)
    list.SetColumnWidth(3, 52)

    return catCount, il, list
Example #6
0
    def GetPageInfo(self):
        self.pageInfo = {}
        try:
            numCategories = len(self.categories)
        except:
            numCategories = 0
        if numCategories == 0:
            return (1, 1, 1, 1)

        iPrintFormat = getattr(Model.race, 'printFormat',
                               0) if Model.race else 0
        if iPrintFormat == 0:  # Fit Entire Category to One Page
            rowDrawCount = 1000000
        elif iPrintFormat == 1:  # Small Text (max 60 riders per page)
            rowDrawCount = 60
        else:  # Big Text (max 30 riders per page)
            rowDrawCount = 30

        # Compute a map by category and range for each page.
        page = 0
        with UnstartedRaceWrapper():
            for c in self.categories:
                categoryLength = len(GetResults(c))
                pageNumberTotal = int(
                    math.ceil(float(categoryLength) / float(rowDrawCount)) +
                    0.1)
                pageNumber = 0
                for i in range(0, categoryLength, rowDrawCount):
                    page += 1
                    pageNumber += 1
                    self.pageInfo[page] = [
                        c, i,
                        min(categoryLength, rowDrawCount), pageNumber,
                        pageNumberTotal, categoryLength
                    ]
        race = Model.race
        if race and getattr(race, 'primes', None) and getattr(
                race, 'includePrimesInPrintout', True):
            page += 1
            pageNumber += 1
            self.pageInfo[page] = [
                'Primes', 0,
                len(race.primes), 1, 1,
                len(race.primes)
            ]
        return (1, page, 1, page)
Example #7
0
    def onOK(self, event):
        self.categories = []
        race = Model.race
        row = 0
        with UnstartedRaceWrapper():
            for c in race.getCategories(startWaveOnly=False,
                                        publishOnly=False):
                if self.catCount[c] == 0:
                    continue
                if self.list.GetItemState(
                        row, wx.LIST_STATE_SELECTED) == wx.LIST_STATE_SELECTED:
                    self.categories.append(c)
                row += 1

        self.positions = self.podiumPositions.GetSelection() + 1
        race.includePrimesInPrintout = self.includePrimesInPrintoutCheckBox.GetValue(
        )
        self.EndModal(wx.ID_OK)
Example #8
0
    def GetPageInfo(self):
        self.pageInfo = {}
        numCategories = len(self.categories)
        if numCategories == 0:
            return (1, 1, 1, 1)

        rowDrawCount = self.positions

        # Compute a map by category and range for each page.
        Finisher = Model.Rider.Finisher
        page = 0
        with UnstartedRaceWrapper():
            for c in self.categories:
                categoryLength = min(
                    sum(1 for r in GetResults(c) if r.status == Finisher),
                    rowDrawCount)
                pageNumberTotal = 1
                pageNumber = 0
                for i in xrange(0, categoryLength, rowDrawCount):
                    page += 1
                    pageNumber += 1
                    self.pageInfo[page] = [
                        c, i,
                        min(categoryLength, rowDrawCount), pageNumber,
                        pageNumberTotal, categoryLength
                    ]

        race = Model.race
        if race and getattr(race, 'primes', None) and getattr(
                race, 'includePrimesInPrintout', True):
            page += 1
            pageNumber += 1
            self.pageInfo[page] = [
                'Primes', 0,
                len(race.primes), 1, 1,
                len(race.primes)
            ]

        return (1, page, 1, page)
Example #9
0
def GetAnimationData(category=None, getExternalData=False):
    animationData = {}
    ignoreFields = {
        'pos', 'num', 'gap', 'gapValue', 'laps', 'lapTimes', 'full_name',
        'short_name'
    }

    with UnstartedRaceWrapper(getExternalData):
        with Model.LockRace() as race:
            for cat in ([category] if category else race.getCategories()):
                results = GetResults(cat)

                for rr in results:
                    info = {'flr': race.getCategory(rr.num).firstLapRatio}
                    bestLaps = race.getNumBestLaps(rr.num)
                    for a in dir(rr):
                        if a.startswith('_') or a in ignoreFields:
                            continue
                        if a == 'raceTimes':
                            info['raceTimes'] = getattr(rr, a)
                            if bestLaps is not None and len(
                                    info['raceTimes']) > bestLaps:
                                info['raceTimes'] = info[
                                    'raceTimes'][:bestLaps + 1]
                        elif a == 'status':
                            info['status'] = statusNames[getattr(rr, a)]
                        elif a == 'lastTime':
                            try:
                                info[a] = rr.raceTimes[-1]
                            except IndexError:
                                info[a] = rr.lastTime
                        else:
                            info[a] = getattr(rr, a)

                    animationData[rr.num] = info

    return animationData
Example #10
0
def getExportGrid():
    race = Model.race
    try:
        externalInfo = race.excelLink.read()
    except:
        externalInfo = {}

    GetTranslation = _
    allZeroStarters = True
    with UnstartedRaceWrapper():
        catMap = dict(
            (c.fullname, c) for c in race.getCategories(startWaveOnly=False))
        catDetails = GetCategoryDetails(False, True)
        catDetailsMap = dict((cd['name'], cd) for cd in catDetails)

        title = u'\n'.join([
            _('Categories'), race.title, race.scheduledStart + u' ' +
            _('Start on') + u' ' + Utils.formatDate(race.date)
        ])
        colnames = [
            _('Start Time'),
            _('Category'),
            _('Gender'),
            _('Numbers'),
            _('Laps'),
            _('Distance'),
            _('Starters')
        ]

        raceStart = Utils.StrToSeconds(race.scheduledStart + ':00')
        catData = []
        for catInfo in catDetails:
            c = catMap.get(catInfo['name'], None)
            if not c:
                continue

            starters = race.catCount(c)
            if starters:
                allZeroStarters = False
            else:
                starters = ''

            laps = catInfo.get('laps', '') or ''
            raceDistance = catInfo.get('raceDistance', '')
            raceDistanceUnit = catInfo.get('distanceUnit', '')

            if raceDistance:
                raceDistance = '%.2f' % raceDistance

            if c.catType == c.CatWave:
                catStart = Utils.SecondsToStr(raceStart +
                                              c.getStartOffsetSecs())
            elif c.catType == c.CatCustom:
                catStart = Utils.SecondsToStr(raceStart)
            else:
                catStart = ''

            catData.append([
                catStart,
                u' - ' + c.name if c.catType == c.CatComponent else c.name,
                GetTranslation(catInfo.get('gender', 'Open')), c.catStr,
                u'{}'.format(laps), u' '.join([raceDistance, raceDistanceUnit])
                if raceDistance else '', u'{}'.format(starters)
            ])

    if allZeroStarters:
        colnames.remove(_('Starters'))
    data = [[None] * len(catData) for i in xrange(len(colnames))]
    for row in xrange(len(catData)):
        for col in xrange(len(colnames)):
            data[col][row] = catData[row][col]

    exportGrid = ExportGrid(title=title, colnames=colnames, data=data)
    exportGrid.leftJustifyCols = {1, 2, 3}
    return exportGrid
Example #11
0
def UCIExcel(category, fname, startList=False):
    race = Model.race
    if not startList and race.isUnstarted():
        return

    Finisher = Model.Rider.Finisher
    statusNames = Model.Rider.statusNames

    rrWinner = None
    if race.isUnstarted():
        with UnstartedRaceWrapper():
            results = GetResults(category)
    else:
        results = GetResults(category)
        try:
            rrWinner = results[0]
        except:
            pass

    if startList:
        results = sorted(copy.deepcopy(results),
                         key=operator.attrgetter('num'))
        for pos, rr in enumerate(results, 1):
            rr.pos = u'{}'.format(pos)
            rr.status = Finisher

    wb = xlsxwriter.Workbook(fname)

    title_format = wb.add_format(dict(font_size=24, valign='vcenter'))

    general_header_format = wb.add_format(
        dict(font_color='white', bg_color='black', bottom=1, right=1))
    general_format = wb.add_format(dict(bottom=1, right=1))

    #-------------------------------------------------------------------------------------------------------
    ws = wb.add_worksheet('General')
    if startList:
        ws.write(0, 0, u"UCI Event's Start List File", title_format)
    else:
        ws.write(0, 0, u"UCI Event's Results File", title_format)
    ws.set_row(0, 26)

    general = [
        (u'Field', u'Value', u'Description', u'Comment'),
        (u'Competition Code', u'', u'UCI unique competition code',
         u'Filled by the system'),
        (u'Event Code', u'', u'UCI unique event code',
         u'Filled by the system'),
        (u'Race Type', u'IRR', u'Race type of the Event (IRR, XCO, OM)',
         u'Optional'),
        (u'Competitor Type', u'A', u'A or T (Athlete or Team)', u'Mandatory'),
        (u'Result type', u'Time', u'Points or Time', u'Mandatory'),
        (u'Document version', 1.0, u'Version number of the file',
         u'Mandatory'),
    ]

    colWidths = {}

    def ww(row, col, v, fmt=None):
        if fmt:
            ws.write(row, col, v, fmt)
        else:
            ws.write(row, col, v)
        colWidths[col] = max(colWidths.get(col, 0), len(six.text_type(v)))

    fmt = general_header_format
    for row, r in enumerate(general, 3):
        for col, v in enumerate(r):
            ww(row, col, v, fmt)
        fmt = general_format

    for col, width in colWidths.items():
        ws.set_column(col, col, width + 2)

    #-------------------------------------------------------------------------------------------------------
    header_format = wb.add_format(
        dict(font_color='white', bg_color='black', bottom=1))

    gray = 'D8D8D8'

    odd_format = wb.add_format(dict(bottom=1))
    even_format = wb.add_format(dict(bg_color=gray, bottom=1))

    odd_format_last = wb.add_format(dict(bottom=1, right=1))
    even_format_last = wb.add_format(dict(bg_color=gray, bottom=1, right=1))

    odd_format_center = wb.add_format(dict(align='center', bottom=1))
    even_format_center = wb.add_format(
        dict(align='center', bg_color=gray, bottom=1))

    odd_format_right = wb.add_format(dict(align='right', bottom=1))
    even_format_right = wb.add_format(
        dict(align='right', bg_color=gray, bottom=1))

    if startList:
        ws = wb.add_worksheet('StartList')
    else:
        ws = wb.add_worksheet('Results')

    if startList:
        colNames = [
            'Start Order', 'BIB', 'UCI ID', 'Last Name', 'First Name',
            'Country', 'Team', 'Gender'
        ]
    else:
        colNames = [
            'Rank', 'BIB', 'UCI ID', 'Last Name', 'First Name', 'Country',
            'Team', 'Gender', 'Phase', 'Heat', 'Result', 'IRM', 'Sort Order'
        ]

    def getFmt(name, row):
        if name == 'Sort Order':
            return odd_format_last if row & 1 else even_format_last
        if name in ('Start Order', 'Rank', 'BIB'):
            return odd_format_center if row & 1 else even_format_center
        if name == 'Result':
            return odd_format_right if row & 1 else even_format_right
        return odd_format if row & 1 else even_format

    def toInt(n):
        try:
            return int(n.split()[0])
        except:
            return n

    def getFinishTime(rr):
        if rr.status != Finisher:
            return u''
        if rrWinner and rrWinner.laps != rr.laps:
            return rr.laps - rrWinner.laps
        try:
            finishTime = rr.lastTime - rr.raceTimes[0]
            return Utils.formatTime(finishTime,
                                    forceHours=True,
                                    twoDigitHours=True)
        except:
            return u''

    def getIRM(rr):
        if 'REL' in six.text_type(rr.pos):
            return 'REL'
        if rrWinner and rr.laps != rrWinner.laps:
            return 'LAP'
        return u'' if rr.status == Finisher else statusNames[
            rr.status].replace('DQ', 'DSQ')

    getValue = {
        'Start Order': lambda rr: toInt(rr.pos),
        'Rank': lambda rr: toInt(rr.pos) if rr.status == Finisher else '',
        'BIB': operator.attrgetter('num'),
        'UCI ID': lambda rr: formatUciId(getattr(rr, 'UCIID', u'')),
        'Last Name': lambda rr: getattr(rr, 'LastName', u''),
        'First Name': lambda rr: getattr(rr, 'FirstName', u''),
        'Country': lambda rr: getattr(rr, 'NatCode', u''),
        'Team': lambda rr: getattr(rr, 'TeamCode', u''),
        'Gender': lambda rr: getattr(rr, 'Gender', u'')[:1],
        'Result': getFinishTime,
        'IRM': getIRM,
        'Phase': lambda rr: u'Final',
    }

    colWidths = {}
    for c, name in enumerate(colNames):
        ww(0, c, name, header_format)

    for row, rr in enumerate(results, 1):
        for col, name in enumerate(colNames):
            ww(row, col,
               getValue.get(name, lambda rr: u'')(rr), getFmt(name, row))

    for col, width in colWidths.items():
        ws.set_column(col, col, width + 2)

    ws.autofilter(0, 0, len(results) + 1, len(colNames))

    wb.close()