def get(self): data_size = int(self.request.get("data_size")) #generate a map map = Map(building="Civil engineering", level_int=4, level_name="Level 4", max_x=973, max_y=368) map.put() #generate scans and locations randomly for i in range(1, data_size): scan = Scan.random() scan.push_back_in_time(random.randint(0, 14), random.randint(0, 23), random.randint(0, 59)) scan.put() loc = Location() loc.device_mac = scan.device_mac loc.map = map loc.x = random.randint(0, map.max_x) loc.y = random.randint(0, map.max_y) loc.time = scan.time loc.put() self.response.out.write("Database generated")
def main(): rc = ControlRelays() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='/home/pi/sprinkler.log', filemode='a') try: outer = Location('/home/pi/outer_stat', 300, 24 * 60 * 60, 7, 'outer', rc.turn_on_living_room, rc.turn_off_living_room) outer2 = Location('/home/pi/outer2_stat', 730, 24 * 60 * 60, 7, 'outer2', rc.turn_on_outer, rc.turn_off_outer) outer_needed = outer.is_watering_needed() outer2_needed = outer2.is_watering_needed() if outer_needed or outer2_needed: logging.info('Turning on power') rc.turn_on_power() if outer_needed: logging.info('Outer watering started') outer.water() logging.info('Outer watering ended') if outer2_needed: logging.info('Outer 2 watering started') outer2.water() logging.info('Outer 2 watering ended') logging.info('Turning off power') rc.turn_off_power() else: logging.info('No need to run') except Exception as e: logging.error(str(e)) rc.stop_all() finally: call("sync")
class TestLocation(TestCase): def setUp(self): self.location = Location( {"id": "car", "name": "Carnival", "active": False} ) def test_set_active(self): self.location.set_active() self.assertTrue(self.location.active) def test_is_active(self): self.assertFalse(self.location.is_active()) self.location.active = True self.assertTrue(self.location.is_active())
def a_star(start, end): location = Location.get_instance() open_set = {start} came_from = dict() gscore = {coord: 100000 for coord in location.get_valid_for_ghosts_coords()} fscore = dict(gscore) # copy of this dict gscore[start] = 0 fscore[start] = h(start, end) while len(open_set) > 0: # get the coordinate with the lowest value current = min(open_set, key=lambda x: fscore[x]) if current == end: return get_first_step(start, came_from, end) open_set.remove(current) for neighbour in [coord for coord in current.get_neighbours()]: tentative_gScore = gscore[current] + 1 if tentative_gScore < gscore[neighbour]: came_from[neighbour] = current gscore[neighbour] = tentative_gScore fscore[neighbour] = gscore[neighbour] + h(neighbour, end) if neighbour not in open_set: open_set.add(neighbour)
def do_add_user(self, line): ''' This command adds a single user to the list of users USAGE: ad_user PersonE {(17, 42), [Running, Reading, Trekking]} ''' try: name, x, y, interests, attributes = parse_line(line.strip()) except Exception as e: print 'Unable to add user: ERROR: %s' % e return location = Location(x, y) user = User(name, location, interests, **attributes) cell = location.cell() if cell in self.users: self.users[cell].append(user) else: self.users[cell] = [user] self.users_by_name[name] = user print 'User added'
def setUp(self): self.location1 = Location(postcode='EC4M 8AD', address="St. Paul's Churchyard, London", geo={ 'lat': 51.513723, 'lng': -0.099858 }) self.location2 = Location(postcode='EC4M 8AD', address="St. Paul's Churchyard, London", geo={ 'lat': 51.513723, 'lng': -0.099858 }) self.location3 = Location(postcode='EC4M 8AD', address="St. Paul's Churchyard, London", geo={ 'lat': 51.513723, 'lng': -0.099858 })
def do_action(self, command_text, game): """Perform a special action associated with this item""" end_game = False # Switches to True if this action ends the game. if command_text in self.commands: function, arguments, preconditions = self.commands[command_text] if Location.check_preconditions(preconditions, game): end_game = function(game, arguments) else: print("Cannot perform the action %s" % command_text) return end_game
def move(self, movement): locations = Location.get_instance() next_coord = Coordinate(self.location.x, self.location.y) next_coord.go_in_direction(movement) if not Movement.inverses( self.movement, movement) and locations.is_valid_for_ghosts(next_coord): self.movement = movement super().move(self.movement)
def location_text(self): paths = self.location.paths nPath = None if not paths['N'] else Location.toEnum(paths['N']) sPath = None if not paths['S'] else Location.toEnum(paths['S']) wPath = None if not paths['W'] else Location.toEnum(paths['W']) ePath = None if not paths['E'] else Location.toEnum(paths['E']) nPathString = nPath.emoji + '/go_' + str( nPath.id) + ' ' + nPath.cstring if nPath else '' sPathString = sPath.emoji + '/go_' + str( sPath.id) + ' ' + sPath.cstring if sPath else '' ePathString = ePath.emoji + '/go_' + str( ePath.id) + ' ' + ePath.cstring if ePath else '' text = ' {}\n'.format(nPathString) text += ' {}{}{}\n'.format( '__' + wPath.emoji if wPath else ' ', u'\U0001F466', ePathString) text += ' {} {}\n'.format('/' if wPath else ' ', sPathString) text += '/go_{}\n'.format(str(wPath.id) + ' ' + wPath.cstring + '\n') if wPath else '\n' return text
def place(self): self.drawer_id = self.drawer_combobox.currentText() recipient_text = self.recipient_combobox.currentText() for user in User.get_users(): if user.name == recipient_text: self.recipient_id = user.id location_text = self.location_combobox.currentText() for location in Location.get_locations(): if location.name == location_text: self.location_id = location.id self.content.components['open_drawer'].drawer_id = self.drawer_combobox.currentText() self.content.activate(self.content.components['open_drawer'])
def place(self): self.drawer_id = self.drawer_combobox.currentText() recipient_text = self.recipient_combobox.currentText() for user in User.get_users(): if user.name == recipient_text: self.recipient_id = user.id location_text = self.location_combobox.currentText() for location in Location.get_locations(): if location.name == location_text: self.location_id = location.id self.content.components[ 'open_drawer'].drawer_id = self.drawer_combobox.currentText() self.content.activate(self.content.components['open_drawer'])
def get(self): data_size = int(self.request.get("data_size")) #generate a map map = Map(building="Civil engineering",level_int=4, level_name="Level 4", max_x=973,max_y=368) map.put() #generate scans and locations randomly for i in range(1,data_size): scan = Scan.random() scan.push_back_in_time(random.randint(0,14),random.randint(0,23),random.randint(0,59)) scan.put() loc = Location() loc.device_mac = scan.device_mac loc.map = map loc.x = random.randint(0,map.max_x) loc.y = random.randint(0,map.max_y) loc.time = scan.time loc.put() self.response.out.write("Database generated")
def find_group_callback(update, context): message = update.message location = Location(latitude=message.location.latitude, longitude=message.location.longitude) groups = groups_by_distance(location) closest = groups[:CLOSEST_GROUPS] groups_display_str = '\n'.join(list(map(str, closest))) LOGGER.info(f'Received location {location}. Replying with {closest}') if closest[0].distance > 1.0: response = messages.LOCATIONS_CLOSE_TEMPLATE_NOK.format( group_info=groups_display_str) else: response = messages.LOCATIONS_CLOSE_TEMPLATE_OK.format( group_info=groups_display_str) context.bot.send_message(chat_id=update.effective_chat.id, text=response)
def __init__(self, content): super(AddDelivery, self).__init__() self.content = content loadUi(os.path.join(UI_DIRECTORY, 'add_delivery.ui'), self) self.cancel_button.clicked.connect(self.cancel) self.save_button.clicked.connect(self.place) self.deliveries = {} self.sender = None self.drawer_id = '1' for location in Location.get_locations(): self.location_combobox.addItem(location.name) #from PySide.QtGui import QComboBox #test = QComboBox() #self.recipient_combobox.addItems(User.get_users()) #self.location_combobox.addItems(Location.get_locations()) AuthenticationClient.add_listener(self)
def setUp(self): self.location = Location( {"id": "car", "name": "Carnival", "active": False} )
def build_game(): # Locations cottage = Location("Cottage", "You are standing in a small cottage.") garden_path = Location( "Garden Path", "You are standing on a lush garden path. There is a cottage here.") cliff = Location( "Cliff", "There is a steep cliff here. You fall off the cliff and lose the game. THE END.", end_game=True) fishing_pond = Location("Fishing Pond", "You are at the edge of a small fishing pond.") winding_path = Location( "Winding Path", "You are walking along a winding path that leads south and east. There is a tall tree here." ) tree = Location( "A Tall Tree", "You are at the top of a tall tree. From your perch you can see the tower of Action Castle." ) drawbridge = Location("Drawbridge", "You come to the drawbridge of Action Castle.") courtyard = Location( "Courtyard", "You are in the courtyard of Action Castle. A castle guard stands watch to the east. Stairs lead up into the tower and down into darkness." ) great_feasting_hall = Location( "Gread Feasting Hall", "You stand inside the great feasting hall.") tower_stairs = Location( "Tower Stairs", "You climb the tower stairs until you come to a door.") dungeon_stairs = Location( "Dungeon Stairs", "You are on the dungeon stairs. It's very dark here.") tower = Location("Tower", "You are in the tower.") dungeon = Location("Dungeon", "You are in the dungeon.") throne_room = Location( "Throne Room", "This is the throne room of Action Castle. There is an ornate gold throne here." ) # Connections cottage.add_connection("out", garden_path) garden_path.add_connection("west", cliff) garden_path.add_connection("south", fishing_pond) garden_path.add_connection("north", winding_path) winding_path.add_connection("up", tree) winding_path.add_connection("east", drawbridge) drawbridge.add_connection("east", courtyard) courtyard.add_connection("up", tower_stairs) courtyard.add_connection("down", dungeon_stairs) courtyard.add_connection("east", great_feasting_hall) tower_stairs.add_connection("in", tower) dungeon_stairs.add_connection("down", dungeon) great_feasting_hall.add_connection("east", throne_room) # Items that you can pick up lantern = Item("lantern", "an oil lantern", "IT PROVIDES ADEQUATE LIGHT WHEN NEEDED. MADE IN CHINA.", start_at=cottage) fishing_pole = Item("pole", "a fishing pole", "A SIMPLE FISHING POLE.", start_at=cottage) potion = Item( "potion", "a poisonous potion", "IT'S BRIGHT GREEN AND STEAMING.", start_at=cottage, take_text= 'As you near the potion, the fumes cause you to faint and lose the game. THE END.', end_game=True) rosebush = Item( "rosebush", "a rosebush", "THE ROSEBUSH CONTAINS A SINGLE RED ROSE. IT IS BEAUTIFUL.", start_at=garden_path) rose = Item("rose", "a red rose", "IT SMELLS GOOD.", start_at=None) fish = Item("fish", "a dead fish", "IT SMELLS TERRIBLE.", start_at=None) branch = Item("branch", "a dead branch", "IT COULD MAKE A GOOD CLUB.", start_at=tree) key = Item("key", "a shining key", "YOUR NOT SURE WHERE IT LEADS TO.", start_at=None) crown = Item( "crown", "a gold crown", "YOU SEE THE GOLD CROWN THAT ONCE BELONGED TO THE KING OF ACTION CASTLE.", start_at=None) candle = Item( "candle", "a strange candle", "YOU SEE THAT THE STRANGE CANDLE IS COVERED IN MYSTERIOUS RUNES.", start_at=great_feasting_hall) # Scenery (not things that you can pick up) pond = Item("pond", "a small fishing pond", "THERE ARE FISH IN THE POND.", start_at=fishing_pond, gettable=False) troll = Item("troll", "a mean troll", "THE TROLL HAS A WARTY GREEN HIDE AND LOOKS HUNGRY!", start_at=drawbridge, gettable=False) guard = Item( "guard", "one of the king's guard", "THE GUARD WEARS CHAINMAIL ARMOR BUT NO HELMET. A KEY HANGS FROM HIS BELT.", start_at=courtyard, gettable=False) unconscious_guard = Item( "unconcious guard", "an unconscious guard", "THE GUARD LIES MOTIONLESS ON THE GROUND. HIS KEY DANGLES LOOSELY FROM HIS BELT.", start_at=None, gettable=False) locked_tower_door = Item("door", "a door", "THE DOOR LOOKS LIKE IT NEEDS A KEY.", start_at=tower_stairs, gettable=False) darkness = Item("nothing, IT'S PITCH BLACK DOWN HERE!", "", "", start_at=dungeon_stairs, gettable=False) ghost = Item( "ghost", "a spooky ghost", "THE GHOST HAS BONY, CLAW-LIKE FINGERS AND WEARS A GOLD CROWN.", start_at=dungeon, gettable=False) princess = Item("princess", "the princess", "THE PRINCESS IS BEAUTIFUL, SAD and LONELY.", start_at=tower, gettable=False) nice_princess = Item( "princess", "the princess", "THE PRINCESS IS BEAUTIFUL, SAD and LONELY. SHE HOLDS YOUR ROSE CLOSE.", start_at=None, gettable=False) elligable_princess = Item( "princess", "the princess", "THE PRINCESS IS BEAUTIFUL, SAD and LONELY. SHE HOLDS YOUR ROSE CLOSE.", start_at=None, gettable=False) throne = Item("throne", "the throne", "AN ORNATE GOLD THRONE", start_at=throne_room, gettable=False) # Add special functions to your items rosebush.add_action("pick rose", Game.add_item_to_inventory, (rose, "You pick the lone rose from the rosebush.", "You already picked the rose.")) rose.add_action("smell rose", Game.describe_something, ("It smells sweet.")) pond.add_action("catch fish", Game.describe_something, ( "You reach into the pond and try to catch a fish with your hands, but they are too fast." )) pond.add_action("catch fish with pole", Game.add_item_to_inventory, (fish, "You dip your hook into the pond and catch a fish.", "You weren't able to catch another fish."), preconditions={"inventory_contains": fishing_pole}) fish.add_action("eat fish", Game.end_game, ( "That's disgusting! It's raw! And definitely not sashimi-grade! But you've won this version of the game. THE END." )) troll.add_action("give troll a fish", Game.perform_multiple_actions, ([ (Game.destroy_item, (fish, "You give the troll a tasty fish.", "")), (Game.destroy_item, (troll, "The troll runs off to eat his prize.", "")), ]), preconditions={ "inventory_contains": fish, "location_has_item": troll }) troll.add_action( "hit troll with branch", Game.end_game, ("Not a good idea! The troll rips you limb from limb! THE END.")) guard.add_action("steal key from guard", Game.end_game, ( "That was unwise... The guard locks you in the dungeon and you starve to death! THE END." )) guard.add_action( "hit guard with branch", Game.perform_multiple_actions, ([ (Game.destroy_item, (branch, "You hit the guard with the branch, and the branch shatters into tiny pieces.", "")), (Game.destroy_item, (guard, "The guard slumps to the ground, unconscious.", "")), (Game.create_item, (unconscious_guard, "", "")), (Game.create_item, (key, "The guard's key falls to the ground", "")), ]), preconditions={ "inventory_contains": branch, "location_has_item": guard }) locked_tower_door.add_action( "unlock door", Game.destroy_item, (locked_tower_door, "You use the key to unlock the door.", ""), preconditions={"inventory_contains": key}) lantern.add_action( "light lantern", Game.destroy_item, (darkness, "You can now see well enough to continue down the stairs.", ""), preconditions={ "inventory_contains": lantern, "in_location": dungeon_stairs }) ghost.add_action("take crown", Game.end_game, ( "The ghost reaches out a skeletal hand and drains your life force. THE END." )) darkness.add_action( "light candle", Game.describe_something, ("The candle's flickering flame is blown out by a draft."), preconditions={"inventory_contains": candle}) ghost.add_action( "light candle", Game.perform_multiple_actions, ([ (Game.describe_something, ("The candle casts a flickering flame and emits acrid smoke.")), (Game.destroy_item, (ghost, "The ghost flees the dungeon, and leaves behind a gold crown.", "")), (Game.create_item, (crown, "", "")), ]), preconditions={"inventory_contains": candle}) candle.add_action( "light candle", Game.describe_something, ("The candle casts a flickering flame and emits acrid smoke."), preconditions={"inventory_contains": candle}) candle.add_action("read runes", Game.describe_something, ( "The odd runes are part of an exorcism ritual used to dispel evil spirits." )) princess.add_action( "give rose to princess", Game.perform_multiple_actions, ([ (Game.destroy_item, (princess, "The princess' cold demeanor softens, and her heart warms to you as she smells the rose.", "")), (Game.destroy_item, (rose, "", "")), (Game.create_item, (nice_princess, "", "")), ]), preconditions={"inventory_contains": rose}) princess.add_action("marry princess", Game.describe_something, ("You're not royalty!")) princess.add_action("speak to princess", Game.describe_something, ("She will not speak to you.")) nice_princess.add_action("marry princess", Game.describe_something, ("You're not royalty!")) nice_princess.add_action( "ask princess about ghost", Game.describe_something, ("'The guards whisper that the ghost of the king haunts the dungeons as a restless spirit!'" )) nice_princess.add_action("ask about crown", Game.describe_something, ("'My father's crown was lost after he died.'")) nice_princess.add_action("ask about tower", Game.describe_something, ("'I cannot leave the tower until I'm wed!'")) nice_princess.add_action( "ask about throne", Game.describe_something, ("'Only the rightful ruler of Action Castle may claim the throne!'")) nice_princess.add_action( "Give crown to princess", Game.perform_multiple_actions, ([ (Game.describe_something, ("'My father's crown! You have put his soul to rest and may now take his place as ruler of this land!' She places the crown on your head." )), (Game.destroy_item, (nice_princess, "", "")), (Game.create_item, (elligable_princess, "", "")), ]), preconditions={"inventory_contains": crown}) elligable_princess.add_action( "marry princess", Game.describe_something, ("'Yes, yes! A thousand times yes.' YOU MARRY THE PRINCESS!")) elligable_princess.add_action( "ask princess about ghost", Game.describe_something, ("'The guards whisper that the ghost of the king haunts the dungeons as a restless spirit!'" )) elligable_princess.add_action( "ask about crown", Game.describe_something, ("'My father's crown was lost after he died.'")) elligable_princess.add_action( "ask about tower", Game.describe_something, ("'I cannot leave the tower until I'm wed!'")) elligable_princess.add_action( "ask about throne", Game.describe_something, ("'Only the rightful ruler of Action Castle may claim the throne!'")) throne.add_action("sit on throne", Game.end_game, ("You are now the new ruler of Action Castle! THE END."), preconditions={"in_inventory": crown}) # Blocks drawbridge.add_block( "east", "There is a troll blocking the bridge. The troll has a warty green hide and looks hungry.", preconditions={"block_gone": troll}) tower_stairs.add_block("in", "The door is locked. Maybe it needs a key.", preconditions={"block_gone": locked_tower_door}) dungeon_stairs.add_block("down", "It's too dark to see!", preconditions={"block_gone": darkness}) return Game(cottage)
def __init__(self): self.grid = [[None] * 5] * 5 #Blank 2D Map Grid self.location = Location() #Blank location object
def get(self): db.delete(Scan.all()) db.delete(Location.all()) self.response.out.write("Database cleared")
class TestLocation(unittest.TestCase): def setUp(self): self.location1 = Location(postcode='EC4M 8AD', address="St. Paul's Churchyard, London", geo={ 'lat': 51.513723, 'lng': -0.099858 }) self.location2 = Location(postcode='EC4M 8AD', address="St. Paul's Churchyard, London", geo={ 'lat': 51.513723, 'lng': -0.099858 }) self.location3 = Location(postcode='EC4M 8AD', address="St. Paul's Churchyard, London", geo={ 'lat': 51.513723, 'lng': -0.099858 }) def test_check_params(self): with self.assertRaises(TypeError): self.location1.set_times(mode='strongest', value=15, to_location=self.location2) with self.assertRaises(TypeError): self.location1.set_impacts(mode='fastest', value='15.8', to_location=self.location2) with self.assertRaises(TypeError): self.location1.set_times(mode='fastest', value=15, to_location='dest') with self.assertRaises(TypeError): self.location1.set_impacts(mode='fastest', value=15, to_location=self.location1) with self.assertRaises(AttributeError): self.location1.times = 15 def test_times(self): self.location1.set_times(mode='fastest', value=15, to_location=self.location2) self.location1.set_times(mode='fastest', value=30.0, to_location=self.location3) self.location1.set_times( 'fastest', 18, self.location2) # Should overwrite the previous 15 self.assertEqual(self.location1.times, [18, 30.0]) self.assertEqual(self.location1.get_times(), [18, 30.0]) self.assertEqual(self.location1.get_times(to_location=self.location2), 18) self.assertEqual(self.location1.get_times(to_location=self.location3), 30.0) self.assertEqual(self.location2.get_times(to_location=self.location1), 18) def test_impact_times(self): self.location1.set_impacts(mode='fastest', value=5, to_location=self.location2) self.location1.set_impacts(mode='fastest', value=-5, to_location=self.location3) self.location1.set_impacts( 'fastest', 8, self.location2) # Should overwrite the previous 15 self.assertEqual(self.location1.impact_times, [8, -5]) self.assertEqual(self.location1.get_impacts(), [8, -5]) self.assertEqual( self.location1.get_impacts(to_location=self.location2), 8) self.assertEqual( self.location1.get_impacts(to_location=self.location3), -5) self.assertEqual( self.location2.get_impacts(to_location=self.location1), 8) def test_geo(self): with self.assertRaises(TypeError): self.location1.geo = 15 with self.assertRaises(KeyError): self.location1.geo = {'lat': 5, 'lon': 5} def test_mode(self): self.location1.set_times('public transport', 15, self.location2) self.location1.set_times('car', 23, self.location2) self.location1.set_impacts('public transport', 8, self.location2) self.location1.set_impacts('car', 11, self.location2) with self.assertRaises(TypeError): self.location1.mode = 'test' self.assertEquals(self.location1.times, []) with self.assertRaises(KeyError): self.location1.get_times(to_location=self.location2) self.location1.mode = 'car' self.assertEquals(self.location1.get_times(to_location=self.location2), 23) self.assertEquals( self.location1.get_impacts(to_location=self.location2), 11) self.location1.mode = 'public transport' self.assertEquals(self.location1.get_times(to_location=self.location2), 15) self.assertEquals( self.location1.get_impacts(to_location=self.location2), 8)
return f'{self.name}: {self.link}' @dataclass class GroupProposal(object): group: Group distance: float def __str__(self): return f'- {self.group}' GROUP_LIST = [ Group(name='Artés', link='https://twitter.com/ateneuartes', center=Location(latitude=41.796428, longitude=1.952352)), Group(name='Badalona', link='https://t.me/XarxaSolidariaBDN', center=Location(latitude=41.4484, longitude=2.244)), Group(name='Barcelona - Antonit de Capmany/Tinent Flomesta', link='https://t.me/flomesta', center=Location(latitude=41.372543, longitude=2.132367)), Group(name='Barcelona - Badal de Baix (La Bordeta)', link='https://chat.whatsapp.com/GzxgmQQeaGyFDCWmWF3QNP', center=Location(latitude=41.369153, longitude=2.13653)), Group(name='Barcelona - Badal superior', link='https://t.me/badalsuperior', center=Location(latitude=41.377685, longitude=2.129068)), Group(name='Barcelona - Barceloneta', link='https://t.me/joinchat/QjDQuxq-jgGVbNwVOFSGGw', center=Location(latitude=41.3825, longitude=2.1859)),
"long":8.5686 },{ "name":"Vattiyoorkavu", "lat":76.8731, "long":8.5686 },{ "name":"External", "lat":76.2999, "long":9.9816 },{ "name":"Trivandrum", "lat":76.2999, "long":9.9816 }] for l in locations: s = Location(name=l['name'],latitude=l['lat'],longitude=l['long']) session.add(s) session.commit() stations = [ { "site_name": "CHC Poonthura", "site_id": "ST1", 'location':"Poonthura", "stype":"phc" }, { "site_name": "PHC Chettivilakonam", "site_id": "ST2",
def distance(self, location: Location) -> float: return location.distance(self.center)