예제 #1
0
    def _build_line_data(self, station_df):
        """Constructs all stations on the line"""
        logging.debug("line - _build_line_data")

        stations = station_df["station_name"].unique()

        station_data = station_df[station_df["station_name"] == stations[0]]
        line = [
            Station(station_data["station_id"].unique()[0], stations[0],
                    self.color)
        ]
        prev_station = line[0]
        for station in stations[1:]:
            station_data = station_df[station_df["station_name"] == station]
            new_station = Station(
                station_data["station_id"].unique()[0],
                station,
                self.color,
                prev_station,
            )
            prev_station.dir_b = new_station
            prev_station = new_station
            logging.info(f"new_station: {new_station}")
            line.append(new_station)
        return line
예제 #2
0
    def _build_line_data(self, station_df):
        """Constructs all stations on the line"""
        stations = station_df["station_name"].unique()

        logger.info(f"\nunique statns: {stations}")

        station_data = station_df[station_df["station_name"] == stations[0]]

        # logger.info(f"{station_data}")
        line = [
            Station(station_data["station_id"].unique()[0], stations[0],
                    self.color)
        ]
        prev_station = line[0]
        for station in stations[1:]:
            station_data = station_df[station_df["station_name"] == station]
            new_station = Station(
                station_data["station_id"].unique()[0],
                station,
                self.color,
                prev_station,
            )
            prev_station.dir_b = new_station
            prev_station = new_station
            line.append(new_station)
        return line
    def _build_line_data(self, station_df):
        """Constructs all stations on the line"""
        stations = station_df["station_name"].unique()
        
        print('stations:', stations)
        

        station_data = station_df[station_df["station_name"] == stations[0]]
        line = [
            Station(station_data["station_id"].unique()[0], stations[0], self.color)
        ]
        prev_station = line[0]
        for station in stations[1:]:
            station_data = station_df[station_df["station_name"] == station]
            new_station = Station(
                station_data["station_id"].unique()[0],
                station,
                self.color,
                prev_station,
            )
            prev_station.dir_b = new_station
            prev_station = new_station
            line.append(new_station)
            
        #print('line:', type(line), len(line), line)
        #for item in line: 
        #    print(item)
        return line
예제 #4
0
    def _build_line_data(self, station_df):
        '''
        Constructs all stations on the line
        '''

        stations = station_df['station_name'].unique()

        station_data = station_df[station_df['station_name'] == stations[0]]
        line = [
            Station(station_data['station_id'].unique()[0], stations[0],
                    self.color)
        ]
        prev_station = line[0]
        for station in stations[1:]:
            station_data = station_df[station_df['station_name'] == station]
            new_station = Station(
                station_data['station_id'].unique()[0],
                station,
                self.color,
                prev_station,
            )
            prev_station.dir_b = new_station
            prev_station = new_station
            line.append(new_station)
        return line
예제 #5
0
def addStation(data):
    try:
        stationType_id = int(data["stationType"])
        serialNum = data["serialNum"]
        latitude = float(data["latitude"])
        longitude = float(data["longitude"])
        frequency = data["frequency"]
        token = data["token"]

        # se recupera el tipo de estacion
        stationType = StationType.objects.get(id=stationType_id)
        automatic = stationType.automatic
        # se crea una estacion
        station = Station()
        station.serialNum = serialNum
        station.location = Point(longitude, latitude)
        station.active = True
        station.stationType = stationType

        # si la estacion es automatica
        # se agregan la frecuencia
        # y el token
        if (automatic == True):
            if (frequency == "" or token == ""):
                return "Error: faltan argumentos"
            frequency = float(frequency)
            if (frequency <= 0):
                return "Error: frecuencia debe ser mayor que cero"
            station.frequency = frequency
            station.token = token

        station.save()
    except Exception as e:
        return "Error " + str(e)
    return None
예제 #6
0
def populate_by_qs(s, output=stdout):
    encoded_s = s.encode('utf-8')
    output.write('QUERYING FOR %s\n' % encoded_s)
    body = send_req('querystation.asp', {'inpPointFr': encoded_s})
    tree = ElementTree()
    tree.parse(StringIO(body))
    root = tree.getroot()
    points = root.getiterator(NS + 'Point')
    for point in points:
        station = Station()
        station.identifier = int(point.find(NS + 'Id').text)

        try:
            station = Station.objects.get(identifier=station.identifier)
        except Station.DoesNotExist:
            station.name = point.find(NS + 'Name').text
            station.x = int(point.find(NS + 'X').text)
            station.y = int(point.find(NS + 'Y').text)
            station.save()
            output.write('  STORED %s\n' % station.name.encode('utf-8'))
        except Station.MultipleObjectsReturned:
            output.write('  ERROR %d, %s\n' %
                         (station.identifier, station.name.encode('utf-8')))
        else:
            # output.write('  IGNORE %s\n' % (station.name.encode('utf-8')))
            pass
예제 #7
0
파일: main.py 프로젝트: Nagatatz/Animer
def iepginput(d):
    a_title = Title(name=d['program-title'])
    b_waves = Waves(name=d['station'])
    c_station = Station(name=d['station-name'])
    d_comments = Comments(name=d['comment'])
    op = timeset(d, start)
    ed = timeset(d, end)
    sg1 = d['genre-1'] * 16 + d['subgenre-1']
    if d['genre-2'] == 0:
        x = Program(title=a_title,
                    program_id=d['program-id'],
                    waves=b_waves,
                    station=c_station,
                    start=op,
                    end=ed,
                    gen_1=d['genre-1'],
                    sgn_1=sg1,
                    comments=d_comments)
        x.save
    else:
        sg2 = d['genre-2'] * 16 + d['subgenre-2']
        x = Program(title=a_title,
                    program_id=d['program-id'],
                    waves=b_waves,
                    station=c_station,
                    start=op,
                    end=ed,
                    gen_1=d['genre-1'],
                    sgn_1=sg1,
                    gen_2=d['genre-2'],
                    sgn_2=sg2,
                    comments=d_comments)
        x.save
예제 #8
0
def station():

    station = Station(request.form['name'], request.form['lat'],
                      request.form['lng'])

    db.session.add(station)
    db.session.commit()

    return jsonify(Station.query.get(station.id).json())
예제 #9
0
 def add_Station():
     try:
         data = json.loads(request.data)
         print(data)
         station = Station(CrewCapacity=data['crewcapacity'],
                           FuelCapacity=data['fuelcapacity'])
         Station.insert(station)
     except BaseException:
         abort(403)
     return paginate_Station()
    def test_station(self):
        colors = IntEnum("colors", "blue green red", start=0)
        s = Station(40020, "test_station", colors.red)
        print(s)

        t = Train("BLUEL999", Train.status.in_service)
        s.run(t, "a", 90000, "a")

        t = Train("BLUEL998", Train.status.in_service)
        s.run(t, "a", 90001, "a")
예제 #11
0
    def post(self, request):
        response_data = {
            'retCode': error_constants.ERR_STATUS_SUCCESS[0],
            'retMsg': error_constants.ERR_STATUS_SUCCESS[1]
        }
        try:
            station_id = int(request.POST.get('stationId'))
            name = request.POST.get('name')
            location = request.POST.get('location')
            channel = request.POST.get('channel', '')
            call_sign = request.POST.get('callSign', '')
            remark_1 = request.POST.get('remark1', '')
            remark_2 = request.POST.get('remark2', '')
            remark_3 = request.POST.get('remark3', '')
        except Exception as ex:
            print 'function name: ', __name__
            print Exception, ":", ex
            return generate_error_response(
                error_constants.ERR_INVALID_PARAMETER,
                status.HTTP_400_BAD_REQUEST)
        cur_station = Station.objects.get(id=station_id)
        district_id = cur_station.district_id
        section_id = cur_station.section_id
        new_station = Station(name=name,
                              location=location,
                              channel=channel,
                              remark1=remark_1,
                              call_sign=call_sign,
                              remark2=remark_2,
                              remark3=remark_3,
                              district_id=district_id)
        try:
            with transaction.atomic():
                new_station.save()
        except Exception as ex:
            print 'function name: ', __name__
            print Exception, ":", ex
            return generate_error_response(
                error_constants.ERR_SAVE_INFO_FAIL,
                status.HTTP_500_INTERNAL_SERVER_ERROR)
        chief = cur_station.chief.all()
        trans = cur_station.exec_chief_trans.all()
        for item in chief:
            new_station.chief.add(item)
        for item in trans:
            new_station.exec_chief_trans.add(item)

        # 路的段/岗数量更新
        if section_id:
            road_id = Section.objects.get(id=section_id).road_id
            if road_id:
                cur_guard_road = guard_road.objects.filter(uid=road_id +
                                                           increment)
                cur_guard_road.update(sectionnum=F('stationnum') + 1)
        return Response(response_data, status.HTTP_200_OK)
예제 #12
0
    def _build_line_data(self, station_df):
        stations = station_df["station_name"].unique()

        station_data = station_df[station_df["station_name"] == stations[0]]
        line = [
            Station(station_data["station_id"].unique()[0], stations[0], self.color)
        ]
        prev_station = line[0]
        for station in stations[1:]:
            station_data = station_df[station_df["station_name"] == station]
            new_station = Station(
                station_data["station_id"].unique()[0],
                station,
                self.color,
                prev_station,
            )
            prev_station.dir_b = new_station
            prev_station = new_station
            line.append(new_station)
        return line
예제 #13
0
def sample_data():
    station = Station(id=3, name='lelkek', lat=32.551, lng=64.112,
                      is_outside=False)
    bike = Bike(id=4, can_be_rented=False, can_be_returned=False, version=2,
                marke_id=23, marke_name="Kekrad", is_pedelec=False)

    location = TemporalLocation(time_from=datetime.now(),
                                time_to=datetime.now())
    location.bike = bike
    location.station = station

    return station, bike, location
예제 #14
0
    def _build_line_data(self, station_df):
        """Constructs all stations on the line"""
        stations = station_df["station_name"].unique()

        station_data = station_df[station_df["station_name"] == stations[0]]
        line = [
            Station(station_data["station_id"].unique()[0], stations[0],
                    self.color)
        ]
        prev_station = line[0]
        for station in stations[1:]:
            station_data = station_df[station_df["station_name"] == station]
            new_station = Station(
                station_data["station_id"].unique()[0],
                station,
                self.color,
                prev_station,
            )
            prev_station.dir_b = new_station
            prev_station = new_station
            line.append(str(new_station).encode('utf8'))
        return line
예제 #15
0
def create_neo_db():
    # Create temporary station and vehicle
    tmp_station = Station(short='STATI',
                          name='Station',
                          latitude=10.0,
                          longitude=10.0).save()
    tmp_vehicle = Vehicle(code='100').save()

    spatial_query = "CALL spatial.addPointLayer('spati')"
    neo_db.cypher_query(query=spatial_query)

    tmp_station.delete()
    tmp_vehicle.delete()
예제 #16
0
def load_stops():
    session = Session()

    stops = parse_stops()
    stations = []

    for stop in stops:
        if stop['parent'] == '':
            stations.append(
                Station(stop['sid'], stop['name'], stop['lat'], stop['lng']))

    session.add_all(stations)
    session.commit()
예제 #17
0
    def _build_line_data(self, station_df) -> List[Station]:
        """Constructs all stations on the line"""
        stations: List[str]=station_df["station_name"].unique()

        station_data=station_df[station_df["station_name"] == stations[0]]

        line: List[Station]=[
            Station(station_data["station_id"].unique()[0], stations[0], self.color)
        ]
        prev_station=line[0]
        for station in stations[1:]:
            station_data=station_df[station_df["station_name"] == station]
            new_station=Station(
                station_data["station_id"].unique()[0],
                station,
                self.color,
                prev_station,
            )
            prev_station.dir_b=new_station
            prev_station=new_station
            line.append(new_station)
        return line
예제 #18
0
def fill_stations():
    """
    Llena con estaciones (POST)
    """

    # POST request
    if request.method == 'POST':
        for i in range(3):
            station1 = Station(name="Estación"+str(i+1), lattitude=str(i+1), longitude=str(i+2), person_id=1, description="", organization_id=1, streetaddress=str(i+1), numberaddress=str(i+1))
            db.session.add(station1)
        db.session.commit()
        return "ok", 200

    return "Invalid Method", 404
예제 #19
0
def new():
    """
  New station form to create a station.
  """
    form = StationForm(request.form)
    if form.validate_on_submit():
        station = Station(form.name.data, form.location.data,
                          form.comment.data)
        db.session.add(station)
        db.session.commit()

        flash('You have successfully added a new station.', 'success')
        return redirect(url_for('stations.view', id=station.id))
    return render_template('stations/new.html', form=form)
예제 #20
0
def save_barrier_state(name: str, state: str) -> None:
    try:
        station_check_0 = db.session.query(Station).filter_by(name=name).first()
        if station_check_0:
            db.session.query(Station).filter_by(name=name).update(
                {"barrier_state": state}
            )
        else:
            db.session.add(Station(name=name, barrier_state=state))
        db.session.commit()

    except Exception as ex:
        raise Exception(ex)
    finally:
        db.session.close()
예제 #21
0
def create_station(session,
                   service_provider_id,
                   name="TestStation",
                   no_commit=False):
    station = Station(-1, name)
    station.service_provider_id = service_provider_id
    station.short_name = name[:8]
    station.medium_name = name[:16]
    station.long_name = name[:64]
    station.short_description = name[:128]
    station.radioepgpi_enabled = True
    session.add(station)
    if not no_commit:
        session.commit()
        time.sleep(config.SPI_GENERATION_INTERVAL * 3)
    return station
예제 #22
0
    def __push_bus_stops_to_postgis(self):
        print "pushing to postgis"

        session = self.Session()
        session.query(Station).delete()
        i = 0
        for id in self.busStopArray:
            d = self.busStopArray[id]
            stop = Station(name=d.name,
                           id=d.id,
                           geom=from_shape(d.geom, srid=4326))
            session.add(stop)
            i += 1
            if i % 100 == 0:
                session.commit()
        session.commit()
        print "%s stations" % i
        print "stations in array: %s" % len(self.busStopArray)
        print "pushing to postgis -- finished"
예제 #23
0
def get_client_and_station(request, id):
    """
    Utility to reduce boilerplate and return the list of the clients (including default) and the list of a station
    and its overrides.

    :param request: The fask request.
    :param id: The id of the station.
    :return: the client and station lists.
    """
    orga = int(request.args.get('ebuio_orgapk') or request.form.get('ebuio_orgapk'))
    clients = [gen_default_client()] + Clients.query.filter_by(orga=orga).order_by(Clients.id).all()

    if id == '-':
        stations = [Station(orga)] * len(clients)
    else:
        stations = [Station.query.filter_by(orga=orga, id=int(id)).first()] + \
                   Station.query.filter_by(orga=orga, parent=int(id)).order_by(Station.fk_client).all()

    return clients, stations
예제 #24
0
    def post(self):
        station_args = station_parser.parse_args()

        if 'id' not in station_args:
            highest = Station.query.order_by(Station.id).last()
            station_id = highest + 1
        else:
            station_id = station_args['id']

        station = Station(id=station_id,name=station_args['name'],block_id=station_args['block_id'])
        block = Block.query.filter_by(id=station_args['block_id']).first()
        if not block:
            abort(404, "Block %d: not found." % station_args['block_id'])

        block.station_id = station_id

        db.session.add(station)
        db.session.commit()

        return station, 201
예제 #25
0
def combine_client_and_station(request, clients, stations, fill=True):
    """
    Combines a client with its existing station's overrides.

    :param request: The flask Request.
    :param clients: The clients list.
    :param stations: The stations list.
    :param fill: If true, any client left without a station will be set with a new empty station in the result list.
    If false, the client will be ignored.
    :return: A list of tuple of the shape List<(client, station)>
    """
    orga = int(request.args.get('ebuio_orgapk') or request.form.get('ebuio_orgapk'))
    clients_stations = [(clients[0], stations[0])]

    for client in clients[1:]:
        filtered_stations = filter(lambda s: s.fk_client == client.id, stations[1:])
        if len(filtered_stations) != 0:
            clients_stations.append((client, filtered_stations[0]))
        elif fill:
            clients_stations.append((client, Station(orga)))

    return map(lambda x: (x[0].json, x[1].json), clients_stations)
예제 #26
0
def handle_station():
    """
    Trae lista de estaciones (GET) y agrega una estación (POST)
    """

    # POST request
    if request.method == 'POST':
        body = request.get_json()

        if body is None:
            raise APIException("You need to specify the request body as a json object", status_code=400)
        if 'name' not in body:
            raise APIException('You need to specify the name', status_code=400)
        if 'lattitude' not in body:
            raise APIException('You need to specify the lattitude', status_code=400)
        if 'longitude' not in body:
            raise APIException('You need to specify the longitude', status_code=400)
        if 'person_id' not in body:
            raise APIException('You need to specify the person_id', status_code=400)
        if 'organization_id' not in body:
            raise APIException('You need to specify the organization_id', status_code=400)
        if 'streetaddress' not in body:
            raise APIException('You need to specify the street address', status_code=400)
        if 'numberaddress' not in body:
            raise APIException('You need to specify the number address', status_code=400)

        station1 = Station(name=body['name'], lattitude=body['lattitude'], longitude=body['longitude'], person_id=body['person_id'], description=body['description'], organization_id=body['organization_id'], streetaddress=body['streetaddress'], numberaddress=body['numberaddress'])
        db.session.add(station1)
        db.session.commit()
        return "ok", 200

    # GET request
    if request.method == 'GET':
        all_stations = Station.query.all()
        all_stations = list(map(lambda x: x.serialize(), all_stations))
        return jsonify(all_stations), 200

    return "Invalid Method", 404
예제 #27
0
def stations_edit(request, id):
    """Edit a station."""

    object = None
    errors = []

    if id != '-':
        object = Station.query.filter_by(orga=int(request.args.get('ebuio_orgapk') or request.form.get('ebuio_orgapk')), id=int(id)).first()

    if request.method == 'POST':

        if not object:
            object = Station(int(request.form.get('ebuio_orgapk')))

        object.name = request.form.get('name')
        object.ip_allowed = request.form.get('ip_allowed')

        # Check errors
        if object.name == '':
            errors.append("Please set a name")

        # If no errors, save
        if not errors:
            
            if not object.id:
                object.gen_random_password()
                db.session.add(object)

            db.session.commit()

            return PlugItRedirect('stations/?saved=yes')

    if object:
        object = object.json
       
    return {'object': object, 'errors': errors}
예제 #28
0
def testdb_command():
    db.drop_all()
    db.create_all()

    block1 = Block(id=1,
                   number=1,
                   line="green",
                   length=100.0,
                   grade=0.5,
                   speedLimit=55,
                   elevation=0.5,
                   cumulative_elevation=0.5,
                   occupancy=False)
    db.session.add(block1)

    tcBlock1 = TrackControllerBlock(id=1,
                                    occupancy=False,
                                    maintenance=False,
                                    broken=False)
    db.session.add(tcBlock1)

    block2 = Block(id=2,
                   number=2,
                   line="green",
                   length=100.0,
                   grade=1.0,
                   speedLimit=55,
                   elevation=1.0,
                   cumulative_elevation=1.5,
                   occupancy=False)
    db.session.add(block2)

    tcBlock2 = TrackControllerBlock(id=2,
                                    occupancy=False,
                                    maintenance=False,
                                    broken=False)
    db.session.add(tcBlock2)

    block3 = Block(id=3,
                   number=3,
                   line="green",
                   length=100.0,
                   grade=1.5,
                   speedLimit=55,
                   elevation=1.5,
                   cumulative_elevation=3.0,
                   occupancy=False)
    db.session.add(block3)

    tcBlock3 = TrackControllerBlock(id=3,
                                    occupancy=False,
                                    maintenance=False,
                                    broken=False)
    db.session.add(tcBlock3)

    switch1 = Switch(id=1, state=False)
    db.session.add(switch1)
    block1.switch = switch1

    crossing1 = Crossing(id=1, state=False)
    db.session.add(crossing1)
    block3.crossing = crossing1

    station1 = Station(id=1, name="Station 1")
    db.session.add(station1)
    block2.station = station1

    light1 = Light(id=1, state=False)
    db.session.add(light1)
    light2 = Light(id=2, state=False)
    db.session.add(light1)

    switch1.lights.append(light1)
    switch1.lights.append(light2)

    # block1.message = "hello"

    train1 = Train(id=1,
                   name="train1",
                   length=1000.0,
                   width=100.0,
                   height=100.0,
                   mass=1000.0,
                   crewCount=0,
                   passengerCount=0)
    db.session.add(train1)
    train1.front_block = block1
    # block1.train_id = block1.front_train.id

    msg1 = Message(id=1, text="50,GO")
    db.session.add(msg1)
    msg1.block = block1
    msg1.train = train1

    msg2 = Message(id=2, text="100,GO")
    db.session.add(msg2)
    msg2.block = block2

    msg3 = Message(id=3, text="0,STOP")
    db.session.add(msg3)
    msg3.block = block3

    request = CTCRequest(id=0, type=0, input="")
    db.session.add(request)

    db.session.commit()

    # user1 = User(username='******', password='******')
    # db.session.add(user1)
    #
    # chatroom1 = ChatRoom(name='Super Awesome Chat Room')
    # db.session.add(chatroom1)
    #
    # user1.created_rooms.append(chatroom1)
    #
    # message1 = Message(creator=user1.username,text="Hello, there!", chatroom=chatroom1.name)
    # db.session.add(message1)
    # db.session.commit()

    print('Initialized the testing database.')
예제 #29
0
파일: data.py 프로젝트: xvzf/sanic-openapi
from models import Car, Driver, Garage, Manufacturer, Status, Station
import datetime

test_manufacturer = Manufacturer()
test_driver = Driver()
test_car = Car()
test_garage = Garage()
test_status = Status()
test_station = Station()

test_manufacturer = {
    'id': 1,
    'name': "Nissan",
    'start_date': datetime.date(year=1933, month=12, day=26)
}

test_driver = {
    'id': 1,
    'name': "Sanic",
    'birthday': datetime.date(year=2010, month=3, day=31)
}

test_car = {
    'id': 1,
    'on': False,
    'doors': 2,
    'color': 'black',
    'make': test_manufacturer,
    'passengers': [test_driver]
}
def range_hourly(station_id, year_start, year_end, month_start, month_end,
                 day_start, local_tz_name):
    """
    Calls Environment Canada endpoint and parses the returned XML into 
    StationData objects.
        
    Keyword arguments:
    station_id -- Integer corresponding to an Environment Canada station ID 
                  (ie. location of weather reading).
    year_start -- Integer indicating the year of the first weather history
                  request.
    year_end -- Integer indicating the year of the last weather history 
                request (inclusive). In combination with month_start and 
                month_end, all weather history between start and end times 
                will be requested.
    month_start -- Integer indicating the month of the first weather history 
                   request.
    month_end -- Integer indicating the month of the last weather history 
                 request (inclusive). In combination with year_start and 
                 year_end, all weather history between start and end times 
                 will be requested.
    day_start -- Integer indicating the starting day of the forecast, 
                 though multiple days of forecasted data will be returned.
    local_tz_name -- String representation of local timezone name 
                     (eg. 'America/Toronto').
                         
    Return:
    Two two-item vector [station, observations] where station is a 
    model.Station object and observations is a list of hourly 
    model.Observation objects.
    """
    # Instantiate objects that are returned by this method
    station = None
    observations = list()

    y = year_start
    m = month_start
    d = day_start
    req_date = datetime(y, m, d)
    end_date = datetime(year_end, month_end, day_start)
    while req_date <= end_date:
        xml_response = fetch_content(station_id=station_id,
                                     year_num=y,
                                     month_num=m,
                                     day_num_start=d,
                                     timeframe=1,
                                     frmt='xml')
        xml_string = xml_response.read().decode('utf-8')
        weather_root = ElementTree.fromstring(xml_string)

        # Only populate Station once
        if station == None:
            station = Station()
            station.station_id = station_id
            station.local_tz_str = local_tz_name
            station_local_tz = pytz.timezone(local_tz_name)
            epoch = datetime.utcfromtimestamp(0)
            offset_delta = station_local_tz.utcoffset(epoch)
            station_std_tz = timezone(offset_delta)
            for si_elmnt in weather_root.iter('stationinformation'):
                name_txt = si_elmnt.find('name').text
                if name_txt and name_txt != ' ':
                    station.name = name_txt

                province_txt = si_elmnt.find('province').text
                if province_txt and province_txt != ' ':
                    station.province = province_txt

                latitude_txt = si_elmnt.find('latitude').text
                if latitude_txt and latitude_txt != ' ':
                    station.latitude = float(latitude_txt)

                longitude_txt = si_elmnt.find('longitude').text
                if longitude_txt and longitude_txt != ' ':
                    station.longitude = float(longitude_txt)

                elevation_txt = si_elmnt.find('elevation').text
                if elevation_txt and elevation_txt != ' ':
                    station.elevation = float(elevation_txt)

                climate_id_txt = si_elmnt.find('climate_identifier').text
                if climate_id_txt and climate_id_txt != ' ':
                    station.climate_identifier = int(climate_id_txt)

        # Iterate stationdata XML elements and append Observations to list
        for sd_elmnt in weather_root.iter('stationdata'):
            observation = Observation()

            # Get portions of date_time for observation
            year_txt = sd_elmnt.attrib['year']
            month_txt = sd_elmnt.attrib['month']
            day_txt = sd_elmnt.attrib['day']
            hour_txt = sd_elmnt.attrib['hour']
            minute_txt = sd_elmnt.attrib['minute']
            if year_txt and month_txt and day_txt and hour_txt and minute_txt:
                observation.obs_datetime_std = datetime(year=int(year_txt),
                                                        month=int(month_txt),
                                                        day=int(day_txt),
                                                        hour=int(hour_txt),
                                                        minute=int(minute_txt),
                                                        second=0,
                                                        microsecond=0,
                                                        tzinfo=station_std_tz)
                observation.obs_datetime_dst = observation.obs_datetime_std.astimezone(
                    station_local_tz)

            if 'quality' in sd_elmnt.attrib:
                quality_txt = sd_elmnt.attrib['quality']
            else:
                quality_txt = None
            if quality_txt and quality_txt != ' ':
                observation.obs_quality = quality_txt

            # Set StationData fields based on child elements' values
            observation.station_id = station_id

            temp_txt = sd_elmnt.find('temp').text
            if temp_txt and temp_txt != ' ':
                observation.temp_c = float(temp_txt)

            dptemp_txt = sd_elmnt.find('dptemp').text
            if dptemp_txt and dptemp_txt != ' ':
                observation.dewpoint_temp_c = float(dptemp_txt)

            relhum_txt = sd_elmnt.find('relhum').text
            if relhum_txt and relhum_txt != ' ':
                observation.rel_humidity_pct = int(relhum_txt)

            winddir_txt = sd_elmnt.find('winddir').text
            if winddir_txt and winddir_txt != ' ':
                observation.wind_dir_deg = int(winddir_txt) * 10

            windspd_txt = sd_elmnt.find('windspd').text
            if windspd_txt and windspd_txt != ' ':
                observation.wind_speed_kph = int(windspd_txt)

            visibility_txt = sd_elmnt.find('visibility').text
            if visibility_txt and visibility_txt != ' ':
                observation.visibility_km = float(visibility_txt)

            stnpress_txt = sd_elmnt.find('stnpress').text
            if stnpress_txt and stnpress_txt != ' ':
                observation.station_pressure_kpa = float(stnpress_txt)

            humidex_txt = sd_elmnt.find('humidex').text
            if humidex_txt and humidex_txt != ' ':
                observation.humidex = float(humidex_txt)

            windchill_txt = sd_elmnt.find('windchill').text
            if windchill_txt and windchill_txt != ' ':
                observation.wind_chill = int(windchill_txt)

            observation.weather_desc = sd_elmnt.find('weather').text

            # Add StationData element to list
            observations.append(observation)

        # Increment year and month to populate date range
        if m < 12:
            m += 1
        else:
            y += 1
            m = 1
        req_date = datetime(y, m, d)

    # Return XML elements parsed into a list of StationData objects
    return [station, observations]