def house_big_board(page): """ House big board """ from models import Race all_races = Race.select().where(Race.office_name == 'U.S. House') all_featured_races = Race.select().where((Race.office_name == 'U.S. House') & (Race.featured_race == True)).order_by(Race.poll_closing_time, Race.state_postal, Race.seat_number) timestamp = get_last_updated(all_races) context = make_context(timestamp=timestamp) context['page_title'] = 'House' context['current_page'] = page context['page_class'] = 'house' if page == 2: featured_races = all_featured_races[HOUSE_PAGE_LIMIT:] else: featured_races = all_featured_races[:HOUSE_PAGE_LIMIT] context['poll_groups'] = columnize_races(featured_races) context['bop'] = calculate_bop(all_races, HOUSE_INITIAL_BOP) context['not_called'] = calculate_seats_left(all_races) context['seat_number'] = ".seat_number" return render_template('slides/race_results.html', **context)
def balance_of_power(): """ Serve up the balance of power graph """ from models import Race house_races = Race.select().where(Race.office_name == 'U.S. House').order_by(Race.state_postal) senate_races = Race.select().where(Race.office_name == 'U.S. Senate').order_by(Race.state_postal) senate_updated = get_last_updated(senate_races) house_updated = get_last_updated(house_races) if senate_updated > house_updated: last_updated = senate_updated else: last_updated = house_updated context = make_context(timestamp=last_updated) context['page_title'] = 'Balance of Power' context['page_class'] = 'balance-of-power' context['house_bop'] = calculate_bop(house_races, HOUSE_INITIAL_BOP) context['senate_bop'] = calculate_bop(senate_races, SENATE_INITIAL_BOP) context['house_not_called'] = calculate_seats_left(house_races) context['senate_not_called'] = calculate_seats_left(senate_races) return render_template('slides/balance-of-power.html', **context)
def index(): """ Example view demonstrating rendering a simple HTML page. """ from models import Race context = make_context() with open('data/featured.json') as f: context['featured'] = json.load(f) context['races'] = Race.select() """ Balance of Power data """ races = Race.select().where(Race.office_name == 'U.S. Senate').order_by(Race.state_postal) context['not_called'] = app_utils.calculate_seats_left(races) if app_config.DEPLOY_PROMO: template_file = 'promo.html' else: template_file = 'index.html' return render_template(template_file, **context), 200,
def index(): """ Example view demonstrating rendering a simple HTML page. """ from models import Race context = make_context() with open('data/featured.json') as f: context['featured'] = json.load(f) context['races'] = Race.select() """ Balance of Power data """ races = Race.select().where(Race.office_name == 'U.S. Senate').order_by( Race.state_postal) context['not_called'] = app_utils.calculate_seats_left(races) if app_config.DEPLOY_PROMO: template_file = 'promo.html' else: template_file = 'index.html' return render_template(template_file, **context), 200,
def _check_race(self): race = self.store.find(Race).one() if race: return race race = Race() race.name = u'First race ever' self.store.add(race) self.store.commit() return race
def test_closing_times(self): with test_database(test_db, [Race,]): data.load_races('data/tests/init_races.json') data.load_closing_times('data/closing-times.csv') house_race = Race.get(Race.race_id == '38529-OR') self.assertEqual(house_race.poll_closing_time, datetime(2014, 11, 4, 23, 0, 0)) senate_race = Race.get(Race.race_id == '38145-OK') self.assertEqual(senate_race.poll_closing_time, datetime(2014, 11, 4, 20, 0, 0))
def produce_bop_json(): """ Loops through houses/parties to count seats and calculate deltas. """ # Party mapping. parties = [('republicans', 'r'), ('democrats', 'd'), ('other', 'o')] # House/seats/delta mapping. houses = [('house', 'H'), ('senate', 'S')] # Blank dataset. data = bootstrap_bop_data() # President. for state in State.select().where(State.called == True): for party, abbr in parties: if state.winner == abbr: data['president'][party] = calculate_president_bop( data['president'][party], state.electoral_votes) # House/senate. for office, short in houses: for race in Race.select().where( (Race.ap_called == True) | (Race.npr_called == True), Race.office_code == short): for party, abbr in parties: if race.winner == abbr: if short == 'H': data[office][party] = calculate_house_bop( data[office][party]) if short == 'S': data[office][party] = calculate_senate_bop( race, data[office][party]) if short == 'S': data[office] = calculate_net_pickups(race, data[office]) # Write the number of uncalled races. # First, the races where we accept AP calls but no calls have come in. data[office]['not_called'] += Race.select()\ .where( Race.accept_ap_call == True, Race.ap_called == False, Race.office_code == short)\ .count() # Second, the races where we don't accept AP calls and no NPR calls are in. data[office]['not_called'] += Race.select()\ .where( Race.accept_ap_call == False, Race.npr_called == False, Race.office_code == short)\ .count() return data
def produce_bop_json(): """ Loops through houses/parties to count seats and calculate deltas. """ # Party mapping. parties = [('republicans', 'r'), ('democrats', 'd'), ('other', 'o')] # House/seats/delta mapping. houses = [('house', 'H'), ('senate', 'S')] # Blank dataset. data = bootstrap_bop_data() # President. for state in State.select().where(State.called == True): for party, abbr in parties: if state.winner == abbr: data['president'][party] = calculate_president_bop(data['president'][party], state.electoral_votes) # House/senate. for office, short in houses: for race in Race.select().where( (Race.ap_called == True) | (Race.npr_called == True), Race.office_code == short): for party, abbr in parties: if race.winner == abbr: if short == 'H': data[office][party] = calculate_house_bop(data[office][party]) if short == 'S': data[office][party] = calculate_senate_bop(race, data[office][party]) if short == 'S': data[office] = calculate_net_pickups(race, data[office]) # Write the number of uncalled races. # First, the races where we accept AP calls but no calls have come in. data[office]['not_called'] += Race.select()\ .where( Race.accept_ap_call == True, Race.ap_called == False, Race.office_code == short)\ .count() # Second, the races where we don't accept AP calls and no NPR calls are in. data[office]['not_called'] += Race.select()\ .where( Race.accept_ap_call == False, Race.npr_called == False, Race.office_code == short)\ .count() return data
def test_closing_times(self): with test_database(test_db, [ Race, ]): data.load_races('data/tests/init_races.json') data.load_closing_times('data/closing-times.csv') house_race = Race.get(Race.race_id == '38529-OR') self.assertEqual(house_race.poll_closing_time, datetime(2014, 11, 4, 23, 0, 0)) senate_race = Race.get(Race.race_id == '38145-OK') self.assertEqual(senate_race.poll_closing_time, datetime(2014, 11, 4, 20, 0, 0))
def incumbents_lost(): """ Ongoing list of which incumbents lost their elections """ from models import Race called_senate_races = Race.select().where( (Race.office_name == 'U.S. Senate') & (((Race.ap_called == True) & (Race.accept_ap_call == True)) | (Race.npr_called == True)) ).order_by(Race.state_postal, Race.seat_number) called_house_races = Race.select().where( (Race.office_name == 'U.S. House') & (((Race.ap_called == True) & (Race.accept_ap_call == True)) | (Race.npr_called == True)) ).order_by(Race.state_postal, Race.seat_number) senate_incumbents_lost = [] house_incumbents_lost = [] senate_updated = get_last_updated(called_senate_races) house_updated = get_last_updated(called_house_races) if senate_updated > house_updated: last_updated = senate_updated else: last_updated = house_updated context = make_context(timestamp=last_updated) for race in called_senate_races: if not race.is_runoff(): for candidate in race.candidates: if candidate.incumbent and not candidate.is_winner(): senate_incumbents_lost.append(race) for race in called_house_races: if not race.is_runoff(): for candidate in race.candidates: if candidate.incumbent and not candidate.is_winner(): house_incumbents_lost.append(race) context['senate_incumbents_lost_count'] = len(senate_incumbents_lost) context['house_incumbents_lost_count'] = len(house_incumbents_lost) context['senate_incumbents_lost'] = columnize_card(senate_incumbents_lost, 6) context['house_incumbents_lost'] = columnize_card(house_incumbents_lost, 6) return render_template('slides/incumbents-lost.html', **context)
def obama_reps(): """ Ongoing list of Incumbent Republicans In Districts Barack Obama Won In 2012 """ from models import Race races = Race.select().where(Race.obama_gop == True).order_by(Race.state_postal, Race.seat_number) timestamp = get_last_updated(races) context = make_context(timestamp=timestamp) won = [race for race in races if race.is_called() and not race.is_runoff() and not race.party_changed()] lost = [race for race in races if race.is_called() and not race.is_runoff() and race.party_changed()] not_called = [race for race in races if not race.is_called() or race.is_runoff()] context['races_won'] = columnize_card(won) context['races_lost'] = columnize_card(lost) context['races_not_called'] = columnize_card(not_called) context['races_won_count'] = len(won) context['races_lost_count'] = len(lost) context['races_not_called_count'] = len(not_called) context['races_count'] = races.count() return render_template('slides/obama-reps.html', **context)
def romney_senate_dems(): """ Ongoing list of Democratically-held seats in states Mitt Romney Won In 2012 """ from models import Race races = Race.select().where( (Race.romney_dem == True) & (Race.office_name == 'U.S. Senate') ).order_by(Race.state_postal, Race.seat_number) timestamp = get_last_updated(races) context = make_context(timestamp=timestamp) won = [race for race in races if race.is_called() and not race.is_runoff() and not race.party_changed()] lost = [race for race in races if race.is_called() and not race.is_runoff() and race.party_changed()] not_called = [race for race in races if not race.is_called() or race.is_runoff()] context['races_won'] = columnize_card(won) context['races_lost'] = columnize_card(lost) context['races_not_called'] = columnize_card(not_called) context['races_won_count'] = len(won) context['races_lost_count'] = len(lost) context['races_not_called_count'] = len(not_called) context['races_count'] = races.count() return render_template('slides/romney-senate-dems.html', **context)
def wipe_status(): """ Blanks the status fields for congress and presidential races. """ rq = Race.update( precincts_reporting=0, ap_called=False, ap_called_time=None, npr_called=False, npr_called_time=None ) rq.execute() cq = Candidate.update( vote_count=0, ap_winner=False, npr_winner=False ) cq.execute() sq = State.update( ap_call='u', ap_called_at=None, npr_call='u', npr_called_at=None, precincts_reporting=0, rep_vote_count=0, dem_vote_count=0 ) sq.execute() write_www_files()
def test_update_results(self): with test_database(test_db, [Race, Candidate]): data.load_races('data/tests/init_races.json') data.load_candidates('data/tests/init_candidates.json') data.load_updates('data/tests/update.json') race = Race.get(Race.race_id == '38529-OR') candidate_4848 = Candidate.get(Candidate.candidate_id == '4848-OR') candidate_4642 = Candidate.get(Candidate.candidate_id == '4642-OR') candidate_4979 = Candidate.get(Candidate.candidate_id == '4979-OR') self.assertEqual(race.precincts_reporting, 1970) self.assertEqual(race.precincts_total, 2288) self.assertTrue(race.is_reporting()) self.assertEqual(candidate_4848.vote_count, 150000) self.assertEqual(candidate_4642.vote_count, 200000) self.assertEqual(candidate_4979.vote_count, 250000) self.assertEqual(race.count_votes(), 600000) self.assertEqual(candidate_4848.vote_percent(), Decimal('25.0')) self.assertAlmostEqual(candidate_4642.vote_percent(), Decimal('33.333'), 3) self.assertAlmostEqual(candidate_4979.vote_percent(), Decimal('41.667'), 3) # Results does not call races self.assertFalse(candidate_4848.ap_winner) self.assertFalse(candidate_4642.ap_winner) self.assertFalse(candidate_4979.ap_winner)
def house_freshmen(): """ Ongoing list of how representatives elected in 2012 are faring """ from models import Race races = Race.select().where(Race.freshmen == True)\ .order_by(Race.state_postal, Race.seat_number) timestamp = get_last_updated(races) context = make_context() won = [race for race in races if race.is_called() and not race.is_runoff() and not race.party_changed()] lost = [race for race in races if race.is_called() and not race.is_runoff() and race.party_changed()] not_called = [race for race in races if not race.is_called() or race.is_runoff()] context['races_won'] = columnize_card(won, 6) context['races_lost'] = columnize_card(lost, 6) context['races_not_called'] = columnize_card(not_called, 6) context['races_won_count'] = len(won) context['races_lost_count'] = len(lost) context['races_not_called_count'] = len(not_called) context['races_count'] = races.count() return render_template('slides/house-freshmen.html', **context)
def get_results(self): #r = requests.get(self.href) #data = r.text #reader = csv.DictReader(data.splitlines(), delimiter='\t') data = open('local_elections/WA/test_data/MediaResults.txt', 'r') reader = csv.DictReader(data, delimiter='\t') reader.next() # Skip header now for row in reader: raw_candidate_name = row['BallotName'] candidate_name_split = raw_candidate_name.split() candidate_first_name = candidate_name_split[0] candidate_last_name = ' '.join(candidate_name_split[1:]) raw_candidate_party = row['PartyName'] party_regex = re.compile("Prefers (\w+) Party") party_result = party_regex.findall(raw_candidate_party) party_name = '' party_abbreviation = '' if party_result: party_name = party_result[0] party_abbreviation = party_name[0].upper() p = Party(party_name, party_abbreviation) c = Candidate(candidate_first_name, candidate_last_name, row['Votes']) r = Race(row['RaceName'], row['RaceJurisdictionTypeName'], row['TotalBallotsCastByRace']) race, created = self.get_or_create_race(r) race.add_candidate(c)
def test_ballot_measures_extra(self): with test_database(test_db, [Race,]): data.load_races('data/tests/init_races.json') data.load_ballot_measures_extra('data/ballot-measures-extra.csv', quiet=True) race = Race.get(Race.race_id == '27456-MO') self.assertEqual(race.ballot_measure_description, 'Teacher performance evaluation (Amendment 3)')
def test_senate_extra(self): with test_database(test_db, [Race,]): data.load_races('data/tests/init_races.json') data.load_senate_extra('data/senate-extra.csv', quiet=True) race = Race.get(Race.race_id == '38145-OK') self.assertEqual(race.previous_party, 'gop')
def test_house_extra(self): with test_database(test_db, [Race,]): data.load_races('data/tests/init_races.json') data.load_house_extra('data/house-extra.csv', quiet=True) race = Race.get(Race.race_id == '38529-OR') self.assertEqual(race.previous_party, 'gop') self.assertFalse(race.featured_race)
def test_count_votes(self): with test_database(test_db, [Race, Candidate], create_tables=True): data.load_races('data/tests/init_races.json') data.load_candidates('data/tests/init_candidates.json') data.load_updates('data/tests/update.json') race = Race.get(Race.race_id == '38529-OR') self.assertTrue(race.is_reporting()) self.assertEqual(race.count_votes(), 600000)
def test_senate_extra(self): with test_database(test_db, [ Race, ]): data.load_races('data/tests/init_races.json') data.load_senate_extra('data/senate-extra.csv', quiet=True) race = Race.get(Race.race_id == '38145-OK') self.assertEqual(race.previous_party, 'gop')
def parse_house(row): race_data = dict(zip(RACE_FIELDS, row[:len(RACE_FIELDS)])) race_data['slug'] = u'%s%s' % ( race_data['state_postal'].lower(), race_data['district_id']) candidate_count = (len(row) - len(RACE_FIELDS)) / len(CANDIDATE_FIELDS) rq = Race.update( precincts_reporting=race_data['precincts_reporting'], ).where(Race.slug == race_data['slug']) rq.execute() i = 0 while i < candidate_count: first_field = len(RACE_FIELDS) + (i * len(CANDIDATE_FIELDS)) last_field = first_field + len(CANDIDATE_FIELDS) candidate_data = dict(zip(CANDIDATE_FIELDS, row[first_field:last_field])) if candidate_data['ap_winner'] == 'X': candidate_data['ap_winner'] = True else: candidate_data['ap_winner'] = False if candidate_data['incumbent'] == "1": candidate_data['incumbent'] = True else: candidate_data['incumbent'] = False if candidate_data['ap_winner'] == True: rq = Race.update( ap_called=True, ap_called_time=datetime.datetime.now(tz=pytz.utc))\ .where(Race.slug == race_data['slug'], Race.ap_called == False) rq.execute() cq = Candidate.update( ap_winner=candidate_data['ap_winner'], vote_count=candidate_data['vote_count'] ).where( Candidate.npid == candidate_data['npid']) cq.execute() i += 1
def test_house_extra(self): with test_database(test_db, [ Race, ]): data.load_races('data/tests/init_races.json') data.load_house_extra('data/house-extra.csv', quiet=True) race = Race.get(Race.race_id == '38529-OR') self.assertEqual(race.previous_party, 'gop') self.assertFalse(race.featured_race)
def return_race_id_from_name_and_district(name, district): try: race = db_session.query(Race)\ .filter(Race.race_name == name)\ .filter(Race.race_district == district).one() except Exception as e: race = Race() race.race_name = name race.race_district = district db_session.add(office) db_session.commit() db_session.begin() return office.id
def test_top_choices(self): with test_database(test_db, [Race, Candidate], create_tables=True): data.load_races('data/tests/init_races.json') data.load_candidates('data/tests/init_candidates.json') data.load_updates('data/tests/update.json') race = Race.get(Race.race_id == '27456-MO') top_choices = race.top_choices() self.assertEqual(top_choices[0].last_name, 'Yes') self.assertEqual(top_choices[1].last_name, 'No')
def test_top_candidates(self): with test_database(test_db, [Race, Candidate], create_tables=True): data.load_races('data/tests/init_races.json') data.load_candidates('data/tests/init_candidates.json') data.load_updates('data/tests/update.json') race = Race.get(Race.race_id == '38529-OR') top_candidates = race.top_candidates() self.assertEqual(top_candidates[0].party, 'Dem') self.assertEqual(top_candidates[1].party, 'GOP')
def parse_house(row): race_data = dict(zip(RACE_FIELDS, row[:len(RACE_FIELDS)])) race_data['slug'] = u'%s%s' % (race_data['state_postal'].lower(), race_data['district_id']) candidate_count = (len(row) - len(RACE_FIELDS)) / len(CANDIDATE_FIELDS) rq = Race.update( precincts_reporting=race_data['precincts_reporting'], ).where( Race.slug == race_data['slug']) rq.execute() i = 0 while i < candidate_count: first_field = len(RACE_FIELDS) + (i * len(CANDIDATE_FIELDS)) last_field = first_field + len(CANDIDATE_FIELDS) candidate_data = dict( zip(CANDIDATE_FIELDS, row[first_field:last_field])) if candidate_data['ap_winner'] == 'X': candidate_data['ap_winner'] = True else: candidate_data['ap_winner'] = False if candidate_data['incumbent'] == "1": candidate_data['incumbent'] = True else: candidate_data['incumbent'] = False if candidate_data['ap_winner'] == True: rq = Race.update( ap_called=True, ap_called_time=datetime.datetime.now(tz=pytz.utc))\ .where(Race.slug == race_data['slug'], Race.ap_called == False) rq.execute() cq = Candidate.update(ap_winner=candidate_data['ap_winner'], vote_count=candidate_data['vote_count']).where( Candidate.npid == candidate_data['npid']) cq.execute() i += 1
def test_ballot_measures_extra(self): with test_database(test_db, [ Race, ]): data.load_races('data/tests/init_races.json') data.load_ballot_measures_extra('data/ballot-measures-extra.csv', quiet=True) race = Race.get(Race.race_id == '27456-MO') self.assertEqual(race.ballot_measure_description, 'Teacher performance evaluation (Amendment 3)')
def chamber_call(chamber): from flask import request race_slug = request.form.get('race_slug', None) race = Race.get(Race.slug == race_slug) # Toggling accept AP call accept_ap_call = request.form.get('accept_ap_call', None) if accept_ap_call != None: if accept_ap_call.lower() == 'true': accept_ap_call = True else: accept_ap_call = False if race_slug != None and accept_ap_call != None: race.accept_ap_call = accept_ap_call race.save() if accept_ap_call == True: Candidate.update(npr_winner=False).where( Candidate.race == race).execute() # Setting NPR winner first_name = request.form.get('first_name', None) last_name = request.form.get('last_name', None) clear_all = request.form.get('clear_all', None) if race_slug != None and clear_all != None: if clear_all == 'true': Candidate.update(npr_winner=False).where( Candidate.race == race).execute() race.npr_called = False race.save() if race_slug != None and first_name != None and last_name != None: Candidate.update(npr_winner=False).where( Candidate.race == race).execute() Candidate.update(npr_winner=True).where( Candidate.race == race, Candidate.first_name == first_name, Candidate.last_name == last_name).execute() race.npr_called = True if race.accept_ap_call == False: if race.npr_called_time == None: race.npr_called_time = datetime.datetime.utcnow() race.save() return 'Success'
def test_is_reporting(self): with test_database(test_db, [Race, Candidate], create_tables=True): data.load_races('data/tests/init_races.json') race = Race.get() self.assertFalse(race.is_reporting()) race.precincts_reporting = 100 race.save() self.assertTrue(race.is_reporting())
def _state_senate_slide(slug): """ Serve a state slide. """ from models import Race, Slide slide = Slide.get(Slide.slug == 'state-senate-results') slug = slug.upper() senate_races = Race.select().where( (Race.office_name == 'U.S. Senate') & (Race.state_postal == slug) ).order_by(Race.seat_number) governor_races = Race.select().where( (Race.office_name == 'Governor') & (Race.state_postal == slug) ) if senate_races.count() == 0 and governor_races.count() == 0: return "404", 404 senate_updated = get_last_updated(senate_races) governor_updated = get_last_updated(governor_races) if senate_updated > governor_updated: timestamp = senate_updated else: timestamp = governor_updated context = make_context(timestamp=timestamp) context['state_postal'] = slug context['state_name'] = app_config.STATES.get(slug) context['slide_class'] = 'state-senate' context['senate'] = senate_races context['governor'] = governor_races context['time_on_screen'] = slide.time_on_screen context['body'] = render_template('slides/state_senate.html', **context) return render_template('_slide.html', **context)
def bootstrap_times(times): for time_zone in times: obj = datetime.datetime.utcfromtimestamp(time_zone['time']) for district in time_zone['districts']: race_district = int(district.split(' ')[1].strip()) race_state = district.split(' ')[0].strip().upper() race = Race.select().where(Race.district_id == race_district, Race.state_postal == race_state).get() race.poll_closing_time = obj race.save()
def test_precincts_reporting_percent(self): with test_database(test_db, [Race, Candidate], create_tables=True): data.load_races('data/tests/init_races.json') data.load_candidates('data/tests/init_candidates.json') data.load_updates('data/tests/update.json') race = Race.select().get() race.precincts_reporting = 700 race.precincts_total = 1100 race.save() self.assertAlmostEqual(race.precincts_reporting_percent(), Decimal('63.636'), 3)
def chamber_call(chamber): from flask import request race_slug = request.form.get('race_slug', None) race = Race.get(Race.slug == race_slug) # Toggling accept AP call accept_ap_call = request.form.get('accept_ap_call', None) if accept_ap_call != None: if accept_ap_call.lower() == 'true': accept_ap_call = True else: accept_ap_call = False if race_slug != None and accept_ap_call != None: race.accept_ap_call = accept_ap_call race.save() if accept_ap_call == True: Candidate.update(npr_winner=False).where(Candidate.race == race).execute() # Setting NPR winner first_name = request.form.get('first_name', None) last_name = request.form.get('last_name', None) clear_all = request.form.get('clear_all', None) if race_slug != None and clear_all != None: if clear_all == 'true': Candidate.update(npr_winner=False).where(Candidate.race == race).execute() race.npr_called = False race.save() if race_slug != None and first_name != None and last_name != None: Candidate.update(npr_winner=False).where(Candidate.race == race).execute() Candidate.update(npr_winner=True).where( Candidate.race == race, Candidate.first_name == first_name, Candidate.last_name == last_name ).execute() race.npr_called = True if race.accept_ap_call == False: if race.npr_called_time == None: race.npr_called_time = datetime.datetime.utcnow() race.save() return 'Success'
def get_last_updated(races): """ Get latest update time from races """ from models import Race races = races.clone() try: last = races.order_by(Race.last_updated.desc()).limit(1).get() except Race.DoesNotExist: last = Race.select().order_by(Race.last_updated).limit(1).get() return last.last_updated
def recent_governor_calls(): """ Get the most recent called Governor races """ from models import Race context = make_context() races = Race.recently_called().where(Race.office_name == 'Governor') context['races'] = races context['label'] = 'Governor' return render_template('slides/recent-calls.html', **context)
def _state_senate_slide(slug): """ Serve a state slide. """ from models import Race, Slide slide = Slide.get(Slide.slug == 'state-senate-results') slug = slug.upper() senate_races = Race.select().where((Race.office_name == 'U.S. Senate') & (Race.state_postal == slug)).order_by( Race.seat_number) governor_races = Race.select().where((Race.office_name == 'Governor') & (Race.state_postal == slug)) if senate_races.count() == 0 and governor_races.count() == 0: return "404", 404 senate_updated = get_last_updated(senate_races) governor_updated = get_last_updated(governor_races) if senate_updated > governor_updated: timestamp = senate_updated else: timestamp = governor_updated context = make_context(timestamp=timestamp) context['state_postal'] = slug context['state_name'] = app_config.STATES.get(slug) context['slide_class'] = 'state-senate' context['senate'] = senate_races context['governor'] = governor_races context['time_on_screen'] = slide.time_on_screen context['body'] = render_template('slides/state_senate.html', **context) return render_template('_slide.html', **context)
def bootstrap_times(times): for time_zone in times: obj = datetime.datetime.utcfromtimestamp(time_zone['time']) for district in time_zone['districts']: race_district = int(district.split(' ')[1].strip()) race_state = district.split(' ')[0].strip().upper() race = Race.select().where( Race.district_id == race_district, Race.state_postal == race_state ).get() race.poll_closing_time = obj race.save()
def _bop(): """ Serve the most recent bop data """ from models import Race context = make_context() races = Race.select().where(Race.office_name == 'U.S. Senate').order_by(Race.state_postal) context['bop'] = app_utils.calculate_bop(races, app_utils.SENATE_INITIAL_BOP) context['not_called'] = app_utils.calculate_seats_left(races) return render_template('bop.html', **context)
def test_update_times(self): with test_database(test_db, [Race, Candidate]): data.load_races('data/tests/init_races.json') data.load_candidates('data/tests/init_candidates.json') data.load_updates('data/tests/update.json') race = Race.get(Race.race_id == '38529-OR') first_last_updated = race.last_updated data.load_updates('data/tests/update.json') race = Race.get(Race.race_id == '38529-OR') last_updated = race.last_updated self.assertEqual(first_last_updated, last_updated) data.load_updates('data/tests/update-votes.json') race = Race.get(Race.race_id == '38529-OR') last_updated = race.last_updated self.assertEqual(first_last_updated, last_updated) data.load_updates('data/tests/update-precincts.json') race = Race.get(Race.race_id == '38529-OR') last_updated = race.last_updated self.assertEqual(first_last_updated, last_updated)
def test_has_incumbent(self): with test_database(test_db, [Race, Candidate], create_tables=True): data.load_races('data/tests/init_races.json') data.load_candidates('data/tests/init_candidates.json') race = Race.get(Race.race_id == '38529-OR') self.assertFalse(race.has_incumbent()) incumbent = race.candidates.get() incumbent.incumbent = True incumbent.save() self.assertTrue(race.has_incumbent())
def load_sql(courses): for course in courses: c1 = Course(name=course.name, going=course.going) c1.save() for race in course.races: r1 = Race( name=race.title, distance=convert_distance_to_yards(race.distance), time=format_time(race.time), runners=race.runners, course=c1) r1.save() for horse in race.horses: h1 = Horse( name=horse.name, race=r1, weight=horse.weight, last_ran=horse.last_ran, forecast_odds=convert_to_decimal_odds(horse.forecast_odds)) h1.save()
def create_race(payload): body = request.get_json() name = body.get('name', None) max_age = body.get('max_age', None) strength_bonus = body.get('strength_bonus', None) speed_bonus = body.get('speed_bonus', None) will_bonus = body.get('will_bonus', None) try: new_race = Race(name=name, max_age=max_age, strength_bonus=strength_bonus, speed_bonus=speed_bonus, will_bonus=will_bonus) new_race.insert() race_list = format_list(Race.query.all()) return jsonify({ 'success': True, 'created_id': new_race.id, 'race_list': race_list, 'number_of_races': len(race_list) }) except BaseException: abort(422)
def test_load_races(self): """ Test loading races from intermediary file. """ with test_database(test_db, [Race, Candidate], create_tables=True): data.load_races('data/tests/init_races.json') race = Race.get(Race.race_id == '38529-OR') self.assertEqual(race.state_postal, 'OR') self.assertEqual(race.office_id, 'H') self.assertEqual(race.office_name, 'U.S. House') self.assertEqual(race.seat_name, "District 2") self.assertEqual(race.seat_number, 2) self.assertEqual(race.race_id, '38529-OR') self.assertEqual(race.race_type, 'G')
def _state_house_slide(slug, page): """ Serve a state slide. """ from models import Race, Slide slide = Slide.get(Slide.slug == 'state-house-results') slug = slug.upper() races = Race.select().where( (Race.office_name == 'U.S. House') & (Race.state_postal == slug) ).order_by(Race.seat_number) timestamp = get_last_updated(races) context = make_context(timestamp=timestamp) context['slide_class'] = 'state-house' context['state_postal'] = slug context['state_name'] = app_config.STATES.get(slug) # Calculate BOP using all races context.update(app_utils.calculate_state_bop(races)) # Filter to display races races = races.where(Race.featured_race == True) if slug in app_config.PAGINATED_STATES: race_count = races.count() page_size = race_count / 2 if page == 1: races = races.limit(page_size) elif page == 2: races = races.offset(page_size) context['page'] = page if races.count(): context['time_on_screen'] = slide.time_on_screen context['races'] = [race for race in races] context['body'] = render_template('slides/state_house.html', **context) return render_template('_slide.html', **context) else: return "no races", 404
def ballot_measures_big_board(): """ Governor big board """ from models import Race races = Race.select().where((Race.office_id == 'I') & (Race.featured_race == True))\ .order_by(Race.poll_closing_time, Race.state_postal) timestamp = get_last_updated(races) context = make_context(timestamp=timestamp) context['page_title'] = 'Ballot Measures' context['page_class'] = 'ballot-measures' context['poll_groups'] = columnize_races(races, 9) return render_template('slides/ballot_measure_results.html', **context)
def governor_big_board(): """ Governor big board """ from models import Race races = Race.select().where(Race.office_name == 'Governor').order_by(Race.poll_closing_time, Race.state_postal) timestamp = get_last_updated(races) context = make_context(timestamp=timestamp) context['page_title'] = 'Governors' context['page_class'] = 'governor' context['poll_groups'] = columnize_races(races, 17) return render_template('slides/race_results.html', **context)
def test_update_calls(self): with test_database(test_db, [Race, Candidate]): data.load_races('data/tests/init_races.json') data.load_candidates('data/tests/init_candidates.json') data.load_calls('data/tests/calls.json') race = Race.get(Race.race_id == '38529-OR') candidate_4848 = Candidate.get(Candidate.candidate_id == '4848-OR') candidate_4642 = Candidate.get(Candidate.candidate_id == '4642-OR') candidate_4979 = Candidate.get(Candidate.candidate_id == '4979-OR') self.assertTrue(race.is_called()) self.assertTrue(race.ap_called) self.assertEqual(race.ap_called_time, datetime(2014, 9, 25, 17, 8, 14)) self.assertEqual(race.get_called_time(), datetime(2014, 9, 25, 17, 8, 14)) self.assertFalse(candidate_4848.ap_winner) self.assertFalse(candidate_4642.ap_winner) self.assertTrue(candidate_4979.ap_winner)
def senate_big_board(): """ Senate big board """ from models import Race races = Race.select().where(Race.office_name == 'U.S. Senate').order_by(Race.poll_closing_time, Race.state_postal) timestamp = get_last_updated(races) context = make_context(timestamp=timestamp) context['page_title'] = 'Senate' context['page_class'] = 'senate' context['poll_groups'] = columnize_races(races, 19) context['bop'] = calculate_bop(races, SENATE_INITIAL_BOP) context['not_called'] = calculate_seats_left(races) return render_template('slides/race_results.html', **context)