def test_init(self): ship = Ship('uid', Location(1, 2), 90, 8, 12) self.assertEqual('uid', ship.uid) self.assertEqual(Location(1, 2), ship.location) self.assertEqual(90, ship.orientation) self.assertEqual(8, ship.size) self.assertEqual(12, ship.speed)
def test_apply_action(self): ship = Ship('uid', Location(150, 100), 90, 8, 6) environment = Environment(300, 200, [ship]) action = Action(ship.uid, 0, True) environment.apply_action(action) self.assertEqual(Location(150, 94), ship.location) # moved up 6 (the ship's speed)
def test_apply_action_collide_with_ship(self): ship1 = Ship('1', Location(150, 100), 0, 8, 6) ship2 = Ship('2', Location(155, 100), 0, 8, 6) environment = Environment(300, 200, [ship1, ship2]) action = Action(ship1.uid, 0, True) with self.assertRaises(Exception): environment.apply_action(action)
def load_locations(): """Load data from locations.csv into locations table in db.""" # Delete all rows in table, so if we need to run this a second time, # we won't be trying to add duplicate users Location.query.delete() with open('seed_data/location.csv', 'r') as f: reader = csv.reader(f) location_list = list(reader) del location_list[0] # Read location list and insert data d = {} for row in location_list: location_id, district_id, state_name = row d[location_id] = [district_id, state_name] if district_id == '': loc = Location(location_id=location_id, district_id=None, state_name=state_name) else: loc = Location(location_id=location_id, district_id=district_id, state_name=state_name) # We need to add to the session or it won't ever be stored db.session.add(loc) # Once we're done, we should commit our work db.session.commit()
def test_init(self): ship1 = Ship('1', Location(1, 2), 90, 8, 6) ship2 = Ship('2', Location(1, 2), 90, 12, 4) environment = Environment(300, 200, [ship1, ship2]) self.assertEqual(300, environment.width) self.assertEqual(200, environment.height) self.assertEqual(2, len(environment.ships)) self.assertEqual(ship1, environment.ships[0]) self.assertEqual(ship2, environment.ships[1])
def test_to_dict(self): ship1 = Ship('1', Location(1, 2), 90, 8, 6) ship2 = Ship('2', Location(1, 2), 90, 12, 4) environment = Environment(300, 200, [ship1, ship2]) expected = { 'width': 300, 'height': 200, 'ships': [ship1.to_dict(), ship2.to_dict()] } self.assertEqual(expected, environment.to_dict())
def create_test_world(): world = add(World(name='Test World')) portal = add(Location(name='Portal', world=world)) plaza = add(Location(name='Plaza', world=world)) hotel = add(Location(name='Old Grand Hotel', world=world)) basement = add(Location(name='Hotel Basement', world=world)) add( Path( start=portal, destination=hotel, description= "YOU ARE IN THE HOTEL. THERE'S A DOOR TO THE BASEMENT IN FRONT OF YOU." )) add( Path( start=plaza, destination=hotel, description= "YOU ARE IN THE HOTEL. THERE'S A DOOR TO THE BASEMENT IN FRONT OF YOU." )) add( Path(start=hotel, destination=plaza, description="YOU ARE IN THE PLAZA, FACING THE HOTEL.")) add( Path( start=hotel, destination=basement, description= "YOU ARE IN THE BASEMENT. THERE ARE STAIRS UP TO THE HOTEL LOBBY BEHIND YOU." )) add( Path( start=basement, destination=hotel, description= "YOU ARE IN THE HOTEL LOBBY. THERE'S AN EXIT TO THE PLAZA IN FRONT OF YOU." )) add( Session(code='TestSession1', active=True, current_location=hotel, previous_location=portal)) db.session.commit()
def load_location(filename): for line in open(filename): line = line.rstrip().split(' (') # print(line[0]) loc_name = line[0] geolocator = Nominatim() input_loc = geolocator.geocode(loc_name) latlng = str(input_loc.latitude) + ',' + str(input_loc.longitude) # print(latlng) loc2 = geolocator.reverse(latlng, language="en") lat = loc2.raw['lat'] lng = loc2.raw['lon'] country = loc2.raw['address']['country'] state = loc2.raw['address']['state'] # city = loc2.raw['address']['city'] # zipcode = loc2.raw['address']['postcode'] # print(loc2, lat, lng, country, state) location = Location(lat=lat, lng=lng, loc_name=loc_name, country=country, state=state) db.session.add(location) print("Out of loop") db.session.commit() print("location db session commit")
def __find_zero_loc(self): self.list_location.clear() for r in range(len(self.__map)): for c in range(len(self.__map[r])): if self.__map[r][c] == 0 : loc = Location(r,c) self.list_location.append(loc)
def put_random_scan(): insert_time = utils.random_time() #Create the location map_id = maps.random_map_id() location = Location(map_id=map_id, x=utils.random_int(0, 300), y=utils.random_int(0, 600), timestamp=insert_time) location.put() #Base station base_mac = BASE_APS_MAC_ADDRESSES[utils.random_int( 0, len(BASE_APS_MAC_ADDRESSES) - 1)] base_station = base_stations.get_base_station_with_mac( utils.mac_string_to_int(base_mac)) #Create or update the client mac_int = utils.mac_string_to_int(CLIENT_MAC_ADDRESSES[utils.random_int( 0, len(CLIENT_MAC_ADDRESSES) - 1)]) client = clients.create_or_update_client(mac_int, base_station, insert_time) #Create the scan scan = Scan(map_key=map_id, client=client.key(), base_ap=base_station.key(), ss=utils.random_int(-90, -25), timestamp=insert_time, location=location) scan.put() logging.info(scan.key())
def load_locations(): """Look up city coordinates using Google Geocode API and write to database.""" with open('data/500cities.csv') as f: reader = csv.reader(f) for row in reader: city, state, companies_qty = row citystate = city + ', ' + state companies_qty = int(companies_qty) gmaps = googlemaps.Client( key='AIzaSyDhCeDrRa_Fs_gLbPUHp-UsHPKb53LIFlw') geocode_result = gmaps.geocode(citystate) lat = geocode_result[0]['geometry']['location']['lat'] lng = geocode_result[0]['geometry']['location']['lng'] location = Location(city=city, state=state, lat=lat, lng=lng, companies_qty=companies_qty) db.session.add(location) db.session.commit()
def create_location(plant_location): """Create a location type for plants.""" location = Location(plant_location=plant_location) db.session.add(location) db.session.commit() return location
def get_empty_location(self): position_zero = [] for i in range(len(self.__map)): for j in range(len(self.__map[0])): if self.__map[i][j] == 0: position_zero.append(Location(i, j)) return position_zero
def load_locations(): """Populates locations with loactions from ex.locations""" print("Locations") # Delete all rows in table, so if we need to run this a second time, # we won't be trying to add duplicate users #need to delete rating db also because it has forigen keys from users Found.query.delete() Lost.query.delete() Location.query.delete() # Read ex.Location file and insert data for row in open("example_data/ex.location"): row = row.rstrip() title, address1, address2, city, state, zipcode, lat, lng = row.split( "|") location = Location(title=title, address1=address1, address2=address2, city=city, state=state, zipcode=zipcode) # We need to add to the session or it won't ever be stored db.session.add(location) # Once we're done, we should commit our work db.session.commit()
def add_location(trip_id): """Gather location information about a trip.""" trip = Trip.query.get(trip_id) if request.method == "POST": user_id = session["user_id"] name = request.form["name"] address = request.form["address"] city = request.form["city"] state = request.form["state"] country = request.form["country"] location = Location(user_id=user_id, address=address, city=city, state=state, country=country, name=name) location.trips = [trip] # assoc table pop db.session.add(location) #if refactor with modelMixin, can do location.save db.session.commit() location_id = location.location_id return redirect(f"/user_journal/{user_id}") else: return render_template("create_location.html", trip_id=trip_id)
def __get_empty_location(self): # 每次统计空位置,都先清空之前的数据,避免影响本次数据. self.__list_empty_location.clear() for r in range(len(self.__map)): for c in range(len(self.__map[r])): if self.__map[r][c] == 0: self.__list_empty_location.append(Location(r, c))
def load_locations(): """Load locations from locations.csv into database.""" print "Locations" for row in open("seed_data/locations.csv"): row = row.rstrip().split(",") for i, element in enumerate(row): if element == "": row[i] = None id, name, city, state, country, latitude, longitude = row # TODO Make locations singular locations = Location( id=id, name=name, city=city, state=state, country=country, latitude=latitude, longitude=longitude, ) db.session.add(locations) db.session.commit()
def location_request(name): """Function that handles appending or fetching a location.""" print(request.form) if request.method == 'PUT': try: lat = float(request.form["latitude"]) lon = float(request.form["longitude"]) except: return "", 400 # <- Bad request db.session.add( Location( name=name, latitude=lat, longitude=lon, elevation=fetch_elevaion(((lat, lon), ))[0], )) db.session.commit() return jsonify({"message": "success"}), 201 if request.method == 'GET': d = db.session.query(Location).filter_by(name=name).first() if not d: return '{}', 204 return jsonify({ "name": d.name, "latitude": d.latitude, "longitude": d.longitude, "elevation": d.elevation, }), 200
def select_all_locations(self): expected_columns = [ 'id', 'address', 'city', 'state', 'zip_code', 'location' ] # self.validate_columns(*expected_columns) sql = ''' SELECT id, address, city, state FROM {} WHERE address IS NOT NULL AND city IS NOT NULL AND state IS NOT NULL AND ( location IS NULL OR zip_code IS NULL ) '''.format(self.locations_table) with self.connection.cursor() as cursor: try: cursor.execute(sql) return [Location(*(*row, None, None, None)) for row in cursor] except Exception as e: self.connection.close() raise e
def get_empty_location(self): self.list_empty_location.clear() for r in range(4): for c in range(4): if self.map[r][c] == 0: loc = Location(r, c) self.list_empty_location.append(loc)
def __calculate_empty_location(self): self.__list_empty_location.clear() for r in range(4): for c in range(4): if self.__map[r][c] == 0: loc = Location(r, c) self.__list_empty_location.append(loc)
def report_lost(): """adds new item to losts""" title = request.form.get('title') description = request.form.get('description') location = request.form.get('location') reward = request.form.get('reward') print(reward) if not reward or reward == 'undefined': reward = None geocoding_info = get_geocoding(location) location_id = get_location_id(geocoding_info['lat'], geocoding_info['lng']) if not location_id: new_location = Location(address1=geocoding_info['street'], city=geocoding_info['city'], zipcode=geocoding_info['zipcode'], state=geocoding_info['state'], lat=geocoding_info['lat'], lng=geocoding_info['lng']) db.session.add(new_location) # location_id = get_location_id(lat, lng) db.session.flush() location_id = new_location.location_id #add item to found database new_lost = Lost(title=title, description=description, location_id=location_id, user_id=session['user_id'], time=datetime.now(), reward=reward) db.session.add(new_lost) db.session.flush() new_lost_id = new_lost.lost_id #if an image was uploaded, store it in the database if 'file' in request.files: file = request.files['file'] img_name = 'l' + str(new_lost_id) + file.filename new_image = Image(img_name=img_name, img_data=file.read(), lost_id=new_lost_id) db.session.add(new_image) db.session.commit() return redirect('/lost')
def __calculate_empty_location(self): self.__list_empty_location.clear() for r in range(len(self.__map)): for c in range(len(self.__map[r])): if self.__map[r][c] == 0: # 记录r c # self.__list_empty_location.append((r, c)) self.__list_empty_location.append(Location(r, c))
def __get_empty_location(self): # 每次统计空位置,都先清空之前的数据,避免影响本次的数据 self.__list_empty_location.clear() # 获取所有空白位置 for row in range(len(self.__map)): for col in range(len(self.__map[row])): if self.__map[row][col] == 0: self.__list_empty_location.append(Location(row, col))
def __get_empty_location(self): # 每次统计空位置,都先清空之前的数据,避免影响本次数据. # (Each time when counting the empty position, the previous data need to be cleared first to avoid affecting the data) self.__list_empty_location.clear() for r in range(len(self.__map)): for c in range(len(self.__map[r])): if self.__map[r][c] == 0: self.__list_empty_location.append(Location(r, c))
def load_data(): """pull data from API and load into db""" page_num = 1 # if type(num) == int: # url = "https://refugerestrooms.org:443/api/v1/restrooms.json?page=1&per_page=" + str(page_num) # else: # pass while True: url = "https://www.refugerestrooms.org:443/api/v1/restrooms.json?per_page=100&page=" + str( page_num) results = [] response = requests.get(url) if response.status_code == 200: results = response.json() page_num += 1 # loop thru json data for v in results: # add bathroom and location b = Bathroom(name=v['name'], unisex=v['unisex'], accessible=v['accessible'], changing_table=v['changing_table']) db.session.add(b) db.session.commit() # add location if v['latitude'] == None or v['longitude'] == None: v['latitude'] = 0.00 v['longitude'] = 0.00 l = Location(bathroom_id=b.bathroom_id,street=v['street'], city=v['city'], state=v['state'], \ country=v['country'], latitude=v['latitude'], longitude=v['longitude'], directions=v['directions']) db.session.add(l) db.session.commit() # add comment if len(v['comment']) > 1: c = Comment(comment=v['comment'], bathroom_id=b.bathroom_id, user_id=0) db.session.add(c) db.session.commit() # add ratings if v['downvote'] == 1: r = Rating(bathroom_id=b.bathroom_id, user_id=0, score=2) db.session.add(r) db.session.commit() elif v['upvote'] == 1: r = Rating(bathroom_id=b.bathroom_id, user_id=0, score=5) db.session.add(r) db.session.commit() time.sleep(1) else: break return "finished loading data"
def create_location(location): """Create and return a new entry type""" new_location = Location(location=location) db.session.add(new_location) db.session.commit() return new_location
def search_location(self, location): try: latitude, longitude, name = get_geocode_location(location) if latitude is not None and longitude is not None: location = Location(name, latitude, longitude) self.add_result(location) return self.results except: # TODO: Handle more exceptions. pass return []
def __get_empty_location(self): """ 每次統計空位置,都先清空之前數據,避免影響本次數據 :return: """ self.__list_empty_location.clear() for r in range(len(self.__map)): for c in range(len(self.__map[r])): if self.__map[r][c] == 0: self.__list_empty_location.append(Location(r, c))
def __get_empty_location(self): # 避免每一次找空位置的时候都创建一个新的列表,把创建空列表写进init # 每一次寻找空位置前,先清空原列表 self.__list_empty_location.clear() for r in range(len(self.__map)): for c in range(len(self.__map[r])): if self.__map[r][c] == 0: # 把行号列号用对象封装好,放进列表 # 直接修改了实例变量(可以看做全局变量),不需要return了。 self.__list_empty_location.append(Location(r,c))