def parseLatLong(self, topLeft, bottomRight):
        minLat = min(topLeft.lat, bottomRight.lat)
        maxLat = max(topLeft.lat, bottomRight.lat)
        minLon = min(topLeft.lon, bottomRight.lon)
        maxLon = max(topLeft.lon, bottomRight.lon)

        return Location(minLat, minLon), Location(maxLat, maxLon)
Exemple #2
0
 def test_partial_value(self, lat, lon, expected):
     with pytest.raises(Exception):
         loc = Location("Test", lon)
     with pytest.raises(Exception):
         loc = Location("Test", lat)
     with pytest.raises(Exception):
         loc = Location(lon, lat)
    def get_neighbors(self, state):
        neighbors = []

        # Wait action
        n = State(state.time + 1, state.location)
        if self.state_valid(n):
            neighbors.append(n)
        # Up action
        n = State(state.time + 1,
                  Location(state.location.x, state.location.y + 1))
        if self.state_valid(n) and self.transition_valid(state, n):
            neighbors.append(n)
        # Down action
        n = State(state.time + 1,
                  Location(state.location.x, state.location.y - 1))
        if self.state_valid(n) and self.transition_valid(state, n):
            neighbors.append(n)
        # Left action
        n = State(state.time + 1,
                  Location(state.location.x - 1, state.location.y))
        if self.state_valid(n) and self.transition_valid(state, n):
            neighbors.append(n)
        # Right action
        n = State(state.time + 1,
                  Location(state.location.x + 1, state.location.y))
        if self.state_valid(n) and self.transition_valid(state, n):
            neighbors.append(n)
        return neighbors
Exemple #4
0
 def test_getLongitude(self):
   # Test the parsing of latitude from -100 to 100 W; from 10 to 10 E; etc.
   l1 = Location([10, -100])
   l2 = Location([10, 30])
   l1_longitude = l1.get_longitude()
   l2_longitude = l2.get_longitude()
   self.assertAlmostEqual(l1_longitude, "100 W")
   self.assertAlmostEqual(l2_longitude, "30 E")
Exemple #5
0
 def test_getLatitude(self):
   # Test the parsing of latitude from -50 to 50 S; from 30 to 30 N; etc.
   l1 = Location([50, 0])
   l2 = Location([-30, 0])
   l1_latitude = l1.get_latitude()
   l2_latitude = l2.get_latitude()
   self.assertAlmostEqual(l1_latitude, "50 N")
   self.assertAlmostEqual(l2_latitude, "30 S")
Exemple #6
0
def initRobotFromCfg(runtimeID):
    done = False
    index = 1
    robots = []
    thisRobot = None

    srcDict = CFGReader.ReadConfig("swarm.cfg", "src")
    dstDict = CFGReader.ReadConfig("swarm.cfg", "dst")

    if not srcDict:
        sys.exit("No [src] found in swarm.cfg")
    if not dstDict:
        sys.exit("No [dst] found in swarm.cfg")

    srcFID = srcDict["fid"]
    srcLoc = Location(float(srcDict["x"]), float(srcDict["y"]),
                      float(srcDict["z"]))
    srcNode = Robot("-1", srcLoc, srcFID, None, 6666, 6666, isSrc=True)
    robots.append(srcNode)

    dstFID = dstDict["fid"]
    dstLoc = Location(float(dstDict["x"]), float(dstDict["y"]),
                      float(dstDict["z"]))
    dstNode = Robot("-2", dstLoc, dstFID, None, 6666, 6666, isDest=True)
    robots.append(dstNode)

    while done == False:
        section = "R" + str(index)
        robotDict = CFGReader.ReadConfig("swarm.cfg", section)
        if not robotDict:
            done = True
            break

        rID = robotDict['rid']
        fID = robotDict['fid']
        x = float(robotDict['x'])
        y = float(robotDict['y'])
        z = float(robotDict['z'])

        loc = Location(x, y, z)

        newRobot = Robot(rID, loc, fID, None, 6666, 6666)
        robots.append(newRobot)
        if rID == runtimeID:
            thisRobot = newRobot
        index += 1

    if (thisRobot == None):
        sys.exit("No [R%s] found in swarm.cfg" % runtimeID)

    thisRobot.all_robots["-1"] = srcLoc
    thisRobot.all_robots["-2"] = dstLoc
    currFlow = Flow.Flow(thisRobot.fid, robots, srcNode, dstNode)
    thisRobot.setFlowAndGraph(currFlow, robots)
    thisRobot.establishConnections()

    return robots
    def __init__(self):
        self.time = -1
        self.type = -1

        self.agent_1 = ''
        self.agent_2 = ''

        self.location_1 = Location()
        self.location_2 = Location()
Exemple #8
0
  def test_distance_between_two_locations(self):
    # Test distance when are two points at 0,0
    location1 = Location([0, 0])
    location2 = Location([0, 0])
    self.assertAlmostEqual(get_distance_between_two_locations(location1, location2), 0)

    # Test distance between two locations
    location1 = Location([54, 30])
    location2 = Location([50, -100])
    self.assertAlmostEqual(get_distance_between_two_locations(location1, location2), 7546)
Exemple #9
0
    def __init__(self):
        self._log = logging.getLogger(__class__.__name__)       # noqa: F821
        self._log.debug("Created board metrics class")

        # Metrics
        self.throne_occupied = True

        # Lookup values
        self._throne_loc = Location(3, 3)
        self._corners = [Location(0, 0), Location(6, 0),
                         Location(0, 6), Location(6, 6)]
    def make_agent_dict(self):
        for agent in self.agents:
            start_state = State(0,
                                Location(agent['start'][0], agent['start'][1]))
            goal_state = State(0, Location(agent['goal'][0], agent['goal'][1]))

            self.agent_dict.update(
                {agent['name']: {
                     'start': start_state,
                     'goal': goal_state
                 }})
Exemple #11
0
    def initialize(self):
        """ Initialize the game board, place pieces, and start the game """
        for i in range(32):
            self.__board.append(None)

        for i in range(12):
            self.addPiece(
                GamePiece(PieceColor.Light, getPlayer[PlayerColor.Light],
                          self), Location(i))
            self.addPiece(
                GamePiece(PieceColor.Dark, getPlayer[PlayerColor.Dark], self),
                Location(32 - i))

        self.__currentTurn = PlayerColor.Light
Exemple #12
0
    def __init__(self, session, api_key, route_id):
        route = Route(session, route_id)

        self.__start_location = Location(session, route.get_start_location())
        self.__end_location = Location(session, route.get_end_location())

        maps_client = googlemaps.Client(key=api_key)

        now = datetime.now()

        self.__directions_result = maps_client.directions(
            self.__start_location.get_full_address(),
            self.__end_location.get_full_address(),
            mode="driving",
            departure_time=now)[0]
Exemple #13
0
    def initLogFileFromCfg(self):
        done = False
        index = 1

        while done == False:
            section = "R" + str(index)
            robotDict = CFGReader.ReadConfig("swarm.cfg", section)
            if not robotDict:
                done = True
                break

            rID = robotDict['rid']
            loc = Location(float(robotDict["x"]), float(robotDict["y"]),
                           float(robotDict["z"]))
            self.nodes[rID] = self.xyzToLatLong(loc.getX(), loc.getY(),
                                                loc.getZ())
            index += 1

        srcDict = CFGReader.ReadConfig("swarm.cfg", "src")
        dstDict = CFGReader.ReadConfig("swarm.cfg", "dst")

        if not srcDict:
            sys.exit("No [src] found in swarm.cfg")
        if not dstDict:
            sys.exit("No [dst] found in swarm.cfg")

        srcLoc = Location(float(srcDict["x"]), float(srcDict["y"]),
                          float(srcDict["z"]))
        dstLoc = Location(float(dstDict["x"]), float(dstDict["y"]),
                          float(dstDict["z"]))
        self.nodes[index] = self.xyzToLatLong(srcLoc.getX(), srcLoc.getY(),
                                              srcLoc.getZ())
        self.nodes[index + 1] = self.xyzToLatLong(dstLoc.getX(), dstLoc.getY(),
                                                  dstLoc.getZ())

        for i in range(11):
            self.currTimeInterval = i
            for rID in sorted(self.nodes.iterkeys()):
                nodeLoc = self.nodes[rID]
                latLongLoc = self.xyzToLatLong(nodeLoc.getX(), nodeLoc.getY(),
                                               nodeLoc.getZ())
                logLine = str(i) + '.0 nem:' + str(
                    rID) + ' location gps ' + str(
                        latLongLoc.getX()) + ',' + str(
                            latLongLoc.getY()) + ',' + str(
                                latLongLoc.getZ()) + '\n'
                self.logFile.write(logLine)
        self.currTimeInterval += 1
Exemple #14
0
    def build(self):
        objects = [TruckObject(Location(23.7, 90.4), 48)]
        links = []
        vertices = []
        tempVertexData = []

        objects.append(self.buildDhaka(self.startData))

        for dataPoint in self.roadData:
            if dataPoint.hasGap():
                if dataPoint.gap == "BS":
                    startNodeData = dataPoint
                    if len(links) == 0:
                        road = StartSimioLink(startNodeData.road,
                                              "Output@Dhaka",
                                              startNodeData.lrp)
                    else:
                        road = SimioLink(startNodeData.road, objects[-1].lrp,
                                         startNodeData.lrp)
                    links.append(road)

                    for vertexData in tempVertexData:
                        vertices.append(
                            SimioVertex(
                                road.linkName,
                                Location(vertexData.lat, vertexData.lon)))

                    tempVertexData = []
                else:
                    (bridgeStart, bridgeEnd,
                     bridgeLink) = self.buildBridge(startNodeData, dataPoint)
                    objects.append(bridgeStart)
                    objects.append(bridgeEnd)
                    links.append(bridgeLink)
                    self.bridgeCount += 1
            else:
                tempVertexData.append(dataPoint)

        sink = self.buildChittagong(self.endData)
        lastLink = EndSimioLink(self.endData.road, objects[-1].lrp,
                                "Input@Chittagong")
        objects.append(sink)
        links.append(lastLink)

        print('Added {} bridges with {} category E.'.format(
            self.bridgeCount, self.categoryECount))

        return (objects, links, vertices)
Exemple #15
0
    def __init__(self, data):
        # name
        self.instance_name = data['name']
        # locations
        self.locations = {
            loc['id']: Location(loc)
            for loc in data['locations']
        }
        # register exiting transitions to each location object
        for t in data['transitions']:
            tid = t['sid']
            transition = Transition(t)
            self.locations[tid].add_outgoing_transition(transition)

        # current location setup
        loc_id = data['initialLocation']  # initial location id
        self.current_location = self.locations[loc_id]

        # variable objects
        self.I = {i['name']: float(i['initialValue']) for i in data['I']}
        self.O = {o['name']: float(o['initialValue']) for o in data['O']}
        self.X = {x['name']: float(x['initialValue']) for x in data['X_C']}

        # Simulink has multiple options for initialization
        # 1. reset on the first transition
        for fx in data['initialization']:
            if fx['LHS'] in self.X:
                self.X[fx['LHS']] = fx['RHS']
            elif fx['LHS'] in self.O:
                self.O[fx['LHS']] = fx['RHS']
        # 2. initial location entry actions
        initLocID = data['initialLocation']
        self.locations[initLocID].en(self.I, self.O,
                                     self.X)  # evaluate "en" of a location
        self.update_O()
def copy_files_not_on_player(pc_folder: Location, player_playlist: Playlist):
    """
    function copying songs from PC to Player Playlist
    (in scope of currently investigated folder)

    :param pc_folder: Location
    :param player_playlist: Playlist
    :return:
    """

    player_curr_folder_song_list = []

    # creating list of songs in Player twin of currently investigated PC Playlist folder
    pc_folder_path = os.path.join(player_playlist.directory, pc_folder.path_relative_to_playlsit_location)
    for _, _, player_file_names in os.walk(pc_folder_path):
        for name in player_file_names:

            player_curr_folder_song_list.append(name)

    # copying music files to album folder on Player
    for root, _, file_names in os.walk(pc_folder.full_path):
        for name in file_names:
            pc_file = os.path.join(root, name)
            if name not in player_curr_folder_song_list:

                player_folder = Location(full_path=os.path.join(player_playlist.directory,
                                                                pc_folder.path_relative_to_playlsit_location),
                                         path_relative_to_playlist_location=player_playlist.directory)

                copy_file(source_file=pc_file,
                          destination_folder=player_folder)
Exemple #17
0
    def initializeLocations(self):
        locations = self.locationData
        for location in locations:
            item = locations[location]
            locationObj = Location(location)
            self.locations[location] = locationObj
            if isinstance(item, dict):
                itemName = item['item']
            else:
                itemName = item

            # if itemName in self.items:
            itemObj = self.items[itemName]
            locationObj.addItem(item, itemObj)
            # else:
            #     locationObj.addItem(item)
            #     itemObj = locationObj.item
            #     self.items[itemName] = itemObj
            #     if itemName in itemDictionary:
            #         itemObj.image = itemDictionary[itemName]
            if location in self.wothData:
                locationObj.isWOTH = True
            for region in self.regions.values():
                for search in region.search:
                    if search in location:
                        region.locations.append(locationObj)
                        locationObj.region = region
                        locationObj.isDungeon = region.isDungeon
                        break
def main():
    rows, columns = eval(
        input("Enter the number of rows and columns in the list: "))
    location1 = Location()
    a = location1.createMatrix(rows, columns)
    location2 = location1.locateLargest(a)
    print(location2.__str__())
def copy_folders_not_on_player(pc_folder: Location, pc_playlist: Playlist, player_playlist: Playlist):
    """
    copying folders from PC to Player, before copying a folder function checks folder structure for non existent parents

    e.g.
    wnen copying album, fucntion checks if artist folder exist, and if not copies artist folder with all subfolders

    :param pc_folder:
    :param pc_playlist:
    :param player_playlist:
    :return:
    """

    relative_parent = os.path.dirname(pc_folder.path_relative_to_playlsit_location)

    # if parent of checked folder exists on player -> copying files into it
    if os.path.isdir(os.path.join(player_playlist.directory, relative_parent)):

        player_folder = Location(full_path=os.path.join(player_playlist.directory, pc_folder.path_relative_to_playlsit_location),
                                 path_relative_to_playlist_location=player_playlist.directory)

        copy_folder(source_folder=pc_folder,
                    destination_folder=player_folder)

    # if parent of checked folder doesn't exists on player -> checking if it's parent exists
    else:
        check_tree_up_for_non_existent_folder(pc_playlist=pc_playlist,
                                              player_playlist=player_playlist,
                                              checked_folder=relative_parent)
Exemple #20
0
    def initialize_objects(self):
        log.info("initialize_objects()")
        args = {"GAME": self}
        objects = json.load(open("GameObjects.json"))
        for location in objects["locations"]:
            z = objects["locations"][location].copy()
            z.update(args)
            self.locations[location] = Location(**z)
            self.allObj[location] = self.locations[location]
        for barrier in objects["barriers"]:
            z = objects["barriers"][barrier].copy()
            z.update(args)
            self.barriers[barrier] = Barrier(**z)
            self.allObj[barrier] = self.barriers[barrier]
        for item in objects["items"]:
            z = objects["items"][item].copy()
            z.update(args)
            self.items[item] = Item(**z)
            self.allObj[item] = self.items[item]
        z = objects["player"]["player"]
        z.update(args)
        self.player = Player(**z)

        self.assemble_barriers()
        self.assemble_inventories(self.items)
        return True
    def openFile(self):
        self.newFile()

        fileName = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', filter="Json files (*.json)")
        if fileName.__len__() == 0:
            return
        f = open(fileName[0], "r")
        file = f.read()
        f.close()

        itemArray = json.loads(file)

        # load items
        for item in itemArray[0]:
            newItem = Item(item["name"])
            newItem.basePrice = item["basePrice"]
            newItem.groups = item["groups"]
            self.items.append(newItem)
            self.ui.itemEditView.addItem(newItem.name)

        # load groups
        for group in itemArray[1]:
            self.groups.append(group)
            self.ui.groupEditView.addItem(group)

        # load locations
        for location in itemArray[2]:
            loc = Location(location["name"])
            loc.loadModifiers(location["modifiers"], self.items, self.groups)
            self.locations.append(loc)
            self.ui.locationSelection.addItem(loc)

        self.refreshEverything()
 def getLocationForPlace(self, country, state, county, city, url, id):
     location = Location(country, state, county, city, 0, 0, -1, False)
     if self.locationToId.has_key(location):
         return self.idToLocation[self.locationToId[location]]
     location.setUrl(url)
     location.setTwitterId(id)
     return location
    def get_folder_list(self):
        """
        Creates lists of folders by tree search from root specified by directory
        then sorts it and filters to leave only leaves from the tree,
        just the lowest children folders with audio files.

        :return:
        """

        for root, dirs, files in os.walk(self.directory):  # searching tree with root in 'directory'
            for name in dirs:                              # creating list of folders and subfolders
                self.locations_list.append(os.path.join(root, name))

        self.locations_list.sort()

        """
        when list of folders is sorted, parent directories
        can be discovered and deleted by checking if next
        position on the list contains the entirety of
        current position. Then marking parent directory
        for deletion
        """
        for index in range(len(self.locations_list) - 1):
            if self.locations_list[index + 1].startswith(self.locations_list[index]):
                self.locations_list[index] = 'clear'

        # erasing marked positions
        self.locations_list = list((filter(lambda element: element != 'clear', self.locations_list)))

        self.locations_list = list(Location(full_path=item,
                                            path_relative_to_playlist_location=get_path_relative_to_directory(item, self.directory)) for item in self.locations_list)
Exemple #24
0
 def get_terminal_string(self, indicies=False):
     # pragma: nocover
     ret = ""
     if indicies is True:
         ret += " X "
         for i in range(self.max_x):
             ret += "{:<2}".format(i)
         ret += "\n"
     for y in range(self.max_y):
         if indicies is True:
             if y == 0:
                 ret += "Y "
             else:
                 ret += "  "
         ret += "+-" * self.max_x + "+\n"
         if indicies is True:
             ret += "{:<2}".format(y)
         for x in range(self.max_x):
             currLoc = Location(x=x, y=y)
             piece = self.pieces.get_piece_at(currLoc)
             draw = " "
             if currLoc in KING_TILES:  # Really, a total hack
                 draw = chr(0x2318)
             if piece:
                 draw = piece.get_terminal_string()
             ret += "|" + draw
         ret += "|\n"
     if indicies is True:
         ret += "  "
     ret += "+-" * self.max_x + "+\n"
     return ret
Exemple #25
0
    def run(self):
        """ Method which shows a menu and allows the user to do inputs for selecting what action he or she wants to do """

        try:
            user_input = input(
                "Where do you wish to fight?"
            )  #The user decides where he or she wants to fight
            location = Location(user_input)
            while True:
                print("Welcome to the Star Wars battle simulator!")
                print("1. Add a duelist! ")
                print("2. List all duelists! ")
                print("3. Duel! ")
                print("0. Exit")
                menu_input = input("What do you wish to do?")
                if menu_input == "1":
                    location.add_duelists()
                elif menu_input == "2":
                    location.list_duelists()
                elif menu_input == "3":
                    duelist1 = location.choose_jedi()
                    duelist2 = location.choose_sith()
                    Duel(duelist1, duelist2).duel()
                elif menu_input == "0":
                    print("-" * 40)
                    print(" May the force be with you!")
                    print("-" * 40)
                    quit()

        except KeyboardInterrupt:  # removes the error text when the user uses keyboard shortcuts to exit the program
            print("\n", "-" * 40)
            print(" May the force be with you!")
            print("-" * 40)
            quit()
def CreateLocation(locationlist):
    locationname = input("\nEnter Location Name:")
    locationlatitude = float(input("\nEnter Location Latitude:"))
    locationlongitude = float(input("\nEnter Location Longitude:"))

    locationlist.append(
        Location(locationname, locationlatitude, locationlongitude, 0))
Exemple #27
0
 def fetchLocation(self):
     loc = Location(
         Helper.ReadConfig("model/location.cfg", "Location")['x'],
         Helper.ReadConfig("model/location.cfg", "Location")['y'],
         Helper.ReadConfig("model/location.cfg", "Location")['z'])
     #print ("Location x %d y %d z %d " %(loc.x, loc.y, loc.z))
     self.setLocation(loc)
Exemple #28
0
    def create_delayed_rules(self):
        for region_name, node, subrule_name in self.delayed_rules:
            region = self.world.get_region(region_name)
            event = Location(subrule_name,
                             type='Event',
                             parent=region,
                             internal=True)
            event.world = self.world

            self.current_spot = event
            # This could, in theory, create further subrules.
            access_rule = self.make_access_rule(self.visit(node))
            if access_rule is self.rule_cache.get('NameConstant(False)'):
                event.access_rule = None
                event.never = True
                logging.getLogger('').debug(
                    'Dropping unreachable delayed event: %s', event.name)
            else:
                if access_rule is self.rule_cache.get('NameConstant(True)'):
                    event.always = True
                event.set_rule(access_rule)
                region.locations.append(event)

                MakeEventItem(subrule_name, event)
        # Safeguard in case this is called multiple times per world
        self.delayed_rules.clear()
Exemple #29
0
 def processSingleDataPoint(self, latitude, longitude):
     location = Location(latitude, longitude)
     try:
         data = self._gmaps.reverse_geocode(
             (location.latitude, location.longitude))
         for addressItem in data[0]['address_components']:
             if 'street_number' in addressItem['types']:
                 location.number = addressItem['long_name']
             elif 'sublocality_level_1' in addressItem['types']:
                 location.district = addressItem['long_name']
             elif 'administrative_area_level_2' in addressItem['types']:
                 location.city = addressItem['long_name']
             elif 'country' in addressItem['types']:
                 country = Country(addressItem['long_name'])
             elif 'administrative_area_level_1' in addressItem['types']:
                 state = State(addressItem['long_name'],
                               addressItem['short_name'])
             elif 'postal_code' in addressItem['types']:
                 location.zipcode = addressItem['long_name']
             elif 'route' in addressItem['types']:
                 location.address = addressItem['long_name']
         state.country = country
         location.state = state
         return location
     except Exception as e:
         print(e)
         return []
Exemple #30
0
class Inset(object):
    width = BoundedFloat("width", minimum=0.0, maximum=1.0)
    height = BoundedFloat("height", minimum=0.0, maximum=1.0)
    location = Location("location")

    def __init__(self,
                 plot,
                 width=0.3,
                 height=0.3,
                 location="best",
                 padding=0.05):
        self.plot = plot

        self.width = width
        self.height = height
        self.location = location
        self.padding = padding

    def draw(self, fig, axes):
        if not BOOMSLANG_INSET_LOCATOR_LOADED:
            print >>sys.stderr, "Plotting insets requires " \
                "mpl_toolkits.axes_grid.inset_locator, which " \
                "your version of matplotlib doesn't appear to " \
                "have."
            sys.exit(1)

        insetAxes = mpl_toolkits.axes_grid.inset_locator.inset_axes(
            axes,
            width="%.2f%%" % (self.width * 100.0),
            height="%.2f%%" % (self.height * 100.0),
            loc=self.location)

        self.plot.drawPlot(fig, insetAxes)

        return insetAxes