def index(location_id): # return "<h1><b>That's all for tonight folks</b></h1>Thanks for playing!<p><a href='mailto:[email protected]'>Contact the team</a> behind milkshake.fm</p>" l = Location.from_id(location_id) if not l: l = Location(name="whatever") l.save() return render_template('client.html')
def __init__(self,N_mazeSize, x,y, ith, SURFdict): #self.placeCells = np.zeros((1+4*N_mazeSize)) loc=Location() loc.setXY(x,y) #placeId = loc.placeId #self.placeCells[placeId] = 1 self.grids = loc.getGrids().copy() self.hd = np.array([0,0,0,0]) self.hd[ith]=1 self.rgb=np.array([0,0,0]) #assume a red poster in the east and a green poster in the north if ith==0: #NB these differ from head direction cells, as HD odometry can go wrong! self.rgb[0]=1 if ith==1: self.rgb[1]=1 if SURFdict is not None: #HOOK ALAN - include SURF features in the senses of the dictionary #Problem with merging here is you can only have one image per direction? self.surfs=findSurfs(x,y,ith,SURFdict) else: self.surfs=np.array([]) #print("Surf feature for %d,%d,%d:\n%s" % (x,y,ith,self.surfs)) #x,y relate to surf features in SURFdict self.whiskers=np.array([0,0,0]) #to be filled in outside
def walkTo(self, olatitude, olongitude, epsilon=10, step=7.5): if step >= epsilon: raise Exception("Walk may never converge") # Calculate distance to position latitude, longitude, _ = self.getCoordinates() dist = closest = Location.getDistance( latitude, longitude, olatitude, olongitude ) # Run walk divisions = closest / step dLat = (latitude - olatitude) / divisions dLon = (longitude - olongitude) / divisions while dist > epsilon: logging.info("%f m -> %f m away", closest - dist, closest) latitude -= dLat longitude -= dLon self.setCoordinates( latitude, longitude ) time.sleep(1) dist = Location.getDistance( latitude, longitude, olatitude, olongitude )
def __init__(self, config): Location.__init__(self, config) self.victory_chance = config['victory_chance'] self.reward = config['reward'] self.exp_reward = config['exp_reward'] self.penalty = config['penalty'] self.drop_object = config['drop_object']
def walkTo(self, olatitude, olongitude, epsilon=10, step=7.5): if step >= epsilon: raise GeneralPogoException("Walk may never converge") # Calculate distance to position latitude, longitude, _ = self.getCoordinates() dist = closest = Location.getDistance( latitude, longitude, olatitude, olongitude ) # Run walk divisions = closest / step dLat = (latitude - olatitude) / divisions dLon = (longitude - olongitude) / divisions logging.info("Walking %f meters. This will take %f seconds..." % (dist, dist / step)) while dist > epsilon: logging.debug("%f m -> %f m away", closest - dist, closest) latitude -= dLat longitude -= dLon self.setCoordinates( latitude, longitude ) time.sleep(1) dist = Location.getDistance( latitude, longitude, olatitude, olongitude )
def pack(self, items, fill_limit): locations = [] other = Location(-1) for x in range(0, self._location_count): locations.append(Location(x)) items = sorted(items, key=attrgetter('weight'), reverse=True) items = sorted(items, key=attrgetter('value'), reverse=True) for item in items: stored = False locations = sorted(locations, key=attrgetter('weight')) for idx, location in enumerate(locations): if location.weight < fill_limit and item.weight <= (fill_limit - location.weight): location.add_item(item) stored = True break if not stored: other.add_item(item) return (locations, other)
def walkTo(self, olatitude, olongitude, speed): # speed in m/s # Calculate distance to position latitude, longitude, _ = self.getCoordinates() dist = Location.getDistance( latitude, longitude, olatitude, olongitude ) # don't divide by zero, bad stuff happens if dist == 0: return divisions = dist/speed dlat = (latitude - olatitude)/divisions dlon = (longitude - olongitude)/divisions logging.info("(TRAVEL)\t-\tWalking "+str(dist)+"m at "+str(speed)+"m/s, will take approx "+str(divisions)+"s") while dist > speed: latitude-=dlat longitude-=dlon self.setCoordinates(latitude, longitude) time.sleep(1) dist = Location.getDistance(latitude, longitude, olatitude, olongitude) #final move self.setCoordinates(olatitude, olongitude)
def post(self): locnick=self.request.get('nick') if not locnick: return self.error("Parameter 'nick' missing") loc=Location(nick=locnick) loc.position=self.request.get('position') loc.put() return self.success()
def __init__(self, ec, dictGrids, dghelper=None, N_place_cells=13): self.N_place_cells=N_place_cells self.dghelper = dghelper #HOOK:, needs to use EC data to define "combis" of features aswell if dghelper is not None: #Lets say for now that place whisker combos etc are all encoded normally, and SURF features are encoded using WTA DG. In the end we may make sure that we have blocks referring only to location, blocks refering only to whiskers, blocks refering only to light, etc. #FIXME: This needs changing when integrated to just get the number of surf features from ec! if unittesting: #Slice the SURF features from the numpy array self.numOfSurfFeatures = len(ec) self.surfFeatures = ec[-self.numOfSurfFeatures:] else: self.numOfSurfFeatures = len(ec.surfs) self.surfFeatures = ec.surfs #Choose semantics by choosing X random features N times to make N blocks #For now be stupid, allow the same combinations to come up and the same indices to be compared with each other for winner take all (will the conflict break it?) #Make this more intelligent later #Make random windows associated with the features, i.e. for N windows, choose X random features to encode, make a matrix with the blocks and values # <---X---> # +-------------+ # ^ | 0 0 0 0 1 0 | # | | 1 0 0 0 0 0 | # N | | # | | | # | | | # +-------------+ self.semanticValues = dghelper.getSemanticValues(self.surfFeatures) #These are our input activations, once passed through a neural network with competitive learning applied to its ECDGweights to encourage winner takes all, the output should only have 1 active value per block (row), thus is sparse #What happens if none of the features are active?? Should the one with the highest weight win? Or should there just be no activation in that block making it a even sparser matrix? I suspect the latter! self.encode() if not unittesting: if dghelper is None: self.encodedValues = np.array([]) #TODO: Need to remove place cells.... #self.N_place_cells = 13 # N_hd = 4 loc=Location() #NEW, pure place cells in DG loc.setGrids(ec.grids, dictGrids) self.place=np.zeros(self.N_place_cells) self.place[loc.placeId] = 1 self.hd_lightAhead = np.zeros(4) if ec.lightAhead == 1: self.hd_lightAhead = ec.hd.copy() self.whisker_combis = np.zeros(3) #extract multi-whisker features. self.whisker_combis[0] = ec.whiskers[0] * ec.whiskers[1] * ec.whiskers[2] #all on self.whisker_combis[1] = (1-ec.whiskers[0]) * (1-ec.whiskers[1]) * (1-ec.whiskers[2]) #none on self.whisker_combis[2] = ec.whiskers[0] * (1-ec.whiskers[1]) * ec.whiskers[2] # both LR walls but no front
def test_location_on_obstacle(self): grid = Grid(3, 3) grid.place_obstacle(0, 1) location = Location(grid, 0, 0, direction.N) self.assertFalse(location.is_on_obstacle()) next_location = location.next_location(command.F) self.assertTrue(next_location.is_on_obstacle())
def __init__(self, map_name, name): xml = doc.xpath('//map[@name="%s"]/door[@name="%s"]' % (map_name, name))[0] #~ print etree.tostring(xml) Location.__init__(self, map_name, xml.get('loc')) #~ Location.__init__(self, map_name, doc.xpath('//map[@name="%s"]/door[@name="%s"]' % (map_name, name))[0].get('loc')) self.door_name = name if not xml.get('target'): raise Exception("door without target: %s" % etree.tostring(xml)) self.target = xml.get('target')
def test_next_location3(): loc = Location(2, 2, 3) loc_x, loc_y, x, y = loc.next_location("down", 10, loc.size + 1) assert loc_y == 0 assert loc_x == 2 loc_x, loc_y, x, y = loc.next_location("right", loc.size + 1, 10) assert loc_x == 0 assert loc_y == 2
def test_next_location2(): loc = Location(0, 0, 3) loc_x, loc_y, x, y = loc.next_location("up", 10, -1) assert loc_y == 2 assert loc_x == 0 loc_x, loc_y, x, y = loc.next_location("left", -1, 10) assert loc_x == 2 assert loc_y == 0
def testMumbai(self): lc = Location() mumbai_cord = lc.getCoordinates(query="Mumbai") mumbai_expected = Coordinates(lat=19.017587, lng=72.856248, state="Maharashtra", sub_district="Mumbai", district="Mumbai", level="Town", name="MUMBAI") self.assertTrue((float(mumbai_cord.lat) - float(mumbai_expected.lat)) < 0.00001, "Latitude didnot Match for Mumbai") self.assertTrue((float(mumbai_cord.lng) - float(mumbai_expected.lng))< 0.00001, "Longitude didnot Match for Mumbai") self.assertEqual(mumbai_cord.state, mumbai_expected.state, "States didnot Match for Mumbai") self.assertEqual(mumbai_cord.district, mumbai_expected.district, "District didnot Match for Mumbai") self.assertEqual(mumbai_cord.sub_district, mumbai_expected.sub_district, "SUB District didnot Match for Mumbai") self.assertEqual(mumbai_cord.level, mumbai_expected.level, "Levels didnot Match for Mumbai")
def walkToAndCatch(session,olatitude, olongitude, epsilon=10, step=4): logging.debug("Calculate distance to destination(%f,%f) - %im/s", olatitude, olatitude, step) latitude, longitude, _ = session.getCoordinates() dist = Location.getDistance( latitude, longitude, olatitude, olongitude ) divisions = dist / step if (divisions == 0): session.setCoordinates( olatitude, olongitude ) logging.debug("Current location(%f,%f) - %im to destination", latitude, longitude, int(dist)) return dLat = (latitude - olatitude) / divisions dLon = (longitude - olongitude) / divisions logging.info("(%f,%f) -> (%f,%f) : %im in %i s", latitude, longitude, olatitude, olongitude, int(dist), int(dist / step) + 1) logging.debug("Start Walk") while dist > epsilon: if dist < step: session.setCoordinates( olatitude, olongitude ) logging.debug("Current location(%f,%f) - %im to destination", latitude, longitude, int(dist)) break latitude -= dLat longitude -= dLon session.setCoordinates( latitude, longitude ) dist = Location.getDistance( latitude, longitude, olatitude, olongitude ) logging.debug("Current location(%f,%f) - %im to destination", latitude, longitude, int(dist)) catchAllPokemon(session) time.sleep(1) # 1 sec
def test_next_location(self): grid = Grid(3, 3) location = Location(grid, 0, 0, direction.N) next_location = location.next_location(command.F) self.assert_location(Location(grid, 0, 1, direction.N), next_location) next_location = next_location.next_location(command.R) self.assert_location(Location(grid, 0, 1, direction.E), next_location) next_location = next_location.next_location(command.F) self.assert_location(Location(grid, 1, 1, direction.E), next_location)
def test_next_location_wrapped(self): grid = Grid(3, 3) location = Location(grid, 0, 0, direction.W) next_location = location.next_location(command.F) self.assert_location(Location(grid, 2, 0, direction.W), next_location) next_location = next_location.next_location(command.L) self.assert_location(Location(grid, 2, 0, direction.S), next_location) next_location = next_location.next_location(command.F) self.assert_location(Location(grid, 2, 2, direction.S), next_location)
def walkTo(self, olatitude, olongitude, epsilon=10, step=7.5, delay=10): if step >= epsilon: raise GeneralPogoException("Walk may never converge") if self.location.noop: raise GeneralPogoException("Location not set") # Calculate distance to position latitude, longitude, _ = self.getCoordinates() dist = closest = Location.getDistance( latitude, longitude, olatitude, olongitude ) # Run walk divisions = closest / step dLat = (latitude - olatitude) / divisions dLon = (longitude - olongitude) / divisions logging.info("Walking %f meters. This will take ~%f seconds..." % (dist, dist / step)) steps = 1 while dist > epsilon: logging.debug("%f m -> %f m away", closest - dist, closest) latitude -= dLat longitude -= dLon steps %= delay if steps == 0: self.setCoordinates( latitude, longitude ) time.sleep(1) dist = Location.getDistance( latitude, longitude, olatitude, olongitude ) steps += 1 # Finalize walk steps -= 1 if steps % delay > 0: time.sleep(delay - steps) self.setCoordinates( latitude, longitude )
def updateGrids(self, ca1grids, ca1hd, b_odom, N_mazeSize, dictGrids): loc=Location() loc.setGrids(ca1grids, dictGrids) (x_hat_prev, y_hat_prev) = loc.getXY() ## Hard coded again here North negative..... dxys = [[1,0],[0,1],[-1,0],[0,-1]] #by hd cell ihd = argmax(ca1hd) odom_dir = dxys[ihd] odom = [0,0] if b_odom: odom=odom_dir x_hat_now = x_hat_prev + odom[0] y_hat_now = y_hat_prev + odom[1] ##SMART UPDATE -- if odom took us outside the maze, then ignore it #pdb.set_trace() ##if this takes me to somewhere not having a '3'(=N_mazeSize) in the coordinate, then the move was illegal? if sum( (x_hat_now==N_mazeSize) + (y_hat_now==N_mazeSize))==0: print "OFFMAZE FIX: OLD:" ,x_hat_now, y_hat_now x_hat_now = x_hat_prev y_hat_now = y_hat_prev print "NEW:",x_hat_now, y_hat_now x_hat_now = crop(x_hat_now, 0, 2*N_mazeSize) y_hat_now = crop(y_hat_now, 0, 2*N_mazeSize) #restrict to locations in the maze loc=Location() loc.setXY(x_hat_now, y_hat_now) #self.placeCells=zeros(ca1placeCells.shape) #self.placeCells[loc.placeId] = 1 self.grids = loc.getGrids().copy()
def main(): edf = EnergyDataFile('EnergyReportingtest.csv') #edf.read_CSV(header=True) edf.read_CSVDictTest() edf.print_Header() #edf.getDict() loc = Location("City Hall") loc.setAccount("123456789", "11111") #loc.setAccount("555555555", "55555") #loc.setAccount("123456789", "22222") #loc.setAccount("987654321", "33333") #loc.setAccount("987654321", "33333") loc.printLoc() print edf.__type__
def init_locations_from_file(): """ Initialize world from location json file. """ global WORLD with open("locations.json", "r") as json_file: data = json.load(json_file) for loc in data: new_loc = Location(loc["id"], loc["name"]) new_loc.description = loc["description"] new_loc.has_enemy = loc["enemy"] new_loc.has_npc = loc["npc"] new_loc.has_investigate = loc["investigate"] new_loc.north = loc["north"] new_loc.east = loc["east"] new_loc.south = loc["south"] new_loc.west = loc["west"] WORLD[new_loc.id] = new_loc
def get_bot(data): pos = get_location_from_string(data['BotLocation']) location = Location(pos[0], pos[1]) isMissileAvailable = bool(data['MissileAvailableIn']) bot = Bot(location, isMissileAvailable) bot.print_debug() return bot
def create(cls, level, loc_string): location = Location.from_string(loc_string) if location: return cls(level = level, loc_building = location.building, loc_floor = location.floor, loc_room = location.room)
def position(self): geographic_loc = self._sat.at(self._ts.now()).subpoint() pos = Location(geographic_loc.longitude.degrees,geographic_loc.latitude.degrees, geographic_loc.elevation.m) LOGGER.debug("Station ["+self.name+"] is at "+str(pos)) return pos
def GetLocation(self, location_id): connection = getConnection() cursor = connection.cursor() query = """ SELECT location_id,user_id,lat,long,photo,video,document FROM EVENTTABLE WHERE location_id= %s;""" try: cursor.execute(query, (location_id)) fetched_data = cursor.fetchone() connection.commit() if fetched_data is None: status = 'Invalid or no location data' connection.close() return None else: location_id = fetched_data[0] lat = fetched_data[1] long = fetched_data[2] photo = fetched_data[3] video = fetched_data[4] document = fetched_data[5] location = Location(location_id, lat, long, photo, video, document) except connection.Error as error: print(error) connection.close() return location
def __init__(self, location_string, segmentor='baseline', dataset='train'): self.segmentor = segmentor self.location = Location(location_string) self.dataset = dataset print(self.location.training_data_path) print(self.segmentor) print(self.dataset)
def test_dauphine_post_2010(self): france = country.France() valence = Location("Valence", france) prologue = Prologue(datetime(2018, 6, 3), valence, valence, 6.6) dauphine = Dauphine() dauphine.add_stage(prologue) assert dauphine.name == "Critérium du Dauphiné"
def test_getitem(self): map_ = [".#.", "##.", ".#."] labyrinth = Labyrinth(map_) wall = LabyrinthObject(True) empty = LabyrinthObject(False) for x in range(3): for y in range(3): current = labyrinth[Location(x, y)] if y == 1 or x == 1 and y == 0: self.assertEqual(current, wall) else: self.assertEqual(current, empty) self.assertRaises(TypeError, labyrinth.__getitem__, 1) self.assertRaises(IndexError, labyrinth.__getitem__, Location(-1, 1))
def find(image_name, precision=None, in_region=None): """Look for a single match of a Pattern or image :param image_name: String or Pattern :param precision: Matching similarity :param in_region: Region object in order to minimize the area :return: Location """ if isinstance(image_name, str) and is_ocr_text(image_name): a_match = text_search_by(image_name, True, in_region) if a_match is not None: return Location(a_match['x'] + a_match['width'] / 2, a_match['y'] + a_match['height'] / 2) else: raise FindError('Unable to find text %s' % image_name) elif isinstance(image_name, str) or isinstance(image_name, Pattern): if precision is None: precision = Settings.MinSimilarity try: pattern = Pattern(image_name) except Exception: pattern = image_name image_found = image_search(pattern, precision, in_region) if (image_found.x != -1) & (image_found.y != -1): return image_found else: raise FindError('Unable to find image %s' % image_name) else: raise ValueError(INVALID_GENERIC_INPUT)
def test_getitem(self): map_ = ["#.", "#."] wall = LabyrinthObject(True) empty = LabyrinthObject(False) labyrinth = Labyrinth3d([map_, map_]) self.assertRaises(TypeError, labyrinth.__getitem__, 1) self.assertRaises(IndexError, labyrinth.__getitem__, Location(-1, 1, 0)) for x in range(2): for y in range(2): for z in range(2): location = Location(x, y, z) if y == 0: self.assertEqual(wall, labyrinth[location]) else: self.assertEqual(empty, labyrinth[location])
def load_locations(self): """ Reads in the string data from the csv file. Loads each location as a point in the graph class. :return:None """ with open('WGUPS_Distance_Table.csv') as csv_file: csv_reader = csv.reader(csv_file) line_count = 0 distances = list() self.destinations.add_location(self.center) distances.append([ '0', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '' ]) for row in csv_reader: line_count += 1 if line_count < 4: continue address = row[0].split("\n") label = row[1].split("\n") zip_code = int(label[1].strip("(").strip(")")) location = Location(address[0], address[1], zip_code, label[0].strip(" ")) self.destinations.add_location(location) distances.append(row[2:-1]) self.load_distances(distances)
def newLocation(): if request.method == 'GET': form = { 'lat': '', 'long': '', 'photo': '', 'video': '', 'document': '' } locations = current_app.savelocation.GetLocations() return render_template('locationAdd.html', locations=locations, form=form) else: lonT = request.form['long'] latT = request.form['lat'] phoT = request.form['photo'] vidT = request.form['video'] docT = request.form['document'] locT = Location(long=lonT, lat=latT, photo=phoT, video=vidT, document=docT) current_app.savelocation.AddLocation(locT) locations = current_app.savelocation.GetLocations() form = { 'long': '', 'lat': '', 'photo': '', 'video': '', 'document': '' } return render_template('map.html', locations=locations, form=form)
def createLocation(self, locationName, serviceType, viewOption, dataOption): location = Location(locationName, serviceType, viewOption, dataOption, self) if not self.exists(location): self.add(location) return location #return location to the controller so that we can use it to make a monitor else: return None
def __init__(self, *args, **kwargs): super(ParentStatement, self).__init__() self.description = "" self.before_stmt = {} self.next_stmt = {} self.begin_stmt = None self.end_stmt = None self.dom_next_stmt = set() self.dom_parent_stmt = None self.post_dom_next_stmt = set() self.post_dom_parent_stmt = None self._is_condition = False self.method_obj = None self.name = "" self.location = Location(None) self.result_has_from_recursive = None self.order_id = -1 self.operator_variable = None self.stmt_child = [] self.control = control.ControlDependency(self)
def _click_at(location=None, clicks=None, duration=None, button=None): """Click on Location coordinates. :param location: Location , image name or Pattern. :param clicks: Number of mouse clicks. :param duration: Speed of hovering from current location to target. :param button: Mouse button clicked (can be left, right, middle, 1, 2, 3). :return: None. """ if duration is None: duration = Settings.move_mouse_delay if location is None: location = Location(0, 0) pyautogui.moveTo(location.x, location.y, duration) if parse_args().highlight: hl = ScreenHighlight() hl.draw_circle(HighlightCircle(location.x, location.y, 15)) hl.render() if clicks > 1: mouse = Controller() mouse.position = (location.x, location.y) mouse.click(Button.left, 2) else: pyautogui.click(clicks=clicks, interval=Settings.click_delay, button=button) if Settings.click_delay != DEFAULT_CLICK_DELAY: Settings.click_delay = DEFAULT_CLICK_DELAY
def save_product_for_sale(cls, data, user_id): p = Product() p.us_id = user_id p.name = data.get('title', '-') p.cat_id = data.get('category') p.subcat_id = data.get('subcategory') p.subcat2_id = data.get('subcategory2') or None p.kind = data.get('bargain_type') p.loc_id = data.get('city') p.bargain_type = data.get('bargain_type') p.price = data.get('price') p.availability = data.get('availability_type') p.shipping_method = data.get('shipping_type') p.description = data.get('description') p.quantity = int(data.get('quantity')) p.set_end_date(data.get('end_date')) p.specifics = [int(x) for x in data.get('specifics', [])] p.quantity_measure = data.get('quantity_measure', 'P') if p.loc_id: city = Location.get(p.loc_id) if city: p.localisation = "%s, %s, Polska" % ( city.name, city.wojewodztwo.name.lower()) DBSession.add(p) DBSession.flush() return p
def _general_click(where=None, clicks=None, duration=None, in_region=None, button=None): """General Mouse Click. :param where: Location , image name or Pattern. :param clicks: Number of mouse clicks. :param duration: Speed of hovering from current location to target. :param in_region: Region object in order to minimize the area. :param button: Mouse button clicked (can be left, right, middle, 1, 2, 3). :return: None. """ if duration is None: duration = Settings.move_mouse_delay if isinstance(where, Pattern): _click_pattern(where, clicks, duration, in_region, button) elif isinstance(where, str): ocr_search = OCRSearch() a_match = ocr_search.text_search_by(where, True, in_region) if a_match is not None: click_location = Location(a_match['x'] + a_match['width'] / 2, a_match['y'] + a_match['height'] / 2) _click_at(click_location, clicks, duration, button) elif isinstance(where, Location): _click_at(where, clicks, duration, button) else: raise ValueError(INVALID_GENERIC_INPUT)
def is_regular_three(x, y): ''' Returns true if x, y are behind the regular (non-corner) 3-point line. ''' loc = Location(x, y, 0.0) return (min(get_distance(loc, HOOP1), get_distance(loc, HOOP2)) >= 23.75)
def findClosestPokemon(session): # Get Map details and print pokemon logging.info("Printing Nearby Pokemon:") cells = session.getMapObjects() closest = float("Inf") pokemonBest = None latitude, longitude, _ = session.getCoordinates() for cell in cells.map_cells: for pokemon in cell.wild_pokemons: # Log the pokemon found logging.info("%i at %f,%f" % ( pokemon.pokemon_data.pokemon_id, pokemon.latitude, pokemon.longitude )) # Fins distance to pokemon dist = Location.getDistance( latitude, longitude, pokemon.latitude, pokemon.longitude ) # Greedy for closest if dist < closest: pokemonBest = pokemon return pokemonBest
def parse_map(filename): # initialize location dictionary {ID -> Location} and road dictionary {ID -> list[Road]} locationDict = {} roadDict = {} # parse file with open(filename, "r") as file: for line in file: # remove \n and split line by delimiter line = line.rstrip() splitLine = line.split("|") # create new Location instances for "location" lines and add them to locationDict if splitLine[0] == "location": newLocation = Location(splitLine[1], splitLine[2], splitLine[3]) locationDict[splitLine[1]] = newLocation # create new Road instances for "road" lines and add them to roadDict elif splitLine[0] == "road": newRoad = Road(splitLine[4], splitLine[3], splitLine[1], splitLine[2]) if splitLine[1] in roadDict.keys(): roadDict[splitLine[1]] += [newRoad] else: roadDict[splitLine[1]] = [newRoad] if splitLine[2] in roadDict.keys(): roadDict[splitLine[2]] += [newRoad] else: roadDict[splitLine[2]] = [newRoad] file.close() return locationDict, roadDict
def add_location(self, coords): """ adds a location to the Realm """ key = tuple(coords) # check for existence of loot to add to this location per LOOT_LIST if key in self.LOOT_LIST: loot = self.LOOT_LIST[key] loot_present = True else: loot = [] loot_present = False # check for existence of monsters to add to this location per MONSTER_LIST if key in self.MONSTER_LIST: monster_list = self.get__master_monster_list() monsters = monster_list[key] monsters_present = True else: monsters = [] monsters_present = False # create new instance of Location and add it to the list of instances, then set it to the player's current location new_location = Location(coords, monsters_present, loot_present, monsters, loot) self.add_to_locations(new_location) self.current_player_location = new_location
def renderBoard(food: Food, snake: Snake): batch = pyglet.graphics.Batch() darkSquareColor = [12, 16, 21] lightSquareColor = [48, 59, 71] foodColor = [189, 30, 46] snakeColor = [35, 158, 235] if snake.isAlive() else [151, 50, 168] for i in range(BOARD_SIZE): for j in range(BOARD_SIZE): vertexList = ('v2i', createQuadVertexList(i * BLOCK_SIZE, j * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)) if snake.isSnakeBlock(Location(i, j)): batch.add(4, pyglet.gl.GL_QUADS, None, vertexList, ('c3B', snakeColor * 4)) elif i == food.getX() and j == food.getY(): batch.add(4, pyglet.gl.GL_QUADS, None, vertexList, ('c3B', foodColor * 4)) elif (i + j) % 2 == 0: batch.add(4, pyglet.gl.GL_QUADS, None, vertexList, ('c3B', darkSquareColor * 4)) else: batch.add(4, pyglet.gl.GL_QUADS, None, vertexList, ('c3B', lightSquareColor * 4)) batch.draw()
def get_direction(self, owner): if self.unit_in_loc is None: return None unit_direction = self.unit_in_loc.get_direction() start_node_direction = self.get_node_direction(unit_direction, owner) end_node_direction = self.get_node_direction( Location.reverse_direction(unit_direction), owner) dir_options = [] if unit_direction is not None: dir_options.append(unit_direction) if start_node_direction is not None: dir_options.append(start_node_direction) if end_node_direction is not None: dir_options.append(end_node_direction) if len(dir_options) <= 0: return None elif len(dir_options) == 1: return dir_options[0] elif len(dir_options) == 2: if dir_options[0] == unit_direction: return dir_options[1] return dir_options[0] else: if dir_options[0] == dir_options[1]: return dir_options[0] elif dir_options[0] == dir_options[2]: return dir_options[0] elif dir_options[1] == dir_options[2]: return dir_options[1] else: return start_node_direction
def test_bomb_hard(self): map_ = ["........", "###..#..", "#.######", "...##..#", ".#...#..", "........"] labyrinth = Labyrinth3d([map_]) info = solve(labyrinth, Location(0, 0), Location(5, 0), 10) expected = ["XX......", "#B#..#..", "#X######", "XX.##..#", "X#...#..", "X......."] self.assertEqual(find_path(labyrinth, info), expected)
def get_location_data_objects(self, payload): """Convert the JSON payload into a location object. Return that object. """ for i in range(0, len(payload)): location = Location(payload) return location
def test_rover_can_move_and_turn_batch(self): grid = Grid(3, 3) location = Location(grid, 0, 0, direction.N) rover = Rover(location) rover.move(command.to_commands('ffrff')) self.assert_location(rover.location, 2, 2, direction.E)
def main(): player = Entity("Anu", 0) location = Location("Nirn") clock = 0 distance = 0 speedBase = 1.5 play = True while play == True: clockUpdate(clock) print("\n") print("Time: %i\nLocation: %i\nresource_a: %i" % (clock, player.location, player.resource_a)) choice = input("\nchoices: \n%s\n%s\n%s\n" % ("1- scene", "2- march", "3- pace")) #list choices time.sleep(.1) if choice == "1": describeScene(clock, location) #input() elif choice == "2": # Change to Action menu? clock += 1 march(player, int(input("How fast? ")), 1, clock) elif choice == "quit": quit() else: print("ivalid input")
class Voter: def __init__(self, simulation): self.location = Location() self.simulation = simulation def update_vote(self): parties = self.simulation.get_parties() smallest_distance = 2 party_index = -1 i = 0 for p in parties: distance = self.location.distance(p.location) if distance < smallest_distance: smallest_distance = distance party_index = i i += 1 closest_party = parties[party_index] self.vote = closest_party self.vote.add_voter(self) def get_vote(self): return self.vote def get_location(self): return self.location
def test_one_task_one_user_assign(self): start_a = datetime.datetime(2000, 1, 1, 6, 0, 0) end_a = datetime.datetime(2000, 1, 1, 22, 0, 0) availability = [Availability(Duration(start_a, end_a))] category = Category(1, 'TestCategory') preferences = [Preference(category, 0, True)] groups = [Group(1, 'Employee')] generic = CommonTestFunctions() staff_member = StaffMember(1, 'TestMember', 0, 40, 80, 10, availability, preferences, groups) start_t = datetime.datetime(2000, 1, 1, 9, 0, 0) end_t = datetime.datetime(2000, 1, 1, 16, 0, 0) task_time = Duration(start_t, end_t) location = Location(1, 'TestLocation') task = Task(1, 'TestTask', task_time, 1, groups[0], location, category) staff_members = [staff_member] roles = [] tasks = [task] settings = generic.settings(40, True) generator = ScheduleGenerator(staff_members, roles, tasks) generator.schedule(settings) self.assertTrue(staff_member.has_task(task)) self.assertFalse(generator.has_unassigned_tasks())
def AddLocationAndItem(self, location: Location, item: Item) -> None: if item in [ Item.MAP, Item.COMPASS, Item.KEY, Item.BOMBS, Item.FIVE_RUPEES, Item.NOTHING ]: return level_or_cave_num = location.GetLevelOrCaveNum() self.per_level_item_location_lists[level_or_cave_num].append(location) self.loc_counter += 1 #TODO: This would be more elgant with a dict lookup if self.settings.progressive_items: if item == Item.RED_CANDLE: item = Item.BLUE_CANDLE elif item == Item.RED_RING: item = Item.BLUE_RING elif item == Item.SILVER_ARROWS: item = Item.WOOD_ARROWS elif item == Item.WHITE_SWORD: item = Item.WOOD_SWORD elif item == Item.MAGICAL_SWORD: item = Item.WOOD_SWORD elif item == Item.MAGICAL_BOOMERANG: item = Item.BOOMERANG if item == Item.TRIFORCE: print("Not adding Triforce") else: print("Adding item %s" % item) self.item_num_list.append(item) self.item_counter += 1 num_locations = 0 print("Num items/locations: %d/%d" % (self.item_counter, self.loc_counter))
class Visit(object): ''' (String(hh:mm)) start (String(hh:mm)) end (Number (minutes)) duration (Number (any unit)) load (String or Array) type ''' def __init__(self,lat,lng,name=None,start=None,end=None,duration=None,load=None,type=None): # TODO: Type check parameters self.location = Location(lat,lng,name) self.start = start self.end = end self.duration = duration self.load = load self.type = type ''' Serialize object to dictionary ''' def toDict(self): visit = {} if self.location: visit["location"] = self.location.toDict() if self.start: visit["start"] = self.start if self.end: visit["end"] = self.end if self.duration: visit["duration"] = self.duration if self.load: visit["load"] = self.load if self.type: visit["type"] = self.type return visit def toJson(self): return json.dumps(self.toDict())
def __init__(self): QtWidgets.QMainWindow.__init__(self) self.setupUi(self) self.database = Database() self.tles = self.database.get_tles() self.fill_satellite_list() self.fill_location_list() self.tbTle.setText("https://www.celestrak.com/NORAD/elements/noaa.txt") self.btnLoadTle.clicked.connect(self.load_tles) self.btnPredict.clicked.connect(self.predict) self.btnAddLocation.clicked.connect(self.open_location_chooser) self.location_chooser = Location(self.database, self)
def findAll(what, precision=None, in_region=None): """Look for multiple matches of a Pattern or image :param what: String or Pattern :param precision: Matching similarity :param in_region: Region object in order to minimize the area :return: """ if isinstance(what, str) and is_ocr_text(what): all_matches = text_search_by(what, True, in_region, True) list_of_locations = [] for match in all_matches: list_of_locations.append( Location(match['x'] + match['width'] / 2, match['y'] + match['height'] / 2)) if len(list_of_locations) > 0: return list_of_locations else: raise FindError('Unable to find text %s' % what) elif isinstance(what, str) or isinstance(what, Pattern): try: pattern = Pattern(what) except Exception: pattern = what if precision is None: precision = Settings.MinSimilarity return image_search_multiple(pattern, precision, in_region) else: raise ValueError(INVALID_GENERIC_INPUT)
def __init__(self, locations, xy=None, randomize=True): self.size = len(locations) if xy is not None: self.xy = xy else: self.xy = True start = 0 end = self.size - 1 if self.size % 2 == 0: median = self.size / 2 - 1 else: median = self.size / 2 if start < end: self.loc = Location.partition_around_median(locations, self.xy, randomize) if start < median: self.left = TwoDTree(locations[:median], not self.xy, randomize) else: self.left = None if median < end: self.right = TwoDTree(locations[median + 1:], not self.xy, randomize) else: self.right = None elif start == end: self.loc = locations[start] self.left = self.right = None else: self.loc = self.left = self.right = None
def find_pokemon(session, sort=False, num_return=5, radius=10): # Get Map details and print pokemon logging.info('Finding nearby Pokemon') cells = session.getMapObjects(radius=radius) latitude, longitude, _ = session.getCoordinates() p_d = [] pokemons = [pokemon for cell in cells.map_cells for pokemon in cell.wild_pokemons] distances = [None] * len(pokemons) for ind, pokemon in enumerate(pokemons): # Log the pokemon found logging.info("Found %s at %f,%f" % ( mappings.id_name[pokemon.pokemon_data.pokemon_id], pokemon.latitude, pokemon.longitude )) distance = Location.getDistance( latitude, longitude, pokemon.latitude, pokemon.longitude ) # Finds distance to pokemon if sort: heapq.heappush(p_d, (distance, pokemon)) else: distances[ind] = distance if sort: try: distances, pokemons = zip(*heapq.nsmallest(num_return, p_d)) except: distances, pokemons = [], [] return distances, pokemons
def group_locations(self): """ :return: list of locations """ group_locations = self._graph_db.match(start_node=self.group_node, rel_type=GraphRelationship.LOCATED_IN, end_node=None) locations_list = [] for rel in group_locations: location_dict = {} location = Location() location.id = rel.end_node['id'] location_dict = dict(location.location_properties) locations_list.append(location_dict) # locations_list.append(item.end_node["formatted_address"]) return locations_list
def __init__(self,lat,lng,name=None,start=None,end=None,duration=None,load=None,type=None): # TODO: Type check parameters self.location = Location(lat,lng,name) self.start = start self.end = end self.duration = duration self.load = load self.type = type
def test_next_location(): loc = Location(1, 1, 3) loc_x, loc_y, x, y = loc.next_location("up", 10, -1) assert loc_y == 0 assert loc_x == 1 loc_x, loc_y, x, y = loc.next_location("down", 10, loc.size + 1) assert loc_y == 2 assert loc_x == 1 loc_x, loc_y, x, y = loc.next_location("left", -1, 10) assert loc_x == 0 assert loc_y == 1 loc_x, loc_y, x, y = loc.next_location("right", loc.size + 1, 10) assert loc_x == 2 assert loc_y == 1
def addTrack(): l = Location.from_id(request.form["location_id"]) uid = User.current_id() if User.is_admin() and request.form["special"] == "true": special = 1 uid = 29 #MAGIC NUMBER!!! This is the ID of the MSS user on the server else: special = 0 ret = l.add_track(request.form["provider_id"], uid, special) return ret