Example #1
0
 def __init__(self, loader, parentFSM, doneEvent):
     self.parentFSM = parentFSM
     Place.__init__(self, loader, doneEvent)
     self.fsm = ClassicFSM('Street', [
         State(
             'start', self.enterStart, self.exitStart,
             ['walk', 'doorOut', 'teleportIn', 'tunnelOut', 'elevatorIn']),
         State('walk', self.enterWalk, self.exitWalk,
               ['stop', 'tunnelIn', 'shtickerBook', 'teleportOut']),
         State('shtickerBook', self.enterShtickerBook,
               self.exitShtickerBook, ['teleportOut', 'walk']),
         State('teleportOut', self.enterTeleportOut, self.exitTeleportOut,
               ['teleportIn', 'stop']),
         State('tunnelOut', self.enterTunnelOut, self.exitTunnelOut,
               ['walk']),
         State('tunnelIn', self.enterTunnelIn, self.exitTunnelIn, ['stop']),
         State('stop', self.enterStop, self.exitStop,
               ['walk', 'died', 'teleportOut', 'doorIn']),
         State('doorIn', self.enterDoorIn, self.exitDoorIn, ['stop']),
         State('doorOut', self.enterDoorOut, self.exitDoorOut, ['walk']),
         State('teleportIn', self.enterTeleportIn, self.exitTeleportIn,
               ['walk', 'stop']),
         State('elevatorIn', self.enterElevatorIn, self.exitElevatorIn,
               ['walk', 'stop']),
         State('final', self.enterFinal, self.exitFinal, ['final'])
     ], 'start', 'final')
def find_places_in_lyrics(lyrics, song_title, song_artist):
    st = StanfordNERTagger(
        '/Users/yuvalhering/Desktop/stanford-ner-2018-10-16/classifiers/english.all.3class.distsim.crf.ser.gz',
        '/Users/yuvalhering/Desktop/stanford-ner-2018-10-16/stanford-ner.jar',
        encoding='utf-8')
    tokenized_text = word_tokenize(lyrics)
    classified_text = st.tag(tokenized_text)
    ner_places = []
    for classification in classified_text:
        if classification[1] == 'LOCATION':
            ner_places.append(classification[0])
    extracted_places = list(set(ner_places))

    places = []

    for new_place_name in extracted_places:
        exists = False
        for place in places:
            if place.name == new_place_name:
                place.add_song(song_title, song_artist)
                exists = True
                break
        if not exists:
            p = Place(new_place_name)
            p.add_song(song_title, song_artist)
            places.append(p)

    json_places = []

    for p in places:
        place_dict = p.to_json()
        json_places.append(place_dict)

    with open('places.json', 'w', encoding='utf-8') as places_file:
        json.dump(json_places, places_file, indent=2)
 def test_removing_user(self):
     self.db.set_user_stage(1, Stage.START)
     self.db.add_place(1, Place("Good restaurant", 65.13, 66.14))
     self.db.add_place(1, Place("Very Good restaurant", 62.12, 66.14))
     self.assertTrue(self.db.has_user(1))
     self.db.reset_user(1)
     self.assertFalse(self.db.has_user(1))
Example #4
0
 def exit(self, vis=1):
     if vis:
         self.visibilityOff()
     self.loader.geom.reparentTo(hidden)
     self.loader.hood.stopSky()
     self.loader.music.stop()
     Place.exit(self)
Example #5
0
 def exit(self, vis = 1):
     if vis:
         self.visibilityOff()
     self.loader.geom.reparentTo(hidden)
     self.loader.hood.stopSky()
     self.loader.music.stop()
     Place.exit(self)
Example #6
0
def run_tests():
    """Test Place class."""

    # Test empty place (defaults)
    print("Test empty place:")
    default_place = Place("Townsville", "Australia", 0, "v")
    print(default_place)
    assert default_place.name == "Townsville"
    assert default_place.country == "Australia"
    assert default_place.priority == 0
    assert default_place.is_visited

    # Test initial-value place
    print("Test initial-value place:")
    new_place = Place("Malagar", "Spain", 2, False)
    # TODO: Write tests to show this initialisation works
    print(new_place)
    print(new_place.name)
    print(new_place.country)
    print(new_place.priority)
    print(new_place.visited)

    print(f"Dict: {new_place.__dict__}")




    # TODO: Add more tests, as appropriate, for each method
    print("Is important: {}".format(new_place.is_important()))
    print("Visited? {}".format(new_place.is_visited()))
Example #7
0
 def unload(self):
     self.parentFSM.getStateNamed('street').removeChild(self.fsm)
     del self.fsm
     del self.parentFSM
     self.enterZone(None)
     self.ignoreAll()
     Place.unload(self)
     return
 def test_places(self):
     self.db.add_place(1, Place("Good restaurant", 65.13, 66.14))
     self.db.add_place(1, Place("Very Good restaurant", 62.12, 66.14))
     places = self.db.get_places(1)
     self.assertIn(Place("Good restaurant", 65.13, 66.14), places)
     self.assertIn(Place("Very Good restaurant", 62.12, 66.14), places)
     self.assertEqual(self.db.get_place_by_name(1, "Good restaurant"),
                      Place("Good restaurant", 65.13, 66.14))
Example #9
0
 def unload(self):
     self.parentFSM.getStateNamed('street').removeChild(self.fsm)
     del self.fsm
     del self.parentFSM
     self.enterZone(None)
     self.ignoreAll()
     Place.unload(self)
     return
Example #10
0
    def addToken(self, token):
        assert token.__class__.__name__ == 'TimeToken'

        Place.addToken(self, token)
        if self.withoutTime:
            token.placeClocks = {}
            token.pclock = 0.0
        token.addPlaceClock(self, token.placeClocks.get(self))
        token.pclock = token.placeClocks[self]
 def enter(self, requestStatus, visibilityFlag=1):
     Place.enter(self)
     self.fsm.enterInitialState()
     base.playMusic(self.loader.music, volume=0.8, looping=1)
     self.loader.geom.reparentTo(render)
     if visibilityFlag:
         self.visibilityOn()
     self.loader.hood.startSky()
     self.enterZone(requestStatus['zoneId'])
     self.fsm.request(requestStatus['how'], [requestStatus])
Example #12
0
 def enter(self, requestStatus, visibilityFlag = 1):
     Place.enter(self)
     self.fsm.enterInitialState()
     base.playMusic(self.loader.music, volume=0.8, looping=1)
     self.loader.geom.reparentTo(render)
     if visibilityFlag:
         self.visibilityOn()
     self.loader.hood.startSky()
     self.enterZone(requestStatus['zoneId'])
     self.fsm.request(requestStatus['how'], [requestStatus])
    def load_places(self, filename):
        self.filename = filename
        with open(filename) as file:
            for line in file:
                parts = line.strip().split(',')
                place = Place(parts[0], parts[1], parts[2], parts[3])

                if parts[3] == 'v' or parts[3] == True:
                    place.is_visited = True
                else:
                    place.is_visited = False
                self.file_places.append(place)
def simulatedAnnealing(data, hotel, maxIterations = 10):
    finalBestOrdering = {}
    finalBestTime = 0
    hotelObj = Place(None, None, None, None, None)
    hotelObj.pos = hotel
    foodLists = {}
    entertainLists = {}

    #get all food places out
    #edited this block
    for key in data:
        foodLists[key], entertainLists[key] = [], []
        for attraction in data[key]:
            if attraction.category == 'FOOD_BEVERAGE':
                foodLists[key].append(attraction)
            else:
                entertainLists[key].append(attraction)

    for key in data:
        if len(data[key]) == 0:
            finalBestOrdering[key] = data[key]
            continue

        elif len(data[key]) == 1:
            finalBestOrdering[key] = data[key]
            finalBestTime += getTime(hotelObj, data[key][0]) + getTime(data[key][0], hotelObj)
            continue

        ##edited these 2 lines
        curr = [hotelObj] + getInitialOrdering(foodLists[key], entertainLists[key]) + [hotelObj]
        foodIndeces, entertainIndeces = getIndeces(curr)

        bestOrdering = curr
        bestTime = getTime(curr)

        for i in range(maxIterations):
            curr = randomizeOrdering(curr, foodIndeces, entertainIndeces)
            val = getTime(curr)
            if val < bestTime:
                bestTime = val
                bestOrdering = curr
            else:
                rand = random.random()
                if rand < temperature(i):
                    bestTime = val
                    bestOrdering = curr

        finalBestOrdering[key] =  bestOrdering[1:-1]
        finalBestTime += bestTime

    return finalBestOrdering, finalBestTime
Example #15
0
    def getAllTweets(dbm):
        """Regresa una lista de objetos Tweet con todos los elementos de la tabla"""
        allTweets = []
        if dbm is not None:
            res = dbm.runQuery(
                "SELECT tweetID, from_user_id, tweet, created_at, placeId, source, favorite_count, coordinates, userId, \
									   geo, lang, filter_level, in_reply_to_status_id_str FROM Tweets")
            for row in res:
                tweetRes = Tweet()
                tweetRes.set(tweetID=row[0],
                             from_user=User.searchUserById(dbm, row[1]),
                             tweet=row[2],
                             created_at=row[3],
                             place=Place.searchPlaceById(dbm, row[4]),
                             source=row[5],
                             favorite_count=row[6],
                             coordinates=row[7],
                             geo=row[9],
                             lang=row[10],
                             filter_level=row[11],
                             in_reply_to_status_id_str=row[12])
                tweetRes.dbm = dbm
                allTweets.append(tweetRes)
            return allTweets
        else:
            raise Exception("No DBM declared")
Example #16
0
 def searchTweetById(dbm, tweetID):
     """Regresa un objeto Tweet para la id buscada"""
     tweetRes = Tweet(dbm)
     if dbm is not None:
         res = dbm.runQuery(
             "SELECT tweetID, from_user_id, tweet, created_at, placeId, source, favorite_count, coordinates, userId, geo, lang, filter_level, in_reply_to_status_id_str FROM Tweets WHERE tweetID={}"
             .format(tweetID))
         try:
             if res is not None:
                 row = res[0]
                 tweetRes.set(tweetID=row[0],
                              from_user=User.searchUserById(dbm, row[1]),
                              tweet=row[2],
                              created_at=row[3],
                              place=Place.searchPlaceById(dbm, row[4]),
                              source=row[5],
                              favorite_count=row[6],
                              coordinates=row[7],
                              geo=row[9],
                              lang=row[10],
                              filter_level=row[11],
                              in_reply_to_status_id_str=row[12])
         except:
             pass
         return tweetRes
     else:
         raise Exception("No DBM declared")
Example #17
0
    def __init__(self, config_places, config_crowd, config_isolation,
                 config_preventions, medicalModel):
        self.config_places = config_places
        self.config_crowd = config_crowd
        self.config_isolation = dict(config_isolation.items())
        self.enableIsolation = self.config_isolation['enable']
        if not self.enableIsolation:
            self.config_isolation['agreeIsolationRate'] = 0
        self.config_preventions = config_preventions
        self.medicalModel = medicalModel
        self.flexPlaces = {}
        self.day = 0

        # step 1: create citizens
        self.crowd = []
        for config in config_crowd:
            for i in range(config['number']):
                healthStage = self.medicalModel.initIllnessStage if i < config[
                    'patient'] else self.medicalModel.healthStage
                prevention = [
                    preventionType
                    for preventionType, config in config_preventions.items()
                    if random.random() < config['applicationRatio']
                ]
                newPerson = Person(
                    config, healthStage, prevention,
                    random.random() < config_isolation['agreeIsolationRate'],
                    config_isolation['selfDiscipline'])
                self.crowd.append(newPerson)
        self.population = self.crowd.copy()
        random.shuffle(self.crowd)

        # step 2: create (fixed) locations
        self.fixedPlaces = {}
        for config in config_places:
            if config['number'] is None: continue
            self.fixedPlaces[config['type']] = [
                Place(config) for i in range(config['number'])
            ]

        # step 3: randomly link people with fixed locations according to the 'fixedActivity'
        allPossibleDefaultPlaceTypes = [
            person.defaultActivity for person in self.crowd
        ]
        allPossibleFixedPlaceTypes = itertools.chain(
            *[person.fixedActivityTypes() for person in self.crowd],
            allPossibleDefaultPlaceTypes)
        allPossibleFixedPlaceTypes = set(allPossibleFixedPlaceTypes)
        for placeType in allPossibleFixedPlaceTypes:
            people = [
                person for person in self.crowd
                if placeType in person.fixedActivityTypes()
                or placeType == person.defaultActivity
            ]
            places = [place for place in self.fixedPlaces[placeType]]
            # randomly link the remaining people with places
            allocation = self.randomlyAllocate(people, places)
            for place, person in allocation:
                person.linkedPlace[placeType] = place
                place.linkedPeople.append(person)
Example #18
0
def CrossStreet(CrossStreetName=None, StreetName=None, StreetType=None,
                City=None, State=None, Zip=None):
    try:
        return Place(city=City, state=State, zip=Zip, street_name=StreetName,
                     street_type=StreetType, cross_street=CrossStreetName)
    except ValueError:
        return None
Example #19
0
def Add_New_Place():
    Location = Location_Error_Checking()
    Country = Country_Error_Checking()
    Priority_Input = Integer_Error_Checking()
    print(
        f"{Location} in {Country} (priority {Priority_Input}) added to Travel Tracker"
    )
    file_entry.insert(0, Place(Location, Country, Priority_Input, 'n'))
Example #20
0
def add_place_location(message):
    print(f"Adding place location with {message.chat.id}")
    lat, lon = message.location.latitude, message.location.longitude
    name = db.get_staged_place_name(message.chat.id)
    db.add_place(message.chat.id, Place(name, lat, lon))
    db.clean_staged_place_name(message.chat.id)
    memorizer.send_message(message.chat.id, "Новое место успешно добавлено")
    db.set_user_stage(message.chat.id, Stage.START)
def simulatedAnnealing(data, hotel, maxIterations=100):
    finalBestOrdering = {}
    finalBestTime = 0
    hotelObj = Place(None, None, None, None)
    hotelObj.pos = hotel

    for key in data:
        if len(data[key]) == 0:
            finalBestOrdering[key] = data[key]
            continue

        elif len(data[key]) == 1:
            finalBestOrdering[key] = data[key]
            finalBestTime += getTime(hotelObj, data[key][0]) + getTime(
                data[key][0], hotelObj)
            continue

        curr = [hotelObj] + data[key] + [hotelObj]
        #numAttractions = len(data[key])

        # for _ in range(numAttractions):
        # 	rand = random.randint(0, len(data[key]))
        # 	curr.append(data[key][rand])
        # 	data[key].remove(data[key][rand])

        #curr.append(hotelObj)
        bestOrdering = curr
        bestTime = getTime(curr)

        for i in range(maxIterations):
            curr = randomizeOrdering(curr)
            val = getTime(curr)
            if val < bestTime:
                bestTime = val
                bestOrdering = curr
            else:
                rand = random.random()
                if rand < temperature(i):
                    bestTime = val
                    bestOrdering = curr

        finalBestOrdering[key] = bestOrdering[1:-1]
        finalBestTime += bestTime
    return finalBestOrdering, finalBestTime
Example #22
0
 def generate_map(self):
     #for x in range(0, 20):
     #    for y in range(0, 20):
     #        if(x == 1 and y == 1):
     #            self.map_locations[x][y] = Place(1)
     #        else:
     #            self.map_locations[x][y] = Place(0)
     for x in range(0, 19):
         for y in range(0, 13):
             self.map_locations[x][y] = Place(self.temp_map[y][x], self, x, y)
Example #23
0
def BasicAddress(StreetNumber=None, UnitLetter=None, StreetDirection=None,
                 StreetName=None, StreetType=None, City=None,
                 State=None, Zip=None):
    try:
        return Place(city=City, state=State, zip=Zip, street_number=StreetNumber,
                     street_name=StreetName, street_direction=StreetDirection,
                     street_type=StreetType,
                     unit_letter=UnitLetter)
    except ValueError:
        return None
 def filter_by_popularity(self, center, attractions):
     '''
         Filters attractions using knapsack.
         weights = a weighted average of estimated time spent at location and distance from center
         values = a weighted average of num checkins and overall star rating
     '''
     places, weights, values = [], [], []
     for attraction in attractions:
         place = \
             Place(attraction["name"], \
                 attraction["location"]["latitude"], \
                 attraction["location"]["longitude"], \
                 attraction)
         val = place.calculate_value(attraction["checkins"],
                                     attraction["overall_star_rating"])
         weight = place.calculate_weight(center)
         values.append(val)
         weights.append(weight)
         places.append(place)
     return self.knapsack(5000000, weights, values, len(places), places)
Example #25
0
 def movePeople(self, hourId):
     flexPlaceBuffers = {}
     for person in self.crowd:
         if hourId > 0 and person.schedule[hourId] == person.schedule[hourId
                                                                      - 1]:
             continue  # don't need to move the person
         if person.currentPlace is not None:
             person.currentPlace.removePerson(person)
         activity, type = person.schedule[hourId]
         if type == 'isolating':
             person.currentPlace = None
         elif type == 'fixed':
             newPlace = person.linkedPlace[activity]
             newPlace.addPerson(person)
             person.currentPlace = newPlace
         else:  # type==flex
             buffer = flexPlaceBuffers.setdefault(activity, [])
             buffer.append(person)
     pass
     for placeType, people in flexPlaceBuffers.items():
         if placeType in self.fixedPlaces:
             # if people visit a fixed place as a flex activity, just put them in existing fixed places. (ignore the place capacity)
             currentPlaces = self.fixedPlaces[placeType]
             allocation = self.randomlyAllocate(people, currentPlaces)
         else:
             # people visit flex places
             currentPlaces = self.flexPlaces.setdefault(placeType, [])
             # remore the empty places
             currentPlaces = [
                 place for place in currentPlaces
                 if len(place.currentPeople) == 0
             ]
             self.flexPlaces[placeType] = currentPlaces
             placeConfig = [
                 placeConfig for placeConfig in self.config_places
                 if placeConfig['type'] == placeType
             ][0]
             singleCapacity = placeConfig['capacity']
             currentPopulation = sum(
                 [len(place.currentPeople)
                  for place in currentPlaces]) + len(people)
             number_newPlaceRequired = math.ceil(
                 currentPopulation /
                 (singleCapacity * 0.75)) - len(currentPlaces)
             if number_newPlaceRequired > 0:
                 # create new places
                 currentPlaces += [
                     Place(placeConfig)
                     for _ in range(number_newPlaceRequired)
                 ]
             allocation = self.randomlyAllocate(people, currentPlaces)
         for place, person in allocation:
             place.addPerson(person)
             person.currentPlace = place
 def test_removing_place(self):
     self.db.add_place(1, Place("Good restaurant", 65.13, 66.14))
     self.db.add_place(1, Place("Very Good restaurant", 62.12, 66.14))
     self.db.add_place(2, Place("Very Good restaurant", 62.12, 66.14))
     self.db.remove_place(1, Place("Very Good restaurant", 62.12, 66.14))
     places = self.db.get_places(1)
     self.assertIn(Place("Good restaurant", 65.13, 66.14), places)
     self.assertNotIn(Place("Very Good restaurant", 62.12, 66.14), places)
     self.assertIn(Place("Very Good restaurant", 62.12, 66.14),
                   self.db.get_places(2))
Example #27
0
 def __init__(self, **kwargs):
     pygame.init()
     self.screen_info = pygame.display.Info()
     self.screen_size = kwargs.get("screen_size", (0, 0))
     self.resizable = kwargs.get("resizable", True)
     if self.resizable:
         self.screen = pygame.display.set_mode(self.screen_size, RESIZABLE)
     else:
         self.screen = pygame.display.set_mode(self.screen_size)
     self.rect = Rect((0, 0), self.screen.get_size())
     self.layout = kwargs.get("layout", None)
     if self.layout == "grid":
         Grid.__init__(self)
         self.layout = Grid
     elif self.layout == "flow":
         Flow.__init__(self)
         self.layout = Flow
     elif self.layout == "place" or self.layout is None:
         Place.__init__(self)
         self.layout = Place
     self.fullscreen = kwargs.get("fullscreen", False)
     self.last_screen_size = self.rect.size
Example #28
0
def simulatedAnnealing(data, hotel, maxIterations=10):
    finalBestOrdering = {}
    finalBestTime = 0
    hotelObj = Place(None, None, None, None, None)
    hotelObj.pos = hotel

    for key in data:
        if len(data[key]) == 0:
            finalBestOrdering[key] = data[key]
            continue

        elif len(data[key]) == 1:
            finalBestOrdering[key] = data[key]
            finalBestTime += getTime([hotelObj] +
                                     [data[key][0]]) + getTime([data[key][0]] +
                                                               [hotelObj])
            continue

        curr = [hotelObj] + data[key] + [hotelObj]

        bestOrdering = curr
        bestTime = getTime(curr)

        for i in range(maxIterations):
            curr = randomizeOrdering(curr)
            val = getTime(curr)
            if val < bestTime:
                bestTime = val
                bestOrdering = curr
            else:
                rand = random.random()
                if rand < temperature(i):
                    bestTime = val
                    bestOrdering = curr

        finalBestOrdering[key] = bestOrdering[1:-1]
        finalBestTime += bestTime
    return finalBestOrdering, finalBestTime
Example #29
0
 def __init__(self, loader, parentFSM, doneEvent):
     self.parentFSM = parentFSM
     Place.__init__(self, loader, doneEvent)
     self.fsm = ClassicFSM('Street', [State('start', self.enterStart, self.exitStart, ['walk',
       'doorOut',
       'teleportIn',
       'tunnelOut']),
      State('walk', self.enterWalk, self.exitWalk, ['stop',
       'tunnelIn',
       'shtickerBook',
       'teleportOut']),
      State('shtickerBook', self.enterShtickerBook, self.exitShtickerBook, ['teleportOut', 'walk']),
      State('teleportOut', self.enterTeleportOut, self.exitTeleportOut, ['teleportIn', 'stop']),
      State('tunnelOut', self.enterTunnelOut, self.exitTunnelOut, ['walk']),
      State('tunnelIn', self.enterTunnelIn, self.exitTunnelIn, ['stop']),
      State('stop', self.enterStop, self.exitStop, ['walk',
       'died',
       'teleportOut',
       'doorIn']),
      State('doorIn', self.enterDoorIn, self.exitDoorIn, ['stop']),
      State('doorOut', self.enterDoorOut, self.exitDoorOut, ['walk']),
      State('teleportIn', self.enterTeleportIn, self.exitTeleportIn, ['walk', 'stop']),
      State('final', self.enterFinal, self.exitFinal, ['final'])], 'start', 'final')
Example #30
0
def run_tests():
    """Test PlaceCollection class."""

    # Test empty PlaceCollection (defaults)
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.file_places  # an empty list is considered False

    # Test loading places
    print("Test loading places:")
    place_collection.load_places('places.csv')
    print(place_collection)
    assert place_collection.file_places  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new Place with values
    print("Test adding new place:")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)

    # Test sorting places
    print("Test sorting - priority:")
    place_collection.sort("priority")
    print(place_collection)
    # TODO: Add more sorting tests

    place_collection.sort("country")
    print(place_collection)
    # TODO: Test saving places (check CSV file manually to see results)

    place_collection.save_places()
    print(place_collection)
    place_collection.add_place(Place("Townsville", "Australia", 7, True))
    print(f"Updated: {place_collection}")

    # TODO: Add more tests, as appropriate, for each method
    print(place_collection.total_unvisited_places())
Example #31
0
 def getGeo(s):
     s.lat = None
     s.lon = None
     s.place_id = None
     s.place = None
     s.geo_type = "not"
     if 'place' in s.json and s.json['place'] is not None:
         s.geo_type = 'place'
         s.place_id = s.json['place']['id']
         s.place = Place(s.place_id)
         s.place.loadJSON(s.json['place'])
     if 'coordinates' in s.json and s.json['coordinates'] is not None:
         s.geo_type = 'precise'
         s.lat = s.json['coordinates']['coordinates'][1]
         s.lon = s.json['coordinates']['coordinates'][0]
    def query_potential_locations(self, center_lat, center_lon, interests = ["FOOD_BEVERAGE"], categories = ['ARTS_ENTERTAINMENT','SHOPPING_RETAIL'], num_locations=50, dist=500):
        '''
            Queries num_locations near the center (lat, lon) using Facebook Places API_KEY
        '''

        center = center_lat + ", " + center_lon
        API_KEY = "MyhhJX525dvRwSUWpKHNOTKDjJaK59WX"
        access_token = "2210087485905915|vSCL_c4XqrU_ABMFWOdzbyhh_jk"
        FB_URL = "https://graph.facebook.com/search?type=place"
        cat = 'FOOD_BEVERAGE'
        FB_PARAMS = {'categories' : str([cat]), \
            'fields': ['name,checkins,overall_star_rating,location, category_list, price_range'], \
            'center': center, \
            'distance': 2000, \
            'access_token': access_token}
        res = requests.get(url = FB_URL, params = FB_PARAMS)
        all_locations = res.json()['data']
        all_locations.sort(key = lambda place: -place['checkins'])
        attractions_with_rating = [a for a in all_locations if 'overall_star_rating' in a]
        places = []
        attractions = []
        price_mapping = {"$": 10, "$$": 20, "$$$": 40, "$$$$": 200, "Unspecified": 15}

        for category in categories:
            FB_PARAMS = {'categories' : str([category]), \
            'fields': ['name,checkins,overall_star_rating,location, price_range'], \
            'center': center, \
            'distance': 2000, \
            'access_token': access_token}
            res = requests.get(url = FB_URL, params = FB_PARAMS)
            all_locations = res.json()['data']
            all_locations.sort(key = lambda place: -place['checkins'])
            attractions_with_rating = [a for a in all_locations if 'overall_star_rating' in a]
            for attraction in attractions_with_rating:
                if 'price_range' in attraction.keys():
                    price = price_mapping[str(attraction['price_range'])]
                else:
                    price = 10
                place = \
                        Place(attraction["name"], \
                              attraction["location"]["latitude"], \
                              attraction["location"]["longitude"], \
                              attraction, attraction["checkins"], \
                              attraction["overall_star_rating"], category, price)
                places.append(place)

        filtered_places = self.filter_user_interests(interests, places) #need to get user input
        return filtered_places[:num_locations]
Example #33
0
	def searchTweetById(dbm, tweetID):
		"""Regresa un objeto Tweet para la id buscada"""
		tweetRes = Tweet(dbm)
		if dbm is not None:
			res = dbm.runQuery("SELECT tweetID, from_user_id, tweet, created_at, placeId, source, favorite_count, coordinates, userId, geo, lang, filter_level, in_reply_to_status_id_str FROM Tweets WHERE tweetID={}".format(tweetID))
			try:
				if res is not None:
					row = res[0]
					tweetRes.set(tweetID = row[0], from_user = User.searchUserById(dbm, row[1]), tweet = row[2], created_at = row[3],
								 place = Place.searchPlaceById(dbm, row[4]), source = row[5], favorite_count = row[6], coordinates = row[7], 
							 	 geo = row[9], lang = row[10], filter_level = row[11], in_reply_to_status_id_str = row[12])
			except:
				pass
			return tweetRes
		else:
			raise Exception("No DBM declared")
Example #34
0
    def press_add(self, name_input, country_input, priority_input):
        # if any text_input boxes on app.kv are empty, display message
        if self.root.ids.name_input.text == '' or self.root.ids.country_input.text == '' or self.root.ids.priority_input.text == '':
            self.root.ids.location_clicked_status.text = "All fields must be completed"
        # if priority input is less than 0, display message
        elif int(self.root.ids.priority_input.text) < 0:
            self.root.ids.location_clicked_status.text = "Priority must be > 0"
        else:
            # append new entry to main list and create widget
            place = Place(name_input, country_input, priority_input, False)
            location_button = Button(text=str(place))
            location_button.place = place
            location_button.bind(on_release=self.press_entry)

            self.root.ids.locations_box.add_widget(location_button)
            self.place_collection.add_place(place)
Example #35
0
	def getAllTweets(dbm):
		"""Regresa una lista de objetos Tweet con todos los elementos de la tabla"""
		allTweets = []
		if dbm is not None:
			res = dbm.runQuery("SELECT tweetID, from_user_id, tweet, created_at, placeId, source, favorite_count, coordinates, userId, \
									   geo, lang, filter_level, in_reply_to_status_id_str FROM Tweets")
			for row in res:
				tweetRes = Tweet()
				tweetRes.set(tweetID = row[0], from_user = User.searchUserById(dbm, row[1]), tweet = row[2], created_at = row[3],
							 place = Place.searchPlaceById(dbm, row[4]), source = row[5], favorite_count = row[6], coordinates = row[7], 
						 	 geo = row[9], lang = row[10], filter_level = row[11], in_reply_to_status_id_str = row[12])
				tweetRes.dbm = dbm
				allTweets.append(tweetRes)
			return allTweets
		else:
			raise Exception("No DBM declared")
Example #36
0
def save():
    nazwa = nazwa_input.get()
    opis = opis_input.get(1.0, END)
    miasto = miasto_input.get()
    adres = adres_input.get()
    fb = fb_input.get()
    ig = ig_input.get()
    email = email_input.get()
    tel = tel_input.get()
    web = web_input.get()

    if fb and nazwa and miasto and adres:
        place = Place(nazwa, opis, miasto, adres, fb, ig, email, tel, web)
        Ins.insert(place, inserter)
    else:
        fb_input.delete(0, END)
        fb_input.insert(INSERT, "Brak inforamcji.")
    def init_graph(self):
        # read venue (node) data
        # node_data = {}
        self.pos_dict = {
        }  # will be used to draw the nodes in the graph with geographic topology
        for l in open('./shared_data/newyork_anon_locationData_newcrawl.txt'):
            splits = l.split('*;*')
            venue_id = int(splits[0])
            venue_info = eval(splits[1])

            # add place to graph
            self.NYC_graph.add_node(venue_id)
            self.NYC_graph.nodes[venue_id][
                'info'] = venue_info  # (40.760265, -73.989105, 'Italian', '217', '291', 'Ristorante Da Rosina')

            # initialise placee and within place, population information
            self.places[venue_id] = Place(venue_info)

            # this will be used for drawing the network
            self.pos_dict[venue_id] = (venue_info[1], venue_info[0])
Example #38
0
 def gen_specified_locations(self, user_locs):
     """
         Generate data for a list of user specified locations of interests, which will be combined
         with the generic list of attractions. Will be passed into k-means.
     """
     API_KEY = "AIzaSyC2Sixwd61MWgbL6qxCrX1JTAEotj5RWDs"
     URL = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?"  #change output and parameters
     fields = 'name,rating,geometry,formatted_address'
     places = []
     for l in user_locs:
         r = requests.get(URL + 'input=' + l + \
                             '&inputtype=textquery' + '&fields=' + fields + \
                             '&key=' + API_KEY)
         attraction = r.json()['candidates'][0]
         place = \
             Place(attraction["name"], \
                 attraction["geometry"]["location"]["lat"], \
                 attraction["geometry"]["location"]["lng"], \
                   attraction, attraction['formatted_address'])
         places.append(place)
     return places
Example #39
0
 def __init__(self, name='no name', logger=logging, time=0.0, withoutTime=False, withoutPriority=False, tokName=None,
              exit=False):
     TimeNode.__init__(name=name, logger=logger, time=time)
     Place.__init__(self, name=name, logger=logger, withoutPriority=withoutPriority, tokName=tokName, exit=exit)
     self.withoutTime = withoutTime
     """ If True, the token arriving on this place have to reinitialize
Example #40
0
 def load(self):
     Place.load(self)
     self.parentFSM.getStateNamed('street').addChild(self.fsm)
Example #41
0
 def __init__(self, parent, **kwargs):
     Widget.__init__(parent)
     Place.__init__()
Example #42
0
from Place import Place
from Being import Being as Being
from Atom import Atom as Atom
from InternalMind import InternalMind as InternalMind
from ExternalMind import ExternalMind as ExternalMind
from Eye import Eye as Eye

# Being : nom, dictin, size, elasticity, visibility, opacity, mind
        
world = Place('world', {
    'dark room': Place('dark room', {
        'goblin': Being('goblin', {
            'body': Atom("body", 5, 5, 0, 5, 0)
        }, 5, 20, 10, 10, InternalMind(1)),
        'cell': Place('cell', {
            'rat': Being('rat', {'body': Atom("body", 5, 5, 0, 5, 0)}, 5, 20, 10, 10,
                         InternalMind(1)),
            'you': Being('you', {'eye': Eye('eye', 1, 1, 0, 1, 0),
                                 'body': Atom("body", 9, 10, 1, 10, 1)}, 10, 20, 10, 7,
                         ExternalMind()),
            'rock': Atom('rock', 1, 10, 1, 10, 10)
        }, 100, 10, 0)
    }, 300, 10, 10)
}, 1000000000000, 0, 0)

you = world.lookfor('you')
while you.act(world) != 'sleep':
    pass