Ejemplo n.º 1
0
    def updateGrid(self):
        self.grid.ClearGrid()

        success, info = self.getRaceInfo()
        if not success:
            return
        race, category, results, laps = info

        if race.isTimeTrial:
            return

        Pulled = Model.Rider.Pulled
        pulled = []
        for rr in results:
            if race.riders[rr.num].status == Pulled:
                pulled.append(
                    getPulledCmpTuple(rr, race.riders[rr.num], laps, False))
        pulled.sort()
        bibLapsToGo = {p[-1].num: abs(p[0]) for p in pulled}
        pulled = [p[-1] for p in pulled]

        Utils.AdjustGridSize(self.grid, len(pulled) + 20)
        for row, rr in enumerate(pulled):
            self.setRow(rr.num, bibLapsToGo[rr.num], laps, row)

        # Remove repeated lapsToGo entries.
        col = self.iCol['lapsToGo']
        for row in range(self.grid.GetNumberRows() - 1, 0, -1):
            if self.grid.GetCellValue(row, col) == self.grid.GetCellValue(
                    row - 1, col):
                self.grid.SetCellValue(row, col, u'')

        self.grid.AutoSizeColumns(False)  # Resize to fit the column name.
        self.grid.AutoSizeRows(False)
Ejemplo n.º 2
0
	def updateGrid( self ):
		race = Model.race
		riderInfo = race.riderInfo if race else []
		
		Utils.AdjustGridSize( self.grid, len(riderInfo), len(self.headerNames) )
		
		# Set specialized editors for appropriate columns.
		for col, name in enumerate(self.headerNames):
			self.grid.SetColLabelValue( col, name )
			attr = gridlib.GridCellAttr()
			if col == 0:
				attr.SetRenderer( gridlib.GridCellNumberRenderer() )
			elif col == 1:
				attr.SetRenderer( gridlib.GridCellFloatRenderer(precision=1) )
			if name == 'Bib':
				attr.SetBackgroundColour( wx.Colour(178, 236, 255) )
			attr.SetFont( Utils.BigFont() )
			self.grid.SetColAttr( col, attr )
		
		missingBib = 5000
		for row, ri in enumerate(riderInfo):
			for col, field in enumerate(self.fieldNames):
				v = getattr(ri, field, None)
				if v is None:
					if field == 'bib':
						v = ri.bib = missingBib
						missingBib += 1
				self.grid.SetCellValue( row, col, u'{}'.format(v) )
		self.grid.AutoSize()
		self.Layout()
Ejemplo n.º 3
0
    def refresh(self):
        if not self.event:
            self.grid.ClearGrid()
            self.drawLotsDisplay.SetBitmap(self.emptyBitmap)
            return

        self.drawLotsDisplay.Show(not Model.model.competition.isMTB)

        DQs, DNSs, DNFs = Model.model.competition.getRiderStates()

        start = self.event.starts[-1]
        if self.startButton.IsEnabled():
            self.drawLotsDisplay.SetBitmap(
                self.drawLotsBitmap if start.canDrawLots else self.emptyBitmap)
        else:
            self.drawLotsDisplay.SetBitmap(self.drawLotsGreyBitmap if start.
                                           canDrawLots else self.emptyBitmap)

        startPositions = start.startPositions
        Utils.AdjustGridSize(self.grid, rowsRequired=len(startPositions))
        state = self.event.competition.state
        for row, p in enumerate(startPositions):
            rider = state.labels[p]
            for col, v in enumerate([
                    rider.bib, rider.full_name, rider.team, 'DNS' if
                (rider in DNSs or rider.bib in CacheDNSs) else ''
            ]):
                self.grid.SetCellValue(row, col, u' {}'.format(v))

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)
Ejemplo n.º 4
0
    def refresh(self):
        self.grid.ClearGrid()
        model = Model.model
        if not model:
            return

        self.events = [e for t, s, e in model.competition.getCanStart()]
        self.events.sort(
            key=lambda e: (0 if e == self.event else 1, e.tournament.i, e.
                           system.i, e.getHeat(), e.i))

        Utils.AdjustGridSize(self.grid, rowsRequired=len(self.events))
        for row, e in enumerate(self.events):
            for col, v in enumerate([
                    e.multi_line_name, e.multi_line_bibs,
                    e.multi_line_rider_names, e.multi_line_rider_teams,
                    e.multi_line_inlabels, e.multi_line_outlabels
            ]):
                self.grid.SetCellValue(row, col, u' {}'.format(v))
            if e.system != self.events[0].system:
                for col in six.moves.range(self.grid.GetNumberCols()):
                    self.grid.SetCellBackgroundColour(
                        row, col, InactiveBackgroundColour)
            else:
                for col in six.moves.range(self.grid.GetNumberCols()):
                    self.grid.SetCellBackgroundColour(row, col, wx.WHITE)

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)

        if self.events:
            self.grid.SelectRow(0)
Ejemplo n.º 5
0
    def updateGrid(self):
        race = Model.race
        if not race:
            self.grid.ClearGrid()
            return
        categories = race.getCategories(startWaveOnly=False, publishOnly=True)
        Utils.AdjustGridSize(self.grid, self.rowsMax, len(categories) * 2)
        col = 0
        for category in categories:
            fullname = category.fullname
            ib = fullname.rfind('(')
            catname, catgender = fullname[:ib].strip(), fullname[ib:]
            colName = '{}\n{}'.format(catname, catgender)
            self.grid.SetColLabelValue(col, colName)
            attr = wx.grid.GridCellAttr()
            attr.SetReadOnly(False)
            attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
            self.grid.SetColAttr(col, attr)

            self.grid.SetColLabelValue(col + 1, _('Recipient'))
            attr = wx.grid.GridCellAttr()
            attr.SetReadOnly(True)
            attr.SetAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
            attr.SetBackgroundColour(wx.Colour(152, 251, 152))
            self.grid.SetColAttr(col + 1, attr)

            for row in range(self.rowsMax):
                self.setCellPair(row, col, category)
            col += 2

        self.grid.AutoSizeColumns(False)  # Resize to fit the column name.
        self.grid.AutoSizeRows(False)
Ejemplo n.º 6
0
    def refresh(self):
        if not self.event:
            self.grid.ClearGrid()
            return

        # Propose finish order by qualifying time.
        state = self.event.competition.state
        finishPositions = sorted(self.event.starts[-1].startPositions,
                                 key=lambda r: state.labels[r].qualifyingTime)
        Utils.AdjustGridSize(self.grid, rowsRequired=len(finishPositions))

        state = self.event.competition.state
        row = 0
        # List DNS starters at the end.
        for b in [False, True]:
            for p in finishPositions:
                rider = state.labels[p]
                if (rider.bib in CacheDNSs) == b:
                    for col, v in enumerate([
                            rider.bib, rider.full_name, rider.team,
                            'DNS' if rider.bib in CacheDNSs else '', ''
                    ]):
                        self.grid.SetCellValue(row, col, u' {}'.format(v))
                    row += 1

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)
Ejemplo n.º 7
0
 def refresh(self):
     model = SeriesModel.model
     Utils.AdjustGridSize(self.grid, len(model.errors))
     for row, (r, e) in enumerate(model.errors):
         self.grid.SetCellValue(row, self.RaceCol, r.fileName)
         self.grid.SetCellValue(row, self.ErrorCol, '{}'.format(e))
     wx.CallAfter(self.gridAutoSize)
Ejemplo n.º 8
0
	def refresh( self ):
		model = SeriesModel.model
		
		Utils.AdjustGridSize( self.grid, rowsRequired=len(model.referenceTeams) )
		for row, (reference, aliases) in enumerate(model.referenceTeams):
			self.grid.SetCellValue( row, 0, reference )
			self.grid.SetCellValue( row, 1, u'; '.join(aliases) )
			
		self.grid.AutoSize()
		self.GetSizer().Layout()
Ejemplo n.º 9
0
	def refresh( self ):
		model = SeriesModel.model
		Utils.AdjustGridSize( self.grid, len(model.races) )
		for row, race in enumerate(model.races):
			self.grid.SetCellValue( row, self.RaceCol, race.getRaceName() )
			self.grid.SetCellValue( row, self.PointsCol, race.pointStructure.name )
			self.grid.SetCellValue( row, self.RaceFileCol, race.fileName )
		wx.CallAfter( self.gridAutoSize )
		
		self.seriesName.SetValue( SeriesModel.model.name )
		self.organizerName.SetValue( SeriesModel.model.organizer )
Ejemplo n.º 10
0
    def refresh(self, grid):
        font = GetFont()

        Utils.AdjustGridSize(self.grid,
                             rowsRequired=grid.GetNumberRows(),
                             colsRequired=grid.GetNumberCols() + 1)
        self.grid.SetColLabelValue(0, 'Pos')
        attr = gridlib.GridCellAttr()
        attr.SetFont(font)
        attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_TOP)
        attr.SetReadOnly(True)
        self.grid.SetColAttr(0, attr)

        iColStatus = None
        for col in six.moves.range(grid.GetNumberCols()):
            headerName = grid.GetColLabelValue(col)
            self.grid.SetColLabelValue(col + 1, headerName)
            attr = gridlib.GridCellAttr()
            attr.SetFont(font)
            if headerName == 'Bib':
                attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_TOP)
            elif headerName.startswith('Time'):
                attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            elif headerName.startswith('Status'):
                iColStatus = col
            elif headerName.startswith('Warn'):
                attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
                attr.SetRenderer(gridlib.GridCellBoolRenderer())
            elif headerName.startswith('Rel'):
                attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
                attr.SetRenderer(gridlib.GridCellBoolRenderer())
            attr.SetReadOnly(True)
            self.grid.SetColAttr(col + 1, attr)

        results = [[
            grid.GetCellValue(row, col)
            for col in six.moves.range(grid.GetNumberCols())
        ] for row in six.moves.range(grid.GetNumberRows())]
        results.sort(key=lambda x: x[iColStatus])

        for row in six.moves.range(grid.GetNumberRows()):
            self.grid.SetCellValue(row, 0, u'{}'.format(row + 1))
            for col in six.moves.range(grid.GetNumberCols()):
                v = results[row][col]
                self.grid.SetCellValue(row, col + 1, v if v != '0.000' else '')

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)

        self.GetSizer().Layout()
        self.GetSizer().Fit(self)

        self.CentreOnParent(wx.BOTH)
        self.SetFocus()
Ejemplo n.º 11
0
	def updateGrid( self ):
		race = Model.race
		if not race or not getattr(race, 'primes', None):
			self.grid.ClearGrid()
			return
		
		Utils.AdjustGridSize( self.grid, len(race.primes) )
		for row, prime in enumerate(race.primes):
			self.setRow( prime, row )
		
		self.grid.AutoSizeColumns( False )								# Resize to fit the column name.
		self.grid.AutoSizeRows( False )
Ejemplo n.º 12
0
    def refresh(self):
        model = SeriesModel.model
        model.extractAllRaceResults()  # Also harmonizes the categorySequence
        categoryList = model.getCategoriesSorted()

        Utils.AdjustGridSize(self.grid, len(categoryList))
        for row, c in enumerate(categoryList):
            self.grid.SetCellValue(row, self.CategoryCol, c.name)
            self.grid.SetCellValue(row, self.PublishCol, u'01'[int(c.publish)])
            self.grid.SetCellValue(row, self.TeamNCol, six.text_type(c.teamN))
            self.grid.SetCellValue(row, self.UseNthScoreCol,
                                   u'01'[int(c.useNthScore)])
            self.grid.SetCellValue(row, self.TeamPublishCol,
                                   u'01'[int(c.teamPublish)])
        wx.CallAfter(self.gridAutoSize)
Ejemplo n.º 13
0
    def setTestData(self):
        self.grid.ClearGrid()

        testData = TestData.getTestData()
        Utils.AdjustGridSize(self.grid, rowsRequired=len(testData))

        for row, data in enumerate(testData):
            bib = data[0]
            name = data[1] + ' ' + data[2]
            team = data[3]
            time = data[-1]
            for col, d in enumerate([bib, name, team, time]):
                self.grid.SetCellValue(row, col, u' {}'.format(d))

        # Fix up the column and row sizes.
        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)
Ejemplo n.º 14
0
    def refresh(self, event):
        self.event = event

        start = event.starts[-1]
        state = event.competition.state

        font = GetFont()

        startPositions = start.startPositions
        Utils.AdjustGridSize(self.grid, rowsRequired=len(startPositions))

        self.grid.SetLabelFont(font)
        for col in six.moves.range(self.grid.GetNumberCols()):
            self.grid.SetColLabelValue(col, self.headerNames[col])
            attr = gridlib.GridCellAttr()
            attr.SetFont(font)
            if self.headerNames[col] == 'Bib':
                attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_TOP)
                attr.SetReadOnly(True)
            elif col == 1 or col == 2:
                attr.SetReadOnly(True)
            elif self.headerNames[col].startswith('Status'):
                if len(start.getRemainingComposition()) > 2:
                    choices = ['DQ', 'DNF', '']
                    self.titleText.SetLabel(u'Restart Status Change')
                else:
                    choices = ['Inside', '']
                    self.titleText.SetLabel(u'Restart Position Change')
                attr.SetEditor(gridlib.GridCellChoiceEditor(choices=choices))
            self.grid.SetColAttr(col, attr)

        for row, p in enumerate(startPositions):
            rider = state.labels[p]
            for col, v in enumerate(
                [rider.bib, rider.full_name, rider.team, '']):
                self.grid.SetCellValue(row, col, u' {}'.format(v))

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)

        self.GetSizer().Layout()
        self.GetSizer().Fit(self)

        self.CentreOnParent(wx.BOTH)
        self.SetFocus()
Ejemplo n.º 15
0
    def refresh(self):
        race = Model.race
        events = race.events if race else []

        headers = [
            'Event',
            'Bibs',
        ]

        self.grid.BeginBatch()
        Utils.AdjustGridSize(self.grid, len(events), len(headers))

        for c, name in enumerate(headers):
            self.grid.SetColLabelValue(c, name)
            attr = gridlib.GridCellAttr()
            attr.SetReadOnly()
            attr.SetAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
            attr.SetFont(Utils.BigFont())
            self.grid.SetColAttr(c, attr)

        Sprint = Model.RaceEvent.Sprint
        Finish = Model.RaceEvent.Finish
        sprintCount = 0
        for row, e in enumerate(events):
            if e.eventType == Sprint:
                sprintCount += 1
                name = race.getSprintLabel(sprintCount)
            else:
                name = e.eventTypeName
                if e.eventType == Finish:
                    sprintCount += 1
                    name += u' ({})'.format(race.getSprintLabel(sprintCount))

            self.grid.SetCellValue(row, 0, name)
            self.grid.SetCellValue(row, 1,
                                   u','.join(u'{}'.format(b) for b in e.bibs))

        self.grid.AutoSize()
        self.grid.EndBatch()

        self.Layout()
Ejemplo n.º 16
0
    def refresh(self):
        model = Model.model
        riders = model.riders

        self.renumberButton.Show(model.competition.isMTB)

        Utils.AdjustGridSize(self.grid, rowsRequired=len(riders))
        for row, r in enumerate(riders):
            for col, value in enumerate([
                    u'{}'.format(r.bib), r.full_name, r.team,
                    r.qualifyingTimeText
            ]):
                self.grid.SetCellValue(row, col, value)

        # Fix up the column and row sizes.
        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)
        self.grid.SetColSize(self.grid.GetNumberCols() - 1, 96)

        self.Layout()
        self.Refresh()
Ejemplo n.º 17
0
    def refresh(self):
        riders = sorted(Model.model.riders, key=lambda r: r.qualifyingTime)
        starters = Model.model.competition.starters

        Utils.AdjustGridSize(self.grid, rowsRequired=len(riders))
        for row, r in enumerate(riders):
            if row < starters:
                pos = u'{}'.format(row + 1)
            else:
                pos = 'DNQ'
                for col in six.moves.range(self.grid.GetNumberCols()):
                    self.grid.SetCellBackgroundColour(row, col,
                                                      wx.Colour(200, 200, 200))
            for col, value in enumerate([
                    pos, u' {}'.format(r.bib), r.full_name, r.team,
                    '%.3f' % r.qualifyingTime
            ]):
                self.grid.SetCellValue(row, col, value)

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)
Ejemplo n.º 18
0
 def onCellChange(self, event):
     race = Model.race
     if not race:
         return
     row, col = event.GetRow(), event.GetCol()
     if col & 1:
         return
     categories = race.getCategories(startWaveOnly=False, publishOnly=True)
     if self.grid.GetNumberCols() != len(categories) * 2:
         Utils.AdjustGridSize(self.grid, self.rowsMax, len(categories) * 2)
     if row >= self.grid.GetNumberRows() or col >= self.grid.GetNumberCols(
     ):
         return
     self.copyToRace()
     try:
         category = categories[col // 2]
     except IndexError:
         return
     self.grid.SetCellValue(
         row, col + 1,
         self.getRecepient(self.grid.GetCellValue(row, col), row, category))
     wx.CallAfter(self.grid.AutoSizeColumns, False)
Ejemplo n.º 19
0
	def updateGrid( self ):
		race = Model.race
		if not race:
			self.grid.ClearGrid()
			return
		category = FixCategories( self.categoryChoice, getattr(race, 'resultsCategory', 0) )
		self.hbs.RecalcSizes()
		self.hbs.Layout()
		for si in self.hbs.GetChildren():
			if si.IsWindow():
				si.GetWindow().Refresh()
		self.category = category
		
		colnames = self.getColNames()
		
		results = GetTeamResults( self.category )
		Utils.AdjustGridSize( self.grid, len(results), len(colnames) )
		
		for col, colName in enumerate(colnames):
			self.grid.SetColLabelValue( col, colName )
			attr = wx.grid.GridCellAttr()
			attr.SetReadOnly( True )
			if col != 1:
				attr.SetAlignment( wx.ALIGN_RIGHT, wx.ALIGN_TOP )			
			self.grid.SetColAttr( col, attr )
		
		for row, r in enumerate(results):
			self.grid.SetCellValue( row, 0, u'{}'.format(row+1) )
			self.grid.SetCellValue( row, 1, r.team )
			self.grid.SetCellValue( row, 2, r.criteria )
			self.grid.SetCellValue( row, 3, r.gap )
			if race.showNumTeamParticipants:
				self.grid.SetCellValue( row, 4, u'{}'.format(r.numParticipants) )
		
		self.grid.AutoSizeColumns( False )
		self.grid.AutoSizeRows( False )
Ejemplo n.º 20
0
    def refresh(self):
        model = SeriesModel.model
        HeaderNames = getHeaderNames()
        scoreByPoints = model.scoreByPoints
        scoreByTime = model.scoreByTime

        self.postPublishCmd.SetValue(model.postPublishCmd)

        wait = wx.BusyCursor()
        self.raceResults = model.extractAllRaceResults(False)
        del wait

        self.fixCategories()

        categoryName = self.categoryChoice.GetStringSelection()
        if not categoryName or not (scoreByPoints or scoreByTime):
            Utils.AdjustGridSize(self.grid, 0, 0)
            return

        self.grid.ClearGrid()

        pointsForRank = {
            r.getFileName(): r.pointStructure
            for r in model.races
        }

        results, races = GetModelInfo.GetCategoryResultsTeam(
            categoryName,
            self.raceResults,
            pointsForRank,
            useMostEventsCompleted=model.useMostEventsCompleted,
            numPlacesTieBreaker=model.numPlacesTieBreaker,
        )
        results = [rr for rr in results if rr[1] > 0]

        headerNames = HeaderNames + [
            u'{}\n{}'.format(r[1], r[0].strftime('%Y-%m-%d') if r[0] else u'')
            for r in races
        ]

        Utils.AdjustGridSize(self.grid, len(results), len(headerNames))
        self.setColNames(headerNames)

        for row, (team, points, gap, rrs) in enumerate(results):
            self.grid.SetCellValue(row, 0, unicode(row + 1))
            self.grid.SetCellValue(row, 1, unicode(team))
            self.grid.SetCellValue(row, 2, unicode(points))
            self.grid.SetCellValue(row, 3, unicode(gap))
            for q, rt in enumerate(rrs):
                self.grid.SetCellValue(row, 4 + q,
                                       formatTeamResults(scoreByPoints, rt))

            for c in xrange(0, len(headerNames)):
                self.grid.SetCellBackgroundColour(row, c, wx.WHITE)
                self.grid.SetCellTextColour(row, c, wx.BLACK)

        if self.sortCol is not None:

            def getBracketedNumber(v):
                numberMax = 99999
                if not v:
                    return numberMax
                try:
                    return int(reNoDigits.sub('', v.split('(')[1]))
                except (IndexError, ValueError):
                    return numberMax

            data = []
            for r in xrange(0, self.grid.GetNumberRows()):
                rowOrig = [
                    self.grid.GetCellValue(r, c)
                    for c in xrange(0, self.grid.GetNumberCols())
                ]
                rowCmp = rowOrig[:]
                rowCmp[0] = int(rowCmp[0])
                rowCmp[4] = Utils.StrToSeconds(rowCmp[4])
                rowCmp[5:] = [getBracketedNumber(v) for v in rowCmp[5:]]
                rowCmp.extend(rowOrig)
                data.append(rowCmp)

            if self.sortCol > 0:
                fg = wx.WHITE
                bg = wx.Colour(0, 100, 0)
            else:
                fg = wx.BLACK
                bg = wx.Colour(255, 165, 0)

            iCol = abs(self.sortCol)
            data.sort(key=lambda x: x[iCol], reverse=(self.sortCol < 0))
            for r, row in enumerate(data):
                for c, v in enumerate(row[self.grid.GetNumberCols():]):
                    self.grid.SetCellValue(r, c, v)
                    if c == iCol:
                        self.grid.SetCellTextColour(r, c, fg)
                        self.grid.SetCellBackgroundColour(r, c, bg)
                        if c < 4:
                            halign = wx.ALIGN_LEFT
                        elif c == 4 or c == 5:
                            halign = wx.ALIGN_RIGHT
                        else:
                            halign = wx.ALIGN_CENTRE
                        self.grid.SetCellAlignment(r, c, halign, wx.ALIGN_TOP)

        self.statsLabel.SetLabel('{} / {}'.format(
            self.grid.GetNumberRows(),
            GetModelInfo.GetTotalUniqueTeams(self.raceResults)))

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)

        self.GetSizer().Layout()
Ejemplo n.º 21
0
    def refresh(self):
        model = Model.model
        competition = model.competition
        state = competition.state

        self.showNames.SetValue(getattr(model, 'chartShowNames', True))
        self.showTeams.SetValue(getattr(model, 'chartShowTeams', True))

        font = GetFont()

        self.headerNames = [
            '', 'System', 'Event', 'Heats', 'In', 'Bib', 'Name', 'Team', 'H1',
            'H2', 'H3', 'Out', 'Bib', 'Name', 'Team'
        ]
        hideCols = self.getHideCols(self.headerNames)
        self.headerNames = [
            h for c, h in enumerate(self.headerNames) if c not in hideCols
        ]
        Utils.AdjustGridSize(self.grid,
                             rowsRequired=sum(
                                 1 for t, s, e in competition.allEvents()),
                             colsRequired=len(self.headerNames))
        self.grid.ClearGrid()
        self.setColNames()

        for col in six.moves.range(self.grid.GetNumberCols()):
            attr = gridlib.GridCellAttr()
            attr.SetFont(font)
            attr.SetReadOnly(True)
            if col >= 4:
                attr.SetRenderer(GridCellMultiLineStringRenderer())
            if self.headerNames[col] in self.numericFields:
                attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_TOP)
            elif self.headerNames[col].startswith('H'):
                attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_TOP)
            self.grid.SetColAttr(col, attr)

        row = 0
        for tournament in competition.tournaments:
            self.grid.SetCellValue(row, 0, tournament.name)
            for system in tournament.systems:
                self.grid.SetCellValue(row, 1, system.name)
                for i, event in enumerate(system.events):
                    writeCell = WriteCell(self.grid, row, 2)

                    writeCell(u'{}'.format(i + 1))
                    writeCell(u' {}'.format(event.heatsMax))
                    writeCell(u'\n'.join(event.composition).replace(
                        u'\n', u' ({})\n'.format(len(event.composition)), 1))

                    riders = [
                        state.labels.get(c, None) for c in event.composition
                    ]
                    writeCell(u'\n'.join([
                        u'{}'.format(rider.bib if rider.bib else u'')
                        if rider else '' for rider in riders
                    ]))
                    if getattr(model, 'chartShowNames', True):
                        writeCell(u'\n'.join([
                            rider.full_name if rider else u''
                            for rider in riders
                        ]))
                    if getattr(model, 'chartShowTeams', True):
                        writeCell(u'\n'.join([
                            rider.team if rider else u'' for rider in riders
                        ]))

                    for heat in six.moves.range(3):
                        if event.heatsMax > 1:
                            writeCell(u'\n'.join(event.getHeatPlaces(heat +
                                                                     1)))
                        else:
                            writeCell(u'')

                    out = [event.winner] + event.others
                    writeCell(u'\n'.join(out).replace(
                        u'\n', u' ({})\n'.format(len(out)), 1))
                    riders = [state.labels.get(c, None) for c in out]
                    writeCell(u'\n'.join([
                        u'{}'.format(rider.bib if rider.bib else '')
                        if rider else '' for rider in riders
                    ]))
                    if getattr(model, 'chartShowNames', True):
                        writeCell('\n'.join([
                            rider.full_name if rider else ''
                            for rider in riders
                        ]))
                    if getattr(model, 'chartShowTeams', True):
                        writeCell('\n'.join(
                            [rider.team if rider else '' for rider in riders]))
                    row += 1

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)
Ejemplo n.º 22
0
	def refresh( self ):
		race = Model.race
		riders = race.getRiders() if race else []
		hasNumWins = race.rankBy == race.RankByLapsPointsNumWins
		pointsFmt = Utils.asInt if all(rr.pointsTotal == int(rr.pointsTotal) for rr in riders) else Utils.asFloat
		existingPointsFmt = Utils.asInt if all(rr.existingPoints == int(rr.existingPoints) for rr in riders) else Utils.asFloat
				
		riderInfo = {info.bib:info for info in race.riderInfo} if race else {}
		
		headers = ['Rank', 'Points', 'Bib',]
		iRiderInfoBegin = len(headers)
		headerNames = Model.RiderInfo.HeaderNames[2:]
		fieldNames = Model.RiderInfo.FieldNames[2:]
		headers.extend( headerNames )
		iRiderInfoEnd = len(headers)
		if hasNumWins:
			headers.append('Num Wins')
		headers.append( 'Finish' )
		
		self.grid.BeginBatch()
		Utils.AdjustGridSize( self.grid, len(riders), len(headers) )
		
		for c in range(self.grid.GetNumberCols()):
			self.grid.SetColLabelValue( c, headers[c] )
			attr = gridlib.GridCellAttr()
			attr.SetReadOnly()
			attr.SetAlignment(wx.ALIGN_LEFT if iRiderInfoBegin <= c < iRiderInfoEnd else wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
			attr.SetFont( Utils.BigFont() )
			if headers[c] == 'Bib':
				attr.SetBackgroundColour( wx.Colour(178, 236, 255) )
			self.grid.SetColAttr( c, attr )
		
		gr = Model.GetRank()
		for rank, rr in enumerate(riders, 1):
			row = rank-1
			col = 0
			
			# Rank
			self.grid.SetCellValue( row, col, gr(rank, rr) )
			col += 1
			
			# Points
			self.grid.SetCellValue( row, col, pointsFmt(rr.pointsTotal) )
			col += 1
			
			# Bib
			self.grid.SetCellValue( row, col, u'{}'.format(rr.num) )
			col += 1
	
			# Rider info.
			ri = riderInfo.get(rr.num, None)
			for f in fieldNames:
				self.grid.SetCellValue( row, col, u'{}'.format(getattr(ri,f,u'')) )
				col += 1
				
			# Wins
			if hasNumWins:
				self.grid.SetCellValue( row, col, u'{}'.format(rr.numWins) if rr.numWins else u'' )
				col += 1
				
			# Finish order
			self.grid.SetCellValue( row, col, u'{}'.format(rr.finishOrder) if rr.finishOrder not in (0,1000) else u'' )
			col += 1

		self.grid.EndBatch()
		self.grid.AutoSize()
		self.Layout()
Ejemplo n.º 23
0
    def refresh(self):
        race = Model.race

        riders = race.getRiders() if race else []

        hasExistingPoints = any(rr.existingPoints for rr in riders)
        hasNumWins = race.rankBy == race.RankByLapsPointsNumWins

        pointsFmt = Utils.asInt if all(rr.pointsTotal == int(rr.pointsTotal)
                                       for rr in riders) else Utils.asFloat
        existingPointsFmt = Utils.asInt if all(
            rr.existingPoints == int(rr.existingPoints)
            for rr in riders) else Utils.asFloat

        headers = [
            'Rank',
            'Bib',
            'Points',
        ] + [race.getSprintLabel(s)
             for s in range(1, race.sprintCount + 1)] + ['+/- Laps']
        if hasNumWins:
            headers.append('Num Wins')
        if hasExistingPoints:
            headers.append('Existing')
        headers.append('Finish')

        self.grid.BeginBatch()
        Utils.AdjustGridSize(self.grid, len(riders), len(headers))

        for c in range(self.grid.GetNumberCols()):
            self.grid.SetColLabelValue(c, headers[c])
            attr = gridlib.GridCellAttr()
            attr.SetReadOnly()
            attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            attr.SetFont(Utils.BigFont())
            if headers[c] == 'Bib':
                attr.SetBackgroundColour(wx.Colour(178, 236, 255))
            self.grid.SetColAttr(c, attr)

        gr = Model.GetRank()
        for rank, rr in enumerate(riders, 1):
            row = rank - 1
            col = 0

            # Rank
            self.grid.SetCellValue(row, col, gr(rank, rr))
            col += 1

            # Bib
            self.grid.SetCellValue(row, col, u'{}'.format(rr.num))
            col += 1

            # Points
            self.grid.SetCellValue(row, col, pointsFmt(rr.pointsTotal))
            col += 1

            # Sprints
            for s in range(1, race.sprintCount + 1):
                place, points = rr.sprintPlacePoints.get(s, (-1, -1))
                self.grid.SetCellValue(
                    row, col, u'{}'.format(points) if points > 0 else u'')
                col += 1

            # +/- Laps
            self.grid.SetCellValue(
                row, col, u'{}'.format(rr.lapsTotal) if rr.lapsTotal else u'')
            col += 1

            # Wins
            if hasNumWins:
                self.grid.SetCellValue(
                    row, col, u'{}'.format(rr.numWins) if rr.numWins else u'')
                col += 1

            # Existing Points
            if hasExistingPoints:
                self.grid.SetCellValue(
                    row, col,
                    existingPointsFmt(rr.existingPoints)
                    if rr.existingPoints else u'')
                col += 1

            # Finish order
            self.grid.SetCellValue(
                row, col, u'{}'.format(rr.finishOrder)
                if rr.finishOrder not in (0, 1000) else u'')
            col += 1

        self.grid.EndBatch()
        self.grid.AutoSize()
        self.Layout()
def CallupResultsToGrid( grid, registration_headers, callup_headers, callup_results, is_callup=True, top_riders=999999, exclude_unranked=False ):
	callup_results = callup_results[:top_riders]
	if exclude_unranked:
		callup_results = [r for r in callup_results if any(r[k] for k in range(len(registration_headers), len(callup_headers)))]
	
	if not is_callup:
		callup_results = list(reversed(callup_results))
	
	last_name_col = None
	uci_id_col = None
	ignore_headers = set(['age'])
	for col, v in enumerate(callup_headers):
		if v == 'last_name':
			last_name_col = col
		elif v == 'uci_id':
			uci_id_col = col
	
	header_col = {}
	col_cur = 0
	for v in callup_headers:
		if v in ignore_headers:
			continue
		header_col[v] = col_cur
		col_cur += 1
	
	grid.DeleteCols( numCols = grid.GetNumberCols() )
	Utils.AdjustGridSize( grid, rowsRequired=len(callup_results), colsRequired=sum(1 for h in callup_headers if h not in ignore_headers) + 1 )
	
	for ih, v in enumerate(callup_headers):
		if v in ignore_headers:
			continue
		col = header_col[v]
		
		attr = gridlib.GridCellAttr()
		attr.SetReadOnly()
		if v in Model.Result.NumericFields or ih >= len(registration_headers):
			attr.SetAlignment( wx.ALIGN_RIGHT, wx.ALIGN_CENTRE )
		grid.SetColAttr( col, attr )
		
		grid.SetColLabelValue( col, make_title(v) )
		
	# Set an empty column so we can track the row if the user switches things around manually.
	attr = gridlib.GridCellAttr()
	attr.SetReadOnly()
	attr.SetTextColour( wx.WHITE )
	grid.SetColAttr( grid.GetNumberCols()-1, attr )
	grid.SetColLabelValue( grid.GetNumberCols()-1, u'' )
	
	successSoundalikeColour = wx.Colour(255, 255, 0)
	multiMatchColour = wx.Colour(255,140,0)
	
	characterMatchFail = wx.Colour(255, 255, 0)
	soundalikeMatchFail = wx.Colour(255,140,0)
	
	len_callup_results = len(callup_results)
	for row, result in enumerate(callup_results):
		for c, v in enumerate(result):
			if callup_headers[c] in ignore_headers:
				continue
			
			col = header_col[callup_headers[c]]
			
			colour = wx.WHITE
			try:
				s = v.get_status()
				if s == v.SuccessSoundalike:
					colour = successSoundalikeColour
				elif s == v.MultiMatch:
					colour = multiMatchColour
				if s == v.Success:
					s = v.get_name_status()
					if s == 1:
						colour = characterMatchFail
					elif s == 2:
						colour = soundalikeMatchFail
			except AttributeError as e:
				pass
			grid.SetCellBackgroundColour( row, col, colour )
			
			try:
				v = v.get_value()
			except AttributeError:
				pass
			
			if v is None:
				grid.SetCellValue( row, col, u'' )
				continue
				
			try:
				grid.SetCellValue( row, col, u'{:g}'.format(v) )
			except ValueError:
				if c == last_name_col:
					v = u'{}'.format(v).upper()
				elif c == uci_id_col:
					v = Model.format_uci_id( u'{}'.format(v) )
				else:
					v = u'{}'.format( v )
				grid.SetCellValue( row, col, v )
		
		# Record the row index in a hidden column so we can recover the original results.
		grid.SetCellValue( row, grid.GetNumberCols()-1, u'{}'.format(row if is_callup else len_callup_results - row - 1) )
	
	if not is_callup:
		for row in range(grid.GetNumberRows()):
			grid.SetRowLabelValue( row, u'{}'.format(grid.GetNumberRows() - row) )
	
	grid.AutoSize()
	grid.SetColSize( grid.GetNumberCols()-1, 0 )
Ejemplo n.º 25
0
	def onAddRows( self, event ):
		growSize = 10
		Utils.AdjustGridSize( self.grid, rowsRequired = self.grid.GetNumberRows()+growSize )
		self.Layout()
		self.grid.MakeCellVisible( self.grid.GetNumberRows()-growSize, 0 )
Ejemplo n.º 26
0
    def commit(self):
        self.grid.SaveEditControlValue(
        )  # Make sure the current edit is committed.
        self.grid.DisableCellEditControl()

        race = Model.race
        if not race:
            return
        race.useTableToPullRiders = self.useTableToPullRidersCkBox.GetValue()
        if not race.useTableToPullRiders:
            self.grid.ClearGrid()
            Utils.AdjustGridSize(self.grid, 20)
            return

        rows = [self.getRow(r) for r in range(self.grid.GetNumberRows())]
        rows = [rv for rv in rows if rv['pulledBib']]

        # Fix any missing data lapsToGo in the table.
        lapsToGoLast = 1
        for rv in rows:
            if not rv['lapsToGo']:
                rv['lapsToGo'] = lapsToGoLast
            lapsToGoLast = rv['lapsToGo']

        success, info = self.getRaceInfo()
        if not success:
            return False
        race, category, results, laps = info
        rule80LapTime = race.getRule80LapTime(category)

        changed = False
        Finisher, Pulled = Model.Rider.Finisher, Model.Rider.Pulled
        for rr in results:
            rider = race.riders.get(rr.num, None)
            if not rider or race.getCategory(rr.num) != category:
                continue
            if rider.status == Pulled:
                rider.status = Finisher
                changed = True

        lapsToGoPulled = defaultdict(list)
        for rv in rows:
            lapsToGoPulled[rv['lapsToGo']].append(rv['pulledBib'])

        for lapsToGo, bibs in lapsToGoPulled.items():
            if lapsToGo <= 0:
                continue
            for seq, bib in enumerate(bibs):
                try:
                    rider = race.riders[bib]
                except KeyError:
                    continue

                rider.status = Pulled
                rider.pulledLapsToGo = lapsToGo
                rider.pulledSequence = seq
                changed = True

        if changed:
            race.setChanged()
        self.updateGrid()
Ejemplo n.º 27
0
	def refresh( self ):
		model = SeriesModel.model
		scoreByTime = model.scoreByTime
		scoreByPercent = model.scoreByPercent
		scoreByTrueSkill = model.scoreByTrueSkill
		HeaderNames = getHeaderNames()
		
		model = SeriesModel.model
		self.postPublishCmd.SetValue( model.postPublishCmd )
		
		with wx.BusyCursor() as wait:
			self.raceResults = model.extractAllRaceResults()
		
		self.fixCategories()
		self.grid.ClearGrid()
		
		categoryName = self.categoryChoice.GetStringSelection()
		if not categoryName:
			return
			
		pointsForRank = { r.getFileName(): r.pointStructure for r in model.races }

		results, races, potentialDuplicates = GetModelInfo.GetCategoryResults(
			categoryName,
			self.raceResults,
			pointsForRank,
			useMostEventsCompleted=model.useMostEventsCompleted,
			numPlacesTieBreaker=model.numPlacesTieBreaker,
		)
		
		results = [rr for rr in results if toFloat(rr[3]) > 0]
		
		headerNames = HeaderNames + [u'{}\n{}'.format(r[1],r[0].strftime('%Y-%m-%d') if r[0] else u'') for r in races]
		
		Utils.AdjustGridSize( self.grid, len(results), len(headerNames) )
		self.setColNames( headerNames )
		
		for row, (name, license, team, points, gap, racePoints) in enumerate(results):
			self.grid.SetCellValue( row, 0, six.text_type(row+1) )
			self.grid.SetCellValue( row, 1, six.text_type(name or u'') )
			self.grid.SetCellBackgroundColour( row, 1, wx.Colour(255,255,0) if name in potentialDuplicates else wx.Colour(255,255,255) )
			self.grid.SetCellValue( row, 2, six.text_type(license or u'') )
			self.grid.SetCellValue( row, 3, six.text_type(team or u'') )
			self.grid.SetCellValue( row, 4, six.text_type(points) )
			self.grid.SetCellValue( row, 5, six.text_type(gap) )
			for q, (rPoints, rRank, rPrimePoints, rTimeBonus) in enumerate(racePoints):
				self.grid.SetCellValue( row, 6 + q,
					u'{} ({}) +{}'.format(rPoints, Utils.ordinal(rRank), rPrimePoints) if rPoints and rPrimePoints
					else u'{} ({}) -{}'.format(rPoints, Utils.ordinal(rRank), Utils.formatTime(rTimeBonus, twoDigitMinutes=False)) if rPoints and rRank and rTimeBonus
					else u'{} ({})'.format(rPoints, Utils.ordinal(rRank)) if rPoints
					else u'({})'.format(Utils.ordinal(rRank)) if rRank
					else u''
				)
				
			for c in range( len(headerNames) ):
				self.grid.SetCellBackgroundColour( row, c, wx.WHITE )
				self.grid.SetCellTextColour( row, c, wx.BLACK )
		
		if self.sortCol is not None:
			def getBracketedNumber( v ):
				numberMax = 99999
				if not v:
					return numberMax
				try:
					return int(reNoDigits.sub('', v.split('(')[1]))
				except (IndexError, ValueError):
					return numberMax
				
			data = []
			for r in range(self.grid.GetNumberRows()):
				rowOrig = [self.grid.GetCellValue(r, c) for c in six.moves.range(0, self.grid.GetNumberCols())]
				rowCmp = rowOrig[:]
				rowCmp[0] = int(rowCmp[0])
				rowCmp[4] = Utils.StrToSeconds(rowCmp[4])
				rowCmp[5:] = [getBracketedNumber(v) for v in rowCmp[5:]]
				rowCmp.extend( rowOrig )
				data.append( rowCmp )
			
			if self.sortCol > 0:
				fg = wx.WHITE
				bg = wx.Colour(0,100,0)
			else:
				fg = wx.BLACK
				bg = wx.Colour(255,165,0)
				
			iCol = abs(self.sortCol)
			data.sort( key = lambda x: x[iCol], reverse = (self.sortCol < 0) )
			for r, row in enumerate(data):
				for c, v in enumerate(row[self.grid.GetNumberCols():]):
					self.grid.SetCellValue( r, c, v )
					if c == iCol:
						self.grid.SetCellTextColour( r, c, fg )
						self.grid.SetCellBackgroundColour( r, c, bg )
						if c < 4:
							halign = wx.ALIGN_LEFT
						elif c == 4 or c == 5:
							halign = wx.ALIGN_RIGHT
						else:
							halign = wx.ALIGN_CENTRE
						self.grid.SetCellAlignment( r, c, halign, wx.ALIGN_TOP )
		
		self.statsLabel.SetLabel( '{} / {}'.format(self.grid.GetNumberRows(), GetModelInfo.GetTotalUniqueParticipants(self.raceResults)) )
		
		self.grid.AutoSizeColumns( False )
		self.grid.AutoSizeRows( False )
		
		self.GetSizer().Layout()
Ejemplo n.º 28
0
    def refresh(self):
        self.fixShowResults()
        self.grid.ClearGrid()

        model = Model.model
        competition = model.competition

        self.showNames.SetValue(getattr(model, 'resultsShowNames', True))
        self.showTeams.SetValue(getattr(model, 'resultsShowTeams', True))

        self.communiqueNumber.SetValue(
            model.communique_number.get(self.getPhase(), ''))

        resultName = self.showResults.GetStringSelection()

        if 'Qualifiers' in resultName:
            starters = competition.starters

            self.headerNames = [u'Pos', u'Bib', u'Name', u'Team', u'Time']
            hideCols = self.getHideCols(self.headerNames)
            self.headerNames = [
                h for c, h in enumerate(self.headerNames) if c not in hideCols
            ]

            riders = sorted(model.riders, key=lambda r: r.keyQualifying())
            for row, r in enumerate(riders):
                if row >= starters or r.status == 'DNQ':
                    riders[row:] = sorted(riders[row:],
                                          key=lambda r: r.keyQualifying()[1:])
                    break
            Utils.AdjustGridSize(self.grid,
                                 rowsRequired=len(riders),
                                 colsRequired=len(self.headerNames))
            Utils.SetGridCellBackgroundColour(self.grid, wx.WHITE)
            self.setColNames()
            for row, r in enumerate(riders):
                if row < starters and r.status != 'DNQ':
                    pos = u'{}'.format(row + 1)
                    for col in six.moves.range(self.grid.GetNumberCols()):
                        self.grid.SetCellBackgroundColour(row, col, wx.WHITE)
                else:
                    pos = 'DNQ'
                    for col in six.moves.range(self.grid.GetNumberCols()):
                        self.grid.SetCellBackgroundColour(
                            row, col, wx.Colour(200, 200, 200))

                writeCell = WriteCell(self.grid, row)
                for col, value in enumerate([
                        pos, u' {}'.format(r.bib), r.full_name, r.team,
                        r.qualifyingTimeText
                ]):
                    if col not in hideCols:
                        writeCell(value)

            competitionTime = model.qualifyingCompetitionTime
            self.competitionTime.SetLabel(u'{}: {}'.format(
                _('Est. Competition Time'), Utils.formatTime(competitionTime)
            ) if competitionTime else u'')

        elif 'Final Classification' in resultName:
            self.headerNames = [u'Pos', u'Bib', u'Name', u'Team', u'License']
            hideCols = self.getHideCols(self.headerNames)
            self.headerNames = [
                h for c, h in enumerate(self.headerNames) if c not in hideCols
            ]

            results, dnfs, dqs = competition.getResults()
            Utils.AdjustGridSize(self.grid,
                                 rowsRequired=len(model.riders),
                                 colsRequired=len(self.headerNames))
            Utils.SetGridCellBackgroundColour(self.grid, wx.WHITE)

            self.setColNames()
            for row, (classification, r) in enumerate(results):
                writeCell = WriteCell(self.grid, row)
                if not r:
                    for col in six.moves.range(self.grid.GetNumberCols()):
                        writeCell('')
                else:
                    for col, value in enumerate([
                            classification, r.bib if r.bib else '',
                            r.full_name, r.team, r.license
                    ]):
                        if col not in hideCols:
                            writeCell(u' {}'.format(value))
            self.competitionTime.SetLabel(u'')
        else:
            # Find the Tournament and System selected.
            keepGoing = True
            for tournament in competition.tournaments:
                for system in tournament.systems:
                    name = (u'%s: ' % tournament.name
                            if tournament.name else '') + system.name
                    if name == resultName:
                        keepGoing = False
                        break
                if not keepGoing:
                    break

            heatsMax = max(event.heatsMax for event in system.events)
            if heatsMax == 1:
                self.headerNames = [
                    u'Event', u'Bib', u'Name', u'Note', u'Team', u'    ',
                    u'Pos', u'Bib', u'Name', u'Note', u'Team', u'Time'
                ]
            else:
                self.headerNames = [
                    u'Event', u'Bib', u'Name', u'Note', u'Team', u'H1', u'H2',
                    u'H3', u'    ', u'Pos', u'Bib', u'Name', u'Note', u'Team',
                    u'Time'
                ]
            hideCols = self.getHideCols(self.headerNames)
            self.headerNames = [
                h for c, h in enumerate(self.headerNames) if c not in hideCols
            ]

            Utils.AdjustGridSize(self.grid,
                                 rowsRequired=len(system.events),
                                 colsRequired=len(self.headerNames))
            Utils.SetGridCellBackgroundColour(self.grid, wx.WHITE)

            self.setColNames()
            state = competition.state

            for row, event in enumerate(system.events):
                writeCell = WriteCell(self.grid, row)

                writeCell(u'{}'.format(row + 1))

                riders = [state.labels.get(c, None) for c in event.composition]
                writeCell(u'\n'.join([
                    u'{}'.format(rider.bib) if rider and rider.bib else ''
                    for rider in riders
                ]))
                if getattr(model, 'resultsShowNames', True):
                    writeCell(u'\n'.join([
                        rider.full_name if rider else u'' for rider in riders
                    ]))
                writeCell(u'\n'.join([
                    competition.getRelegationsWarningsStr(
                        rider.bib, event, True) if rider else u''
                    for rider in riders
                ]))
                if getattr(model, 'resultsShowTeams', True):
                    writeCell(u'\n'.join(
                        [rider.team if rider else '' for rider in riders]))

                if heatsMax != 1:
                    for heat in six.moves.range(heatsMax):
                        if event.heatsMax != 1:
                            writeCell(u'\n'.join(event.getHeatPlaces(heat +
                                                                     1)))
                        else:
                            writeCell(u'')

                #writeCell( u' ===> ', vert=wx.ALIGN_CENTRE )
                writeCell(' '.join(['', Arrow, '']), vert=wx.ALIGN_CENTRE)

                out = [event.winner] + event.others
                riders = [state.labels.get(c, None) for c in out]
                writeCell(u'\n'.join(u'{}'.format(i + 1)
                                     for i in six.moves.range(len(riders))))
                writeCell(u'\n'.join([
                    u'{}'.format(rider.bib if rider.bib else '')
                    if rider else '' for rider in riders
                ]))
                if getattr(model, 'resultsShowNames', True):
                    writeCell(u'\n'.join([
                        rider.full_name if rider else '' for rider in riders
                    ]))
                writeCell(u'\n'.join([
                    competition.getRelegationsWarningsStr(
                        rider.bib, event, False) if rider else u''
                    for rider in riders
                ]))
                if getattr(model, 'resultsShowTeams', True):
                    writeCell(u'\n'.join(
                        [rider.team if rider else '' for rider in riders]))
                if event.winner in state.labels:
                    try:
                        value = u'%.3f' % event.starts[-1].times[1]
                    except (KeyError, IndexError, ValueError):
                        value = ''
                    writeCell(value)

            competitionTime = system.competitionTime
            self.competitionTime.SetLabel(u'{}: {}'.format(
                _('Est. Competition Time'), Utils.formatTime(competitionTime)
            ) if competitionTime else u'')

        self.grid.AutoSizeColumns(False)
        self.grid.AutoSizeRows(False)
Ejemplo n.º 29
0
    def refresh(self):
        race = Model.race
        if race and race.isRunning():
            tRace = race.curRaceTime()
            self.expected, self.recorded = getExpectedRecorded()
        else:
            self.expected = self.recorded = []
        self.resetTimer()

        tRace = race.lastRaceTime()
        isRunning = race.isRunning()

        categories = self.refreshCategories(race)

        gridLastX, gridLastY = self.grid.GetViewStart()

        if not categories:
            self.grid.ClearGrid()
            return

        self.iCategory = min(self.iCategory, len(categories) - 1)
        category = categories[self.iCategory]
        results = GetResults(category)

        Finisher = Model.Rider.Finisher
        try:
            leader = results[0]
            leaderLap = find_le(leader.raceTimes, tRace)
            if leader.interp[leaderLap]:
                leaderLap -= 1
            tLeader = leader.raceTimes[leaderLap]
        except:
            leader = leaderLap = tLeader = None

        v = category.fullname
        try:
            lapsToGo = len(leader.raceTimes) - 1 - (leaderLap or 0)
        except Exception as e:
            lapsToGo = None
        if lapsToGo is not None:
            if lapsToGo == 0:
                v += u': {}'.format(_('Finish'))
            else:
                v += u': {} {}'.format(lapsToGo, _('laps to go'))
        if leader and hasattr(leader, 'speed'):
            v += u' {}'.format(leader.speed)

        self.title.SetLabel(v)

        if not results:
            Utils.AdjustGridSize(self.grid, 0, None)
            self.grid.ClearGrid()
            return

        self.bibExpected = {e.num: e for e in self.expected}
        bibRecorded = {e.num: e for e in self.recorded}
        bibETA = {}

        Utils.AdjustGridSize(self.grid, len(results), None)
        self.isRecorded = []

        self.tExpected = []
        iGroup = -1
        groupCount = defaultdict(int)
        group = []
        for row, rr in enumerate(results):
            self.grid.SetCellValue(row, self.iCol[u'Pos'],
                                   u'{}'.format(rr.pos))
            self.grid.SetCellValue(row, self.iCol[u'Bib'],
                                   u'{}'.format(rr.num))
            self.grid.SetCellValue(
                row, self.iCol[u'Name'],
                u'{} {}'.format(getattr(rr, 'FirstName', u''),
                                getattr(rr, 'LastName', u'')).strip())
            self.grid.SetCellValue(row, self.iCol[u'Team'],
                                   getattr(rr, 'Team', u''))
            self.grid.SetCellValue(row, self.iCol[u'Gap'], rr.gap)
            e = self.bibExpected.get(rr.num,
                                     None) if rr.status == Finisher else None
            iGroup += 1
            if e:
                eta = e.t - tRace
                bibETA[rr.num] = eta
                if row > 0:
                    try:
                        numPrev = results[row - 1].num
                        if abs(abs(eta - bibETA[results[row - 1].num]) < 1.0):
                            iGroup -= 1
                    except:
                        pass

            self.tExpected.append(e.t if e else None)
            group.append(iGroup + 1)
            groupCount[iGroup + 1] += 1
            self.grid.SetCellValue(row, self.iCol[u'ETA'],
                                   Utils.formatTime(eta) if e else u'')

            e = bibRecorded.get(rr.num, None)
            if not isRunning or (leaderLap == 1 or (e and tLeader is not None
                                                    and e.t >= tLeader)):
                self.isRecorded.append(True)
            else:
                self.grid.SetCellValue(
                    row, self.iCol[u'Pos'], u'{}{}'.format(
                        self.grid.GetCellValue(row, self.iCol[u'Pos']),
                        recordedChar))
                self.isRecorded.append(False)

            rowColour = recordedColour if self.isRecorded[
                -1] else unrecordedColour
            for c in range(len(self.cols)):
                self.grid.SetCellBackgroundColour(row, c, rowColour)

        gCur = 0
        gLast = None
        gColIndex = 0
        groupColour = None
        iCol = self.iCol[u'Group']
        for row, g in enumerate(group):
            self.grid.SetCellValue(row, iCol, u'')
            if groupCount[g] == 1:
                continue
            if g == gLast:
                self.grid.SetCellBackgroundColour(row, iCol, groupColour)
                continue

            gLast = g
            groupColour = self.groupColours[gColIndex % len(self.groupColours)]
            groupTextColour = self.groupTextColours[gColIndex %
                                                    len(self.groupTextColours)]
            gColIndex += 1
            gCur += 1
            self.grid.SetCellValue(row, iCol, u'{} [{}]'.format(
                gCur,
                groupCount[g],
            ))
            self.grid.SetCellBackgroundColour(row, iCol, groupColour)
            self.grid.SetCellTextColour(row, iCol, groupTextColour)

        self.refreshETA()
        self.grid.AutoSize()
        self.grid.Scroll(gridLastX, gridLastY)
        self.GetSizer().Layout()