def test_if_returns_all_state_cases_from_database(self):
     State().save(self.db.session, abbreviation='SP', name='São Paulo',
                  lat= 12.0001, lng= 25.0001)
     State().save(self.db.session, abbreviation='SP', name='São Paulo',
                  lat= 12.0001, lng= 25.0001)
     StateCases().save(self.db.session, state_id=1, totalcases=1,
                       totalcasesms=1, notconfirmedbyms=0,
                       deaths=0, url='https://some_url.com.br')
     StateCases().save(self.db.session, state_id=2, totalcases=1,
                       totalcasesms=1, notconfirmedbyms=0,
                       deaths=0, url='https://some_url.com.br')
     self.db.session.commit()
     result = state_services.get_state_cases()
     self.assertEqual(len(result), 2)
     self.assertEqual(result, [{
         "stateCode": "SP",
         "stateName": "São Paulo",
         "lat": 12.0001,
         "lng": 25.0001,
         "cases": {
             "totalCases": 1,
             "deaths": 0
         }
     }, {
         "stateCode": "SP",
         "stateName": "São Paulo",
         "lat": 12.0001,
         "lng": 25.0001,
         "cases": {
             "totalCases": 1,
             "deaths": 0
         }
     }])
Example #2
0
def create_state_nodes(df):
    n_nodes = 0
    for _, row in df.drop_duplicates(subset=["state"]).iterrows():
        state = State(name=row["state"])
        state.save()
        n_nodes += 1
    print("created {} nodes".format(n_nodes))
Example #3
0
    def test01_initial_sql(self):
        "Testing geographic initial SQL."
        if DISABLE: return
        if SpatialBackend.oracle:
            # Oracle doesn't allow strings longer than 4000 characters
            # in SQL files, and I'm stumped on how to use Oracle BFILE's
            # in PLSQL, so we set up the larger geometries manually, rather
            # than relying on the initial SQL. 

            # Routine for returning the path to the data files.
            data_dir = os.path.join(os.path.dirname(__file__), 'sql')
            def get_file(wkt_file):
                return os.path.join(data_dir, wkt_file)

            State(name='Colorado', poly=fromfile(get_file('co.wkt'))).save()
            State(name='Kansas', poly=fromfile(get_file('ks.wkt'))).save()
            Country(name='Texas', mpoly=fromfile(get_file('tx.wkt'))).save()
            Country(name='New Zealand', mpoly=fromfile(get_file('nz.wkt'))).save()

        # Ensuring that data was loaded from initial SQL.
        self.assertEqual(2, Country.objects.count())
        self.assertEqual(8, City.objects.count())

        # Oracle cannot handle NULL geometry values w/certain queries.
        if SpatialBackend.oracle: n_state = 2
        else: n_state = 3
        self.assertEqual(n_state, State.objects.count())
Example #4
0
	def post(self):
		action = self.request.POST.get('managerAction')

		if 'toggle' == action:
			state = self.get_state(self.request.POST.get('abbreviation'))
			if state:
				state.striking = not state.striking
				state.put()

		elif 'delete' == action:
			state = self.get_state(self.request.POST.get('abbreviation'))
			if state:
				state.delete()

		elif 'add' == action:
			state = self.get_state(self.request.POST.get('abbreviation'))
			if not state:
				stateName = self.request.POST.get('stateName')
				stateAbbr = self.request.POST.get('abbreviation')
				striking = 'striking' in self.request.POST
				newState = State(name=stateName, abbreviation=stateAbbr, striking=striking)
				newState.put()

		memcache.delete('template_values')
		self.redirect("/manager")
Example #5
0
    def setup_models(self):
        global             Models
        global             MessageState, GroupContact, BroadcastContact
        global             State, Message, Conversation, Contact, Group, MediaType, Media, Broadcast, Status
        from models import State, Message, Conversation, Contact, Group, MediaType, Media, Broadcast, Status
        from models.messagestate import MessageState
        from models.groupcontact import GroupContact
        from models.broadcastcontact import BroadcastContact
        Models = [
            State,
            Message,
            MessageState,
            Conversation,
            Contact,
            Group,
            GroupContact,
            MediaType,
            Media,
            Broadcast,
            BroadcastContact,
            Status
        ]
        logger.debug("setting up models")
        self.db.create_tables(Models, True)

        #init Models that require init to setup initial vals
        State.init()
        MediaType.init()
Example #6
0
def start_game(offer):
  error = False
  try:
    if 'userId' in session:
      player_id = session['userId']
    else:
      player = Player()
      Player.insert(player)
      player_id = player.id
      session['userId'] = player.id
    offer = Offer.query.filter_by(id=offer).first()
    new_game = Game(player_one=offer.player_one, player_two = player_id)
    Game.insert(new_game)
    game = new_game.id
    offer.delete()
    current_state = State(game_id=new_game.id, move_number=1,move='white',position=start_position)
    State.insert(current_state)
    data = current_state.position
  except:
    error = True
    db.session.rollback()
    print(sys.exc_info())
  finally:
    db.session.close()
  if error:
    return 'error'
  else:
    return redirect(url_for('black', game = game))
Example #7
0
def get_state():
    try:
        state = State.objects.get()
    except State.DoesNotExist:
        state = State()
        state.save()
    return state
 def test_if_fetches_all_state_cases_from_database(self):
     State().save(self.db.session,
                  abbreviation='SP',
                  name='São Paulo',
                  lat=12.0001,
                  lng=25.0001)
     State().save(self.db.session,
                  abbreviation='SP',
                  name='São Paulo',
                  lat=12.0001,
                  lng=25.0001)
     StateCases().save(self.db.session,
                       state_id=1,
                       totalcases=1,
                       totalcasesms=1,
                       notconfirmedbyms=0,
                       deaths=0,
                       url='https://some_url.com.br')
     StateCases().save(self.db.session,
                       state_id=2,
                       totalcases=1,
                       totalcasesms=1,
                       notconfirmedbyms=0,
                       deaths=0,
                       url='https://some_url.com.br')
     self.db.session.commit()
     result = StateCases().fetch_all(self.db.session)
     self.assertEqual(len(result), 2)
Example #9
0
def get_state():
  try:
    state = State.objects.get()
  except State.DoesNotExist:
    state = State()
    state.save()
  return state
Example #10
0
    def setUp(self):
        """Create test client, add sample data."""

        db.drop_all()
        db.create_all()

        # add states
        s1 = State(name="oh")
        s2 = State(name="ca")
        s3 = State(name="ny")
        s4 = State(name="nc")
        db.session.add_all([s1, s2, s3, s4])
        db.session.commit()

        self.testuser = User.signUp(username="******",
                                    password="******",
                                    email="*****@*****.**",
                                    address_line1="123 Line One",
                                    address_line2="456 Line Two",
                                    state_name="oh",
                                    zip_code="43212")
        self.testuser_id = 111
        self.testuser.id = self.testuser_id
        db.session.commit()

        self.client = app.test_client()
def DO_NOT_RUN():
    state_result = json.loads(
        requests.get(
            'https://corona.lmao.ninja/v2/historical/usacounties').text)
    excluded_states = [
        'diamond princess', 'grand princess', 'american samoa',
        'northern mariana islands'
    ]
    state_result = [
        elem for elem in state_result if elem not in excluded_states
    ]

    # delete existing entries
    print('Deleted ' + str(County.query.delete()) + ' counties')
    print('Deleted ' + str(State.query.delete()) + ' states')

    #repopulate database
    for state_name in state_result:
        result = json.loads(
            requests.get(
                'https://corona.lmao.ninja/v2/historical/usacounties/' +
                state_name + '?lastdays=14').text)

        state = State(name=state_name.title())
        print('State: ' + state.name)

        sum_2_week_cases = 0
        sum_current_cases = 0

        try:
            for county in result:
                name = county['county']
                if name is not None and 'out of' not in name and name != 'unassigned':
                    case_list = list(county['timeline']['cases'].values())
                    cases_2_weeks_ago = case_list[0]
                    current_cases = case_list[-1]
                    new_cases = current_cases - cases_2_weeks_ago

                    sum_2_week_cases += cases_2_weeks_ago
                    sum_current_cases += current_cases

                    print(name)

                    county = County(name=name.title(),
                                    state=state,
                                    cases_2_weeks_ago=cases_2_weeks_ago,
                                    total_cases=current_cases,
                                    new_cases=new_cases)

                    db.session.add(county)

        except Exception as e:
            print('ERROR: Unable to add counties for the state ' + state_name +
                  ' ' + str(e))

        state.cases_2_weeks_ago = sum_2_week_cases
        state.total_cases = sum_current_cases
        state.new_cases = sum_current_cases - sum_2_week_cases
        db.session.commit()
    def setUp(self):
        """Create test client, add sample data."""

        db.drop_all()
        db.create_all()

        self.client = app.test_client()

        # add states
        s1 = State(name="oh")
        s2 = State(name="ca")
        s3 = State(name="ny")
        s4 = State(name="nc")
        db.session.add_all([s1, s2, s3, s4])
        db.session.commit()

        # add test users
        self.testuser = User.signUp(username="******",
                                    password="******",
                                    email="*****@*****.**",
                                    address_line1="123 Sunset Ave",
                                    address_line2="Apt B",
                                    state_name="ca",
                                    zip_code="99999")
        db.session.commit()

        self.testuser = User.query.get(self.testuser.id)

        self.testuser_id = 111
        self.testuser.id = self.testuser_id
        db.session.commit()

        a1 = Address(user_id=self.testuser_id,
                     address_line1="123 Street",
                     state_name="ri",
                     zip_code="43015",
                     favorite=True,
                     nickname="Brutus's House")
        a3 = Address(user_id=self.testuser_id,
                     address_line1="789 Street",
                     state_name="ny",
                     zip_code="88888",
                     favorite=False,
                     nickname="Sister's House")
        a4 = Address(user_id=self.testuser_id,
                     address_line1="112 Street",
                     state_name="nc",
                     zip_code="88888",
                     favorite=True,
                     nickname="Vacation Home")
        db.session.add_all([a1, a3, a4])
        db.session.commit()

        ua1 = User_Addresses(user_id=self.testuser_id, address_id=4)
        ua2 = User_Addresses(user_id=self.testuser_id, address_id=5)
        ua3 = User_Addresses(user_id=self.testuser_id, address_id=6)

        db.session.add_all([ua1, ua2, ua3])
        db.session.commit()
Example #13
0
def move():
    error = False
    if request.method == 'POST':
        content = json.loads(request.data)
        figure = content.get('figure', None)
        promote = content.get('promote', None)
        move_number = content.get('moveNumber', None)
        gameId = content.get('gameId', None)
        app.logger.info('gameId: %s' % gameId)
        if figure:
            if session['userId']:
                state = State.query.filter_by(game_id=gameId).order_by(
                    State.move_number.desc()).first()
                app.logger.info('state: %s' % state)
                check = legal(state, figure, content['move'])
                if check == 1:
                    try:
                        legal_move = reffery(state, figure, content['move'],
                                             promote)
                        next_state = State(
                            game_id=state.game_id,
                            move_number=state.move_number + 1,
                            move=legal_move['next_move'],
                            position=legal_move['new_position'],
                            white_timer=legal_move['time']['white'],
                            black_timer=legal_move['time']['black'])
                        State.insert(next_state)
                        data = next_state.format()
                        cash_put(state.game_id, state.move_number + 1)
                    except:
                        error = True
                        db.session.rollback()
                        app.logger.info(sys.exc_info())
                        app.logger.info(sys.argv[1])
                    finally:
                        db.session.close()
                    if error:
                        return json.dumps({'error': True})
                    return json.dumps(data)
                    #return json.dumps({'promotion': data})
                else:
                    return json.dumps({'error': check})
        if move_number:
            if session['userId']:
                cashed = cash_get(gameId, move_number)
                if cashed:
                    return json.dumps(None)
                state = State.query.join(Game).filter(
                    or_(Game.player_one == session['userId'],
                        Game.player_two == session['userId'])).order_by(
                            State.move_number.desc()).first()
                new_state = state.format()
                db.session.close()
                if move_number < new_state['move_number']:
                    return json.dumps(new_state)
                else:
                    return json.dumps(None)
    else:
        return json.dumps({'kas': 'per huiniene'})
Example #14
0
 def test_to_dict_result(self):
     """ Tests the result of the dict """
     state = State()
     new_dict = state.to_dict()
     self.assertEqual(new_dict["__class__"], "State")
     self.assertEqual(type(new_dict["created_at"]), str)
     self.assertEqual(type(new_dict["updated_at"]), str)
     self.assertEqual(type(new_dict["id"]), str)
Example #15
0
def state_add():
    data = request.get_json()
    if data is None:
        return 'Not a JSON', 400
    if 'name' not in data.keys():
        return 'Missing name', 400
    state = State(**data)
    state.save()
    return jsonify(state.to_json()), 201
def create_state(name, capital, date_est, abbr, motto):
    new_state = State(name=name,
                      capital=capital or None,
                      date_est=date_est or None,
                      abbr=abbr or None,
                      motto=motto or None)
    db.session.add(new_state)
    db.session.commit()
    return jsonify(new_state.as_dict())
Example #17
0
File: main.py Project: llulai/verbs
def main():
    """runs the main program"""
    pre_state = get_pre_state()
    state = State.load(**pre_state) if State.exists(
        **pre_state) else State.new(**pre_state)

    while True:
        state.update_performance(review_verbs(state, state.get_to_review()))
        print_summary(state)
        state.save()
Example #18
0
    def test_return_all_cases_per_state(self):
        State().save(self.db.session,
                     abbreviation='SP',
                     name='São Paulo',
                     lat=12.0001,
                     lng=25.0001)
        State().save(self.db.session,
                     abbreviation='MG',
                     name='Minas Gerais',
                     lat=13.0001,
                     lng=26.0001)
        StateCases().save(self.db.session,
                          state_id=1,
                          totalcases=1,
                          totalcasesms=1,
                          notconfirmedbyms=0,
                          deaths=0,
                          url='https://some_url.com.br')
        StateCases().save(self.db.session,
                          state_id=2,
                          totalcases=5,
                          totalcasesms=3,
                          notconfirmedbyms=2,
                          deaths=8,
                          url='https://some_url.com.br')
        self.db.session.commit()

        resp = self.client.get(
            '/data_api/v1/cases/state',
            headers={
                'Authorization':
                f"Bearer {self.authentication['access_token']}"
            })
        response = json.loads(resp.get_data(as_text=True))
        self.assertEqual(len(response), 2)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(response, [{
            "stateCode": "SP",
            "stateName": "São Paulo",
            "lat": "12.0001",
            "lng": "25.0001",
            "cases": {
                "totalCases": 1,
                "deaths": 0
            }
        }, {
            "stateCode": "MG",
            "stateName": "Minas Gerais",
            "lat": "13.0001",
            "lng": "26.0001",
            "cases": {
                "totalCases": 5,
                "deaths": 8
            }
        }])
Example #19
0
 def test_get_state(self):
     state = State(
         code='NY',
         name='New York',
         innovative_idea='Innovative idea',
         honorable_mention='Honorable mention',
     ).save()
     response = self.client.get(f'/states/{state.code}')
     self.assertEqual(response.status_code, 200)
     json_response = json.loads(response.data)
     self.assertEqual(json_response, state.serialize())
Example #20
0
def states_post():
    """Add a state to storage with given dictionary"""
    obj = request.get_json(silent=True)
    if obj is None:
        return "Not a JSON", 400

    if "name" not in obj:
        return "Missing name", 400

    obj = State(**obj)
    obj.save()
    return jsonify(obj.to_dict()), 201
Example #21
0
    def setUp(self):
        """Create test client, add sample data."""

        db.drop_all()
        db.create_all()

        self.client = app.test_client()

        # add states
        s1 = State(name="oh")
        s2 = State(name="ca")
        s3 = State(name="ny")
        s4 = State(name="nc")
        db.session.add_all([s1, s2, s3, s4])
        db.session.commit()

        # add test users
        self.testuser = User.signUp(username="******",
                                    password="******",
                                    email="*****@*****.**",
                                    address_line1="123 Line One",
                                    address_line2="456 Line Two",
                                    state_name="oh",
                                    zip_code="43212")
        self.testuser_id = 111
        self.testuser.id = self.testuser_id

        self.testuser = User.signUp(username="******",
                                    password="******",
                                    email="*****@*****.**",
                                    address_line1="123 Line One",
                                    address_line2="456 Line Two",
                                    state_name="ny",
                                    zip_code="43212")
        self.testuser_two_id = 222
        self.testuser_two.id = self.testuser_two_id

        db.session.commit()

        testuser = User.query.get(self.testuser_id)
        testuser_two = User.query.get(self.testuser_two_id)

        self.testuser = testuser
        self.testuser_id = self.testuser_id

        self.testuser_two = testuser_two
        self.testuser_two_id = self.testuser_two_id

        self.u3 = User.signUp("three_user", "*****@*****.**", "password", "ca")
        self.u4 = User.signUp("four_user", "*****@*****.**", "password", "ca")

        db.session.commit()
Example #22
0
def post_state():
    """use the post method to create"""
    try:
        if not request.is_json:
            return make_response(jsonify({'error': 'Not a JSON'}), 400)
        req = request.get_json()
    except:
        return make_response(jsonify({'error': 'Not a JSON'}), 400)
    dict_name = req.get("name")
    if dict_name is None:
        return make_response(jsonify({'error': 'Missing name'}), 400)
    new_state = State(**req)
    return(jsonify(new_state.to_dict()), 201)
Example #23
0
    def test_child_State(self):
        """ Tests if the class State is a child class """
        state = State()
        self.assertIsInstance(state, BaseModel)
        self.assertTrue(hasattr(state, "id")
        self.assertTrue(hasattr(state, "created_at"))
        self.assertTrue(hasattr(state, "updated_at"))

    def test_name(self):
        """ Tests for the attr name"""
        state = State()
        self.assertTrue(hasattr(state, "name"))
        self.assertEqual(state.name, ""))
Example #24
0
def post_states():

    content = request.get_json()
    if content is None:
        return (jsonify({"error": "Not a JSON"}), 400)
    name = content.get("name")
    if name is None:
        return (jsonify({"error": "Missing name"}), 400)

    new_state = State(**content)
    new_state.save()

    return (jsonify(new_state.to_dict()), 201)
Example #25
0
def post_states(states_id):
    """
    Post to states
    """
    state = request.get_json()
    if not state:
        return ("Not a JSON", 400)
    elif state.get("name") is None:
        return (abort(400, "Missing name"))
    else:
        add_state = State(name=state['name'])
        storage.new(add_state)
        state_tojson = storage.get("State", add_state.id).to_json()
        add_state.save()
        return (jsonify(state_tojson))
Example #26
0
def post_state():
    """ Adds a new state to State
    """
    try:
        if request.json:
            if 'name' not in request.json:
                return jsonify({'error': 'Missing name'}), 400
            news = request.get_json().get('name')
            newo = State(name=news)
            newo.save()
            return jsonify(newo.to_dict()), 201
        else:
            return jsonify({'error': 'Not a JSON'}), 400
    except:
        abort(404)
def create_state():
    '''
    Creates a State.
    '''
    if not request.is_json:
        abort(400, "Not a JSON")
    update = request.get_json()
    if 'name' not in update.keys():
        abort(400, "Missing name")
    new_state = State()
    storage.new(new_state)
    for key, value in update.items():
        new_state.__dict__[key] = value
    storage.save()
    return jsonify(new_state.to_dict()), 201
Example #28
0
def add_state():
    """Creates a State object"""
    req = request.get_json()

    if req is None:
        return (jsonify("Not a JSON"), 400)

    try:
        req['name']
    except:
        return (jsonify("Missing name"), 400)
    data = State(**req)  # unpack dictionary
    data.save()

    return (jsonify(data.to_json()), 201)
Example #29
0
 def test_create_state_failure(self):
     from models import State
     try:
         State()
         self.assert_(False, "Abstract class couldn't have instance")
     except:
         pass
Example #30
0
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()
Example #31
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
Example #32
0
    def test_search_on_location_by_term_returns_Null_when_not_exists(self):
        State().save(self.db.session,
                     id=1,
                     name="state1",
                     abbreviation="s1",
                     lat=0,
                     lng=0)
        City().save(self.db.session,
                    id=1,
                    city='c1',
                    ibge_id=1,
                    country='Country1',
                    state_id=1,
                    totalcases=10)
        City().save(self.db.session,
                    id=2,
                    city='c2',
                    ibge_id=2,
                    country='Country1',
                    state_id=1,
                    totalcases=20)
        self.db.session.commit()

        response = city_services.search_on_location_by_term('c3')

        self.assertEqual(len(response), 0)
        self.assertEqual(response, [])
Example #33
0
    def test_return_404_when_city_report_by_term_not_exists(self):
        State().save(self.db.session,
                     id=1,
                     name="state1",
                     abbreviation="s1",
                     lat=0,
                     lng=0)
        City().save(self.db.session,
                    id=1,
                    city='c1',
                    ibge_id=1,
                    country='Country1',
                    state_id=1,
                    totalcases=10)
        City().save(self.db.session,
                    id=2,
                    city='c2',
                    ibge_id=2,
                    country='Country1',
                    state_id=1,
                    totalcases=20)
        self.db.session.commit()

        resp = self.client.get(
            '/data_api/v1/cases/city/c3/report',
            headers={
                'Authorization':
                f"Bearer {self.authentication['access_token']}"
            })

        self.assertEqual(resp.status_code, 404)
Example #34
0
def claimPot():
    """Lets a user claim to have made a teapot

    Args:
        - None
    Returns:
        - {'submitMessage': 'Error / Success Message'}
    """
    latest_full_pot = State.get_latest_full_teapot()
    if latest_full_pot.claimed_by:
        return jsonify({'submitMessage': 'Pot has already been claimed'})
    try:
        maker = json.loads(request.data)['potMaker']
    except KeyError:
        return jsonify({'submitMessage': 'You need to select a pot maker'})

    maker = PotMaker.get_single_pot_maker(maker)
    maker.number_of_pots_made += 1
    maker.total_weight_made += latest_full_pot.weight
    maker.number_of_cups_made += latest_full_pot.num_of_cups
    if maker.largest_single_pot < latest_full_pot.weight:
        maker.largest_single_pot = latest_full_pot.weight
    maker.save()
    latest_full_pot.claimed_by = maker
    latest_full_pot.save()
    return jsonify({'submitMessage': 'Pot claimed, thanks, %s' % maker.name})
Example #35
0
def bootstrap_president():
    """
    Creates/overwrites presidential state results with initial data.
    """
    with open('initial_data/president_bootstrap.csv') as f:
        reader = csv.DictReader(f)
        for row in reader:
            for field in ['total_precincts', 'precincts_reporting', 'rep_vote_count', 'dem_vote_count']:
                if row[field] == '':
                    row[field] = 0
            try:
                state = State.select().where(
                    State.id == row['id']
                ).get()
                state.update(**row)
            except State.DoesNotExist:
                state = State.create(**row)

            state.save()
Example #36
0
def update_polls():
    pollster = Pollster()

    for state in State.select().where(State.electoral_votes > 1):
        charts = pollster.charts(topic='2012-president', state=state.id)

        if charts:
            chart = charts[0]
        else:
            print 'NO DATA FOR %s' % state.id.upper()
            continue

        obama = 0
        romney = 0

        if chart.estimates:
            for estimate in chart.estimates:
                if estimate['choice'] == "Obama":
                    obama = estimate['value']
                elif estimate['choice'] == "Romney":
                    romney = estimate['value']
        else:
            print 'NO ESTIMATES FOR %s' % state.id.upper()
            continue

        prediction = "t"

        if abs(obama - romney) > 15:
            if obama > romney:
                prediction = "sd"
            else:
                prediction = "sr"
        elif abs(obama - romney) > 7.5:
            if obama > romney:
                prediction = "ld"
            else:
                prediction = "lr"

        uq = State.update(prediction=prediction).where(State.id == state)
        uq.execute()
Example #37
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
Example #38
0
def template_values():
	values = memcache.get("template_values")
	if(values is not None):
		return values
	
	laender = dict([(s.name, s.striking) for s in State.all()])
	striking = any(laender.values())
	values = {'streik': striking, 
		'laender': laender,
		'title': title(striking),
		'twitter_text': twitter_text(striking)}
	
	memcache.add("template_values", values)
	return values
Example #39
0
def parse_president_district(state_code, row):
    race_data = dict(zip(DISTRICT_RACE_FIELDS, row[:len(DISTRICT_RACE_FIELDS)]))
    candidate_count = (len(row) - len(DISTRICT_RACE_FIELDS)) / len(DISTRICT_CANDIDATE_FIELDS)

    i = 0
    obama_data = None
    romney_data = None
    total_vote_count = 0

    while i < candidate_count:
        first_field = len(DISTRICT_RACE_FIELDS) + (i * len(DISTRICT_CANDIDATE_FIELDS))
        last_field = first_field + len(DISTRICT_CANDIDATE_FIELDS)

        candidate_data = dict(zip(DISTRICT_CANDIDATE_FIELDS, row[first_field:last_field]))

        if candidate_data['last_name'] == 'Obama':
            obama_data = candidate_data
        elif candidate_data['last_name'] == 'Romney':
            romney_data = candidate_data

        total_vote_count += int(candidate_data['vote_count'])

        i += 1

    assert obama_data and romney_data

    if race_data['district_name'] == state_code:
        q = (State.id == state_code.lower())
    else:
        district_number = race_data['district_name'][-1:]
        q = (State.id == state_code.lower() + district_number)

    state = State.select().where(q).get()
    ap_call = 'r' if romney_data['ap_winner'] else 'd' if obama_data['ap_winner'] else 'u'

    ap_called_at = state.ap_called_at

    if ap_call != state.ap_call:
        ap_called_at = datetime.datetime.now(tz=pytz.utc)

    state.ap_call = ap_call
    state.ap_called_at = ap_called_at
    state.total_precincts = race_data['total_precincts']
    state.precincts_reporting = race_data['precincts_reporting']
    state.rep_vote_count = romney_data['vote_count']
    state.dem_vote_count = obama_data['vote_count']
    state.total_vote_count = total_vote_count

    state.save()
Example #40
0
File: cron.py Project: METAJIJI/la2
def check_servers(id, host, port, timeout, server):

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(float(timeout))

        if sock.connect_ex((host, int(port))) == 0:
            b = State(id=id, active=True, server=server)
            b.save()
        else:
            b = State(id=id, active=False, server=server)
            b.save()
Example #41
0
 def start(self):
     """
     Start new Game with width, height
         Initial the State from the Game
         Build all the blocks one by one
         Pick weak robot as a default Robot
         Let the player play first as default
         Set the result label to 'Playing'
         Unlock the application
     """
     self.game = Game(self.width, self.height)
     self.state = State(self.game)
     # generate the blocks
     self.block = {}
     for k in self.state.board.keys():
         self.block[k] = Block(self, k)
     self.pick_weak_robot()
     self.player_first()
     self.result_label.config(text='Playing')
     self.lock = False
Example #42
0
def write_electris_json():
    """
    Rewrites JSON files from the DB for president.
    """
    output_states = []

    for state in State.select().order_by(State.electoral_votes.desc(), State.name.asc()):
        state = state._data

        if state['npr_call'] != 'n' and state['npr_call'] != 'u':
            state['call'] = state['npr_call']
            state['called_at'] = state['npr_called_at']
            state['called_by'] = 'npr'
        elif state['accept_ap_call'] and state['ap_call'] != 'u':
            state['call'] = state['ap_call']
            state['called_at'] = state['ap_called_at']
            state['called_by'] = 'ap'
        else:
            state['call'] = None
            state['called_at'] = None
            state['called_by'] = None

        del state['npr_call']
        del state['npr_called_at']
        del state['ap_call']
        del state['ap_called_at']

        del state['called_by']
        del state['accept_ap_call']
        del state['rowid']
        del state['prediction']

        output_states.append(state)

    output = json.dumps({
        'balance_of_power': produce_bop_json(),
        'states': output_states
    })

    with open(settings.PRESIDENT_FILENAME, 'w') as f:
        f.write(output)
Example #43
0
def write_replay_json():
    def _scale_time(time):
        first_time = datetime.datetime(2012, 11, 06, 19, 04, 02)
        delta = time - first_time
        return round(delta.seconds * 0.00321, 0) * 1000

    output = []
    states = sorted(State.select(), key=lambda state: state.called_time)
    for state in states:
        state_dict = state._data
        state_dict['scaled_time'] = _scale_time(state.called_time)

        if state_dict['npr_call'] != 'n' and state_dict['npr_call'] != 'u':
            state_dict['call'] = state_dict['npr_call']
            state_dict['called_at'] = state_dict['npr_called_at']
            state_dict['called_by'] = 'npr'
        elif state_dict['accept_ap_call'] and state_dict['ap_call'] != 'u':
            state_dict['call'] = state_dict['ap_call']
            state_dict['called_at'] = state_dict['ap_called_at']
            state_dict['called_by'] = 'ap'
        else:
            state_dict['call'] = None
            state_dict['called_at'] = None
            state_dict['called_by'] = None

        del state_dict['npr_call']
        del state_dict['npr_called_at']
        del state_dict['ap_call']
        del state_dict['ap_called_at']

        del state_dict['called_by']
        del state_dict['accept_ap_call']
        del state_dict['rowid']
        del state_dict['prediction']

        output.append(state_dict)

    with open('www/replay.json', 'w') as f:
        f.write(json.dumps(output))
Example #44
0
    def test02_proxy(self):
        "Testing Lazy-Geometry support (using the GeometryProxy)."
        #### Testing on a Point
        pnt = Point(0, 0)
        nullcity = City(name='NullCity', point=pnt)
        nullcity.save()

        # Making sure TypeError is thrown when trying to set with an
        #  incompatible type.
        for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
            try:
                nullcity.point = bad
            except TypeError:
                pass
            else:
                self.fail('Should throw a TypeError')

        # Now setting with a compatible GEOS Geometry, saving, and ensuring
        #  the save took, notice no SRID is explicitly set.
        new = Point(5, 23)
        nullcity.point = new

        # Ensuring that the SRID is automatically set to that of the 
        #  field after assignment, but before saving.
        self.assertEqual(4326, nullcity.point.srid)
        nullcity.save()

        # Ensuring the point was saved correctly after saving
        self.assertEqual(new, City.objects.get(name='NullCity').point)

        # Setting the X and Y of the Point
        nullcity.point.x = 23
        nullcity.point.y = 5
        # Checking assignments pre & post-save.
        self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point)
        nullcity.save()
        self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point)
        nullcity.delete()

        #### Testing on a Polygon
        shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0))
        inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))

        # Creating a State object using a built Polygon
        ply = Polygon(shell, inner)
        nullstate = State(name='NullState', poly=ply)
        self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None
        nullstate.save()

        ns = State.objects.get(name='NullState')
        self.assertEqual(ply, ns.poly)
        
        # Testing the `ogr` and `srs` lazy-geometry properties.
        if gdal.HAS_GDAL:
            self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry))
            self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
            self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference))
            self.assertEqual('WGS 84', ns.poly.srs.name)

        # Changing the interior ring on the poly attribute.
        new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
        ns.poly[1] = new_inner
        ply[1] = new_inner
        self.assertEqual(4326, ns.poly.srid)
        ns.save()
        self.assertEqual(ply, State.objects.get(name='NullState').poly)
        ns.delete()
Example #45
0
 def player_first(self):
     self.btn_pf.config(state='disabled')
     self.btn_rf.config(state='normal')
     self.state = State(self.game, 'o')
     self.restart()
Example #46
0
class Application(Frame):

    """
    Application Main Class
    """

    def __init__(self, width=5, height=4):
        master = Tk()
        Frame.__init__(self, master)
        self.lock = False
        self.pack()
        self.width = width
        self.height = height
        self.master = master
        self.master.title('M N K %d %d %d' % (self.width, self.height, 4))
        self.master.resizable(width=FALSE, height=FALSE)
        self.master.geometry("%dx%d" %
                            (self.width * 100,
                             self.height * 100 + 100))
        self.generate_widgets()
        self.start()

    def start(self):
        """
        Start new Game with width, height
            Initial the State from the Game
            Build all the blocks one by one
            Pick weak robot as a default Robot
            Let the player play first as default
            Set the result label to 'Playing'
            Unlock the application
        """
        self.game = Game(self.width, self.height)
        self.state = State(self.game)
        # generate the blocks
        self.block = {}
        for k in self.state.board.keys():
            self.block[k] = Block(self, k)
        self.pick_weak_robot()
        self.player_first()
        self.result_label.config(text='Playing')
        self.lock = False

    def restart(self):
        """
        Restart the Game
            Reset the State
            Delete all painting on canvas
            Reset the result Label
            Unlock the application
        """
        self.state.start_new()
        for k in self.block.values():
            k.canvas.delete("all")
        self.result_label.config(text='Playing')
        self.lock = False

        if self.state.to_move == 'x':
            Robot(self, None).start()

    def pick_weak_robot(self):
        self.robot_level = 0
        self.btn_w.config(state='disabled')
        self.btn_m.config(state='normal')
        self.btn_s.config(state='normal')

    def pick_mid_robot(self):
        self.robot_level = 1
        self.btn_w.config(state='normal')
        self.btn_m.config(state='disabled')
        self.btn_s.config(state='normal')

    def pick_strong_robot(self):
        self.robot_level = 2
        self.btn_w.config(state='normal')
        self.btn_m.config(state='normal')
        self.btn_s.config(state='disabled')

    def player_first(self):
        self.btn_pf.config(state='disabled')
        self.btn_rf.config(state='normal')
        self.state = State(self.game, 'o')
        self.restart()

    def robot_first(self):
        self.btn_pf.config(state='normal')
        self.btn_rf.config(state='disabled')
        self.state = State(self.game, 'x')
        self.restart()

    def generate_widgets(self):
        # generate the buttons
        self.btn_pf = Button(
            self.master, text="PlayerFirst", command=self.player_first)
        self.btn_rf = Button(
            self.master, text="RobotFirst", command=self.robot_first)
        self.btn_w = Button(
            self.master, text="Weak", command=self.pick_weak_robot)
        self.btn_m = Button(
            self.master, text="Mid", command=self.pick_mid_robot)
        self.btn_s = Button(
            self.master, text="Strong", command=self.pick_strong_robot)
        self.btn_re = Button(
            self.master, text="Restart", command=self.restart)
        self.btn_w.pack()
        self.btn_m.pack()
        self.btn_s.pack()
        self.btn_re.pack()
        self.btn_pf.pack()
        self.btn_rf.pack()
        self.btn_w.place(x=10, y=self.height * 100 + 25)
        self.btn_m.place(x=70, y=self.height * 100 + 25)
        self.btn_s.place(x=121, y=self.height * 100 + 25)
        self.btn_pf.place(x=10, y=self.height * 100 + 55)
        self.btn_rf.place(x=110, y=self.height * 100 + 55)
        self.btn_re.place(x=210, y=self.height * 100 + 55)
        # generate the progress bar
        self.progress = ttk.Progressbar(self.master,
                                        orient="horizontal",
                                        length=self.width * 100 - 20,
                                        mode="determinate")
        self.progress.pack()
        self.progress.place(x=10, y=self.height * 100 + 5)
        # generate the label
        self.robot_thinking_time_label = Label(self.master, text="Used:0s")
        self.robot_thinking_time_label.pack()
        self.robot_thinking_time_label.place(
            x=self.width * 100 - 150, y=self.height * 100 + 25)
        self.result_label = Label(self.master, text="Result")
        self.result_label.pack()
        self.result_label.place(
            x=self.width * 100 - 150, y=self.height * 100 + 55)
Example #47
0
def write_president_json():
    """
    Outputs the president json file for bigboard's frontend.
    """

    data = {}
    data['balance_of_power'] = produce_bop_json()
    data['results'] = []

    for timezone in time_zones.PRESIDENT_TIMES:
        timezone_dict = {}
        timezone_dict['gmt_epoch_time'] = timezone['time']
        timezone_dict['states'] = []
        for s in timezone['states']:
            for state in State.select():
                if state.id == s.lower():
                    state_dict = state._data
                    state_dict['rep_vote_percent'] = state.rep_vote_percent()
                    state_dict['dem_vote_percent'] = state.dem_vote_percent()
                    state_dict['human_gop_vote_count'] = state.human_rep_vote_count()
                    state_dict['human_dem_vote_count'] = state.human_dem_vote_count()
                    state_dict['called'] = state.called
                    state_dict['winner'] = state.winner

                    if state_dict['npr_call'] != 'n' and state_dict['npr_call'] != 'u':
                        state_dict['call'] = state_dict['npr_call']
                        state_dict['called_at'] = state_dict['npr_called_at']
                        state_dict['called_by'] = 'npr'
                    elif state_dict['accept_ap_call'] and state_dict['ap_call'] != 'u':
                        state_dict['call'] = state_dict['ap_call']
                        state_dict['called_at'] = state_dict['ap_called_at']
                        state_dict['called_by'] = 'ap'
                    else:
                        state_dict['call'] = None
                        state_dict['called_at'] = None
                        state_dict['called_by'] = None

                    call_time = None
                    if state_dict['called_at'] != None:
                        call_time = datetime.datetime.strptime(state_dict['called_at'].split('+')[0], '%Y-%m-%d %H:%M:%S.%f')
                        call_time = utc.normalize(utc.localize(call_time))

                    if state_dict['called_at'] != None:
                        state_dict['status_tag'] = 'Called time.'
                        state_dict['status'] = call_time.astimezone(eastern).strftime('%I:%M').lstrip('0')
                    else:
                        if state.precincts_reporting > 0:
                            state_dict['status_tag'] = 'Percent reporting.'
                            pct = state.percent_reporting()

                            if pct < 1:
                                state_dict['status'] = u'< 1%'
                            elif pct > 99 and pct < 100:
                                state_dict['status'] = u'99%'
                            else:
                                state_dict['status'] = u'%.0f%%' % pct
                        else:
                            state_dict['status_tag'] = 'No precincts reporting.'
                            if state_dict['dem_vote_count'] + state_dict['rep_vote_count'] > 0:
                                state_dict['status'] = u'< 1%'
                            else:
                                state_dict['status'] = u'&nbsp;'

                    timezone_dict['states'].append(state_dict)
            timezone_dict['states'] = sorted(timezone_dict['states'], key=lambda state: state['name'])
        data['results'].append(timezone_dict)

    with open('www/president.json', 'w') as f:
        f.write(json.dumps(data))
Example #48
0
	def get_state(self, abbreviation):
		stateQuery = State.all()
		stateQuery.filter("abbreviation =", abbreviation)
		state = stateQuery.get()
		return state
Example #49
0
def president(featured=None):
    """
    Read/update list of presidential state winners.
    """

    is_featured = False
    if featured == 'featured':
        is_featured = True

    if request.method == 'GET':

        states = State.select().order_by(State.name.asc())

        if is_featured == True:
            states = states.where(State.prediction == 't').order_by(State.name.asc())

        context = {
            'states': states,
            'settings': settings
        }

        return render_template('president.html', **context)

    if request.method == 'POST':
        # First, try and get the state.
        race_slug = request.form.get('race_slug', None)
        race_slug = race_slug.strip()

        # Next, try to get the AP call.
        accept_ap_call = request.form.get('accept_ap_call', None)

        if accept_ap_call != None:
            # Figure out which direction we're going and send an appropriate message.
            if accept_ap_call.lower() == 'true':
                accept_ap_call = True
            else:
                accept_ap_call = False

        # Accumulate changes so we only execute a single update
        update_dict = {}

        # If all the pieces are here, do something.
        if race_slug != None and accept_ap_call != None:

            # Run some SQL to change the status of this set of candidate's accept_ap_call column.
            sq = State.update(accept_ap_call=accept_ap_call).where(State.id == race_slug)
            sq.execute()

            # Clear the NPR winner status of candidates who we accept AP calls for.
            if accept_ap_call == True:
                update_dict['npr_call'] = 'n',
                update_dict['npr_called_at'] = None

        # Try and get the winner.
        party = request.form.get('party', None)

        # Try and get a clear_all.
        clear_all = request.form.get('clear_all', None)

        if race_slug != None and clear_all != None:
            # If we're passing clear_all as true ...
            if clear_all == 'true':
                update_dict['npr_call'] = 'n',
                update_dict['npr_called_at'] = None

        # If all of the pieces are here, do something.
        if race_slug != None and party != None:
            update_dict['npr_call'] = party,
            update_dict['npr_called_at'] = datetime.datetime.utcnow()

        if update_dict:
            uq = State.update(**update_dict).where(State.id == race_slug)
            uq.execute()

        if settings.DEBUG:
            o.write_electris_json()
            o.write_president_json()
            o.write_bop_json()

        # TODO
        # Return a 200. This is probably bad.
        # Need to figure out what should go here.
        return "Success."
Example #50
0
    def test04_layermap_unique_multigeometry_fk(self):
        "Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings."
        # All the following should work.
        try:
            # Telling LayerMapping that we want no transformations performed on the data.
            lm = LayerMapping(County, co_shp, co_mapping, transform=False)

            # Specifying the source spatial reference system via the `source_srs` keyword.
            lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269)
            lm = LayerMapping(County, co_shp, co_mapping, source_srs='NAD83')

            # Unique may take tuple or string parameters.
            for arg in ('name', ('name', 'mpoly')):
                lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg)
        except:
            self.fail('No exception should be raised for proper use of keywords.')

        # Testing invalid params for the `unique` keyword.
        for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))):
            self.assertRaises(e, LayerMapping, County, co_shp, co_mapping, transform=False, unique=arg)

        # No source reference system defined in the shapefile, should raise an error.
        if not mysql:
            self.assertRaises(LayerMapError, LayerMapping, County, co_shp, co_mapping)

        # Passing in invalid ForeignKey mapping parameters -- must be a dictionary
        # mapping for the model the ForeignKey points to.
        bad_fk_map1 = copy(co_mapping); bad_fk_map1['state'] = 'name'
        bad_fk_map2 = copy(co_mapping); bad_fk_map2['state'] = {'nombre' : 'State'}
        self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False)
        self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False)

        # There exist no State models for the ForeignKey mapping to work -- should raise
        # a MissingForeignKey exception (this error would be ignored if the `strict`
        # keyword is not set).
        lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
        self.assertRaises(MissingForeignKey, lm.save, silent=True, strict=True)

        # Now creating the state models so the ForeignKey mapping may work.
        co, hi, tx = State(name='Colorado'), State(name='Hawaii'), State(name='Texas')
        co.save(), hi.save(), tx.save()

        # If a mapping is specified as a collection, all OGR fields that
        # are not collections will be converted into them.  For example,
        # a Point column would be converted to MultiPoint. Other things being done
        # w/the keyword args:
        #  `transform=False`: Specifies that no transform is to be done; this
        #    has the effect of ignoring the spatial reference check (because the
        #    county shapefile does not have implicit spatial reference info).
        #
        #  `unique='name'`: Creates models on the condition that they have
        #    unique county names; geometries from each feature however will be
        #    appended to the geometry collection of the unique model.  Thus,
        #    all of the various islands in Honolulu county will be in in one
        #    database record with a MULTIPOLYGON type.
        lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
        lm.save(silent=True, strict=True)

        # A reference that doesn't use the unique keyword; a new database record will
        # created for each polygon.
        lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False)
        lm.save(silent=True, strict=True)

        # The county helper is called to ensure integrity of County models.
        self.county_helper()
Example #51
0
	def get(self):
		states = list(State.all())
		template_values = {'states': states}
		path = os.path.join(os.path.dirname(__file__), 'templates', 'manager.html')
		self.response.out.write(template.render(path, template_values))
Example #52
0
 def robot_first(self):
     self.btn_pf.config(state='normal')
     self.btn_rf.config(state='disabled')
     self.state = State(self.game, 'x')
     self.restart()