Esempio n. 1
0
def insert_route_data(route_number, route_data):
    route = Route(routeNumber=route_number)
    route.put()

    for record in route_data:
        road_name = record[0]

        #check if road exist if not create one
        road = Road.get_or_insert(road_name, name=road_name)

        #store the location
        location = Location(node=record[2],
                            lat=float(record[3]),
                            lng=float(record[4]),
                            placeId=record[5])
        location.put()

        #map location to the route
        route_location = RouteLocation(nodeIndex=int(record[1]),
                                       route=route.key,
                                       road=road.key,
                                       node=location.key)
        route_location.put()

    return route.key
Esempio n. 2
0
 def resolve_Locations(self, args, context, info):
     if args and 'search' in args:
         matches = []
         for l in Location.query():
             if args['search'].lower() in l.node.lower():
                 matches.append(l)
         return matches
     return Location.query()
Esempio n. 3
0
def test_find_neightbour_nodes():
    nodes = Location.query()

    node = Location.query(Location.node == "Kottawa").get()
    if len(route_processor.find_neighbouring_nodes(node)) > 0:
        return True

    return False
Esempio n. 4
0
def main():

    start = Location(100, 200)
    end = Location(200, 200)

    anna = HouseWife("Anna", end, 1000, "0")

    ant25 = Plane("ANT25", 10000, 10)
    ant20 = Plane("ant20", 5000, 10)

    inter_city = Train("InterCity", 15)
    chs2 = Train("ChS2", 15)

    sprinter = Bus("Sprinter", 200)
    double_decker = Bus("Double Decker", 100)

    delivery_date = Date(2019, 4, 21)

    urk_air_transport = PlaneDelivery("SlavaUkraini", 100, 1220, start, end,
                                      ant25, delivery_date, anna)
    pl_air_transport = PlaneDelivery("SmertVorogam", 100, 200, start, end,
                                     ant20, Date(2019, 4, 22), anna)

    urk_railway = TrainDelivery("UkrRailway", 1000, 120, start, end,
                                inter_city, Date(2020, 4, 21), anna)
    pl_railway = TrainDelivery("PlRailway", 100, 109, start, end, chs2,
                               Date(2019, 5, 27), anna)

    fed_ex = BusDelivery("FedEx", 100, 1000, start, end, sprinter,
                         Date(2025, 4, 21), anna)
    dhl = BusDelivery("dhl", 200, 57, start, end, double_decker,
                      Date(2030, 1, 2), anna)

    taras_bulba = Book("Taras Bulba", 500, 400, "Nikolya Gogol",
                       urk_air_transport)
    kobzar = Book("Kobzar", 700, 1000, "Taras Shevchenko", pl_air_transport)
    garry_potter = Book("Garry Potter", 100, 250, "Joah Rouling", urk_railway)

    pro_retina_13 = MacBook("Pro Retina 13", 1250, 13, 13, urk_railway)
    pro_retina_15 = MacBook("Pro Retina 15", 2250, 15, 17, fed_ex)
    air_retina_13 = MacBook("Air Retina 13", 1200, 13, 13, pl_railway)

    g403 = ComputerMouse("Logitech g403", 60, 5, 2, dhl)
    netscroll120 = ComputerMouse("Genius netscroll 120", 5, 2, 1, dhl)
    razer_champion = ComputerMouse("Razor Champion", 100, 10, 2, dhl)

    marta = HouseWife("Marta", end, 1000, "BOOKS")
    nina = HouseWife("Nina", end, 100, "PANS")

    amazon_catalog = [taras_bulba, kobzar, pro_retina_13, g403, netscroll120]

    amazon_clients = [marta, nina]

    amazon = Shop("Amazon", "amazon.com", amazon_catalog)

    amazon_manager = ShopManager(amazon_clients, amazon)
Esempio n. 5
0
def test_path_search():
    start_node = Location.query(Location.node == "Pettah").get()
    end_node = Location.query(Location.node == "Kottawa").get()

    query = RouteQuery(fromNode=start_node.key, toNode=end_node.key)
    query.put()

    route_processor.path_search(start_node, end_node, [], 0, 0, [start_node],
                                [], query.key)

    results = RouteQueryResponse.query(
        RouteQueryResponse.routeQuery == query.key).get()
    if results:
        return True

    return False
Esempio n. 6
0
 def __init__(self, name, x, y):
     self.name = name
     self.location = Location(x, y)
     self.shots_left = 5
     self.mines = 1
     self.has_treasure = False
     self.alive = True
Esempio n. 7
0
def create_location(region, city, street, building_number, adress_index):
    session.commit()
    location = Location(region, city, street, building_number, adress_index)
    session.add(location)
    session.commit()

    return location
Esempio n. 8
0
    def process(self, message):
        message_info = self.get_message_info(message)
        connection = self.connection.get_connection()
        c = connection.cursor()
        c.execute(
            Location.get_find_by_user_id_query(
                message_info.get_user().get_id()))
        locations = c.fetchall()
        self.connection.close_connection()

        chat_id = message_info.get_chat().get_id()

        if len(locations) > 0:
            for location in locations:
                self.bot.send_message(chat_id, location[1])
                if location[2] != 'None' and location[2] != '':
                    image = open(location[2], 'rb')

                    self.bot.send_photo(chat_id,
                                        image,
                                        caption="Photo '{}'".format(
                                            location[1]))

                latitude = int(location[3])
                longtitude = int(location[4])

                if latitude > 0 or longtitude > 0:
                    self.bot.send_location(chat_id, latitude, longtitude)
        else:
            self.bot.send_message(
                chat_id,
                'Locations list is empty. You can /add your first location.')
Esempio n. 9
0
    def initilise_locations(self):
        f = open("game_info/locations.txt", 'r')
        name, description, loc_objects, destinations = (None, ) * 4

        for line in f:

            if name is None:
                name = self.match_object("name:", line)

            if description is None:
                description = self.match_object("description:", line)

            if loc_objects is None:
                loc_objects = self.match_list("objects:", line)

            if destinations is None:
                destinationsObj = match("destinations:", line)
                if destinationsObj is not None:
                    destinations = [
                        Destination(dest.group(1), dest.group(2)) for dest in
                        finditer(r"\"(.+?)\"\[(.+?)\]", line[14:len(line) - 1])
                    ]

            if match("--", line):
                objects_list = [self.objects[i]
                                for i in loc_objects] if loc_objects else None
                self.locations[name] = Location(name, description,
                                                objects_list, destinations)
                name, description, loc_objects, destinations = (None, ) * 4

        f.close()
Esempio n. 10
0
 def read(self):
     rows = Repository().read(self.filename)
     locations = [
         Location(row['country'], row['airport'], row['phone'],
                  row['hours'], row['id']) for row in rows
     ]
     return locations
Esempio n. 11
0
 def post(self):
     location_kwargs = {
         'name': self.request.get('name'),
         'location_type': self.request.get('location-type'),
     }
     new_location = Location.create_location(**location_kwargs)
     response = {'success': True, 'goto_url': '/account/location/{0}'.format(new_location.key.id())}
     self.response.write(json.dumps(response))
Esempio n. 12
0
def show(location_id):
    schema = LocationSchema()
    location = Location.get(id=location_id)

    if not location:
        abort(404)

    return schema.dumps(location)
 def getLocationByIds(self):
     """Returns JSON object of locations"""
     data = request.get_json(force=True)
     locations = []
     for x in data:
         location = Location.findLocationById(x)
         locations.append(location)
     return list(map(lambda x: x.json(), locations))
 def removeLocation(self, id):
     """Returns JSON object of deleted location"""
     location = Location.findLocationById(id)
     if location:
         location.delete()
         return {"message": "The location with id '{}' is deleted!".format(id)}
     else:
         return "The Location does not exist!"
Esempio n. 15
0
 def __init__(self,*places):
     
     self.id=random.randint(0,100)
     self.places=[]
     for p in places:
         l = Location(p)
         self.places.append(l)
     if len(places) > 0:
         self.details=self.get_summary()
Esempio n. 16
0
def delete(location_id):
    location = Location.get(id=location_id)

    if not location:
        abort(404)

    location.delete()
    db.commit()

    return '', 204
Esempio n. 17
0
    def resolve_Query(self, args, context, info):
        if args and len(args) == 2:
            from_node = Location.get_by_id(long(args['fromNode']))
            to_node = Location.get_by_id(long(args['toNode']))

            if (not from_node) or (not to_node):
                return None

            query = RouteQuery(
                fromNode = from_node.key,
                toNode = to_node.key
            )
            query.put()


            route_processor.path_search(from_node,to_node,[],0,0,[from_node],[],query.key)

            #find responses
            # print RouteQueryResponse.query(RouteQueryResponse.routeQuery==query.key).get()
            return RouteQueryResponse.query(RouteQueryResponse.routeQuery==query.key)
Esempio n. 18
0
 def process(self, message):
     message_info = self.get_message_info(message)
     connection = self.connection.get_connection()
     c = connection.cursor()
     c.execute(
         Location.get_delete_by_user_id_query(
             message_info.get_user().get_id()))
     connection.commit()
     self.connection.close_connection()
     self.bot.send_message(
         self.get_message_info(message).get_chat().get_id(),
         'Your list was successfully clean. You can /add new location.')
Esempio n. 19
0
 def post(self):
     company_id = int(self.request.get('company-id'))
     location_kwargs = {
         'company': Company.get_by_id(company_id),
         'name': self.request.get('name'),
         'country': self.request.get('country'),
         'state': self.request.get('state'),
         'city': self.request.get('city'),
         'location_type': self.request.get('location-type'),
         'adult_ads_restricted': bool(int(self.request.get('adult-ads-restricted'))),
         'adult_oriented': bool(int(self.request.get('adult-oriented')))
     }
     new_location = Location.create_location(**location_kwargs)
Esempio n. 20
0
def create():
    schema = LocationSchema()

    try:
        data = schema.load(request.get_json())
        location = Location(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    return schema.dumps(location), 201
Esempio n. 21
0
 def __add__(self,other):
     
     if isinstance(other,str):
         newLoc = Location(other)  
         self.places= self.places + [newLoc]
         self.details=self.get_summary()
         return self         
         #return Trip.fromPlaces(id=self.id,places=self.places + [newLoc])
     elif isinstance(other,Trip):
         if self.places[-1].addr == other.places[0].addr:
             newplaces= self.places[:]+other.places[1:]
             #print(newplaces)
             return Trip.fromPlaces(places=newplaces)
         else:
             raise NameError('Trips cannot be combined.')
Esempio n. 22
0
def update(location_id):
    schema = LocationSchema()
    location = Location.get(id=location_id)

    if not location:
        abort(404)

    try:
        data = schema.load(request.get_json())
        location.set(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    return schema.dumps(location)
 def addLocation(self, id):
     """Returns JSON object of the created location"""
     try:
         data = LocationService.parser.parse_args()
         location = Location.findLocationById(id)
         if location:
             return "The location already exists!"
         else:
             location = Location(id, data["code"], data["description"], data["x_coor"], data["y_coor"], data["waterschap_id"], data["watertype_id"], data["watertype_krw_id"])
             location.save()
             return location.json()
     except exc.IntegrityError:
         return "The code already exists!"
Esempio n. 24
0
 def get(self, location_id):
     location = Location.get_by_id(int(location_id))
     self.template_values['location'] = location
     self.response.out.write("boop")
Esempio n. 25
0
 def get_location_details(self, location_id):
     location = Location(self.__db, location_id)
     if location.exists:
         return [location.name, location.address, location.email]
     else:
         return False
Esempio n. 26
0
 def reload(self):
     self.__previous_state = None
     self.__location = Location()
Esempio n. 27
0
        image='https://pbs.twimg.com/profile_images/1095848308361302021/RZrejye3.jpg'
    )
    elle = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        image='https://media.licdn.com/dms/image/C5603AQHX0omHmh7fWQ/profile-displayphoto-shrink_800_800/0?e=1565222400&v=beta&t=5pP3yPblEgMO-XljaArDpTJJblOqk0dy5L28S3qbWGQ'
    )
    hugo = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        image='https://media.licdn.com/dms/image/C4E03AQFsE6plNPRwsg/profile-displayphoto-shrink_800_800/0?e=1565222400&v=beta&t=6TGy4Oli2Yc5LRLDCPKuuk850vNQiEUnyVW-g08ocjc'
    )

    amsterdam = Location(name='Amsterdam')
    paris = Location(name='Paris')
    kansas = Location(name='Kansas')
    colombia = Location(name='Colombia')
    austria = Location(name='Austria')
    azerbaijan = Location(name='Azerbaijan')
    belgium = Location(name='Belgium')
    bhutan = Location(name='Bhutan')
    chile = Location(name='Chile')
    copenhagen = Location(name='Copenhagen')
    palestine = Location(name='Palestine')
    london = Location(name='London')
    taiga = Location(name='Taiga')
    oxford = Location(name='Oxford')
    edinburgh = Location(name='Edinburgh')
Esempio n. 28
0
with db_session():
    #User
    schema = UserSchema()
    Kristian = User(username='******',
                    email='*****@*****.**',
                    password_hash=schema.generate_hash('pass'))

    # Trips
    trip_one = Trip(name="Trip One", user=Kristian)
    trip_two = Trip(name="Trip Two", user=Kristian)

    # Locations - Trip One
    location_one = Location(name="Clapham Junction",
                            postcode="SW111PW",
                            latitude=51.4652,
                            longitude=-0.1708,
                            trip=trip_one)
    location_two = Location(name="Vauxhall",
                            postcode="SW84ET",
                            latitude=51.4862,
                            longitude=-0.1229,
                            trip=trip_one)
    location_three = Location(name="Southfields",
                              postcode="SW196LL",
                              latitude=51.4448,
                              longitude=-0.2068,
                              trip=trip_one)

    # Locations - Trip Two
    location_four = Location(name="Bethnal Green",
    def create(self):
        counter = 0

        country = ""
        airport = ""
        phone = ""
        hours = ""

        while True:

            self.printer.header("Create location")
            print(
                f"Country:\t\t\t{country}\nAirport:\t\t\t{airport}\nPhone:\t\t\t\t{phone}\nHours:\t\t\t\t{hours}\n"
            )
            self.printer.new_line()
            self.printer.print_fail("Press q to go back")
            self.printer.new_line()
            self.notification()
            next_input = True
            data = None
            try:
                if counter == 0:
                    data = self.input.get_input("country", ["required"],
                                                warning_msg=self.warning_msg)
                    if data[0]:
                        country = data[1]
                    else:
                        next_input = False
                        self.warning_msg = data[1]
                elif counter == 1:
                    data = self.input.get_input("airport", ["required"],
                                                warning_msg=self.warning_msg)
                    if data[0]:
                        airport = data[1]
                    else:
                        next_input = False
                        self.warning_msg = data[1]
                elif counter == 2:
                    data = self.input.get_input("phone", ["required", "phone"],
                                                warning_msg=self.warning_msg)
                    if data[0]:
                        phone = data[1]
                    else:
                        next_input = False
                        self.warning_msg = data[1]
                elif counter == 3:
                    data = self.input.get_input("hours", ["required"],
                                                warning_msg=self.warning_msg)
                    if data[0]:
                        hours = data[1]
                    else:
                        next_input = False
                        self.warning_msg = data[1]
                elif counter > 3:
                    new_location = Location(country, airport, phone, hours)
                    confirmation = input(
                        "Are you sure you want to create this location? (\33[;32mY\33[;0m/\33[;31mN\33[;0m): "
                    ).lower()
                    if confirmation == 'y':
                        self.logic.create_location(new_location)
                        return True
                    return False
                if next_input:
                    counter += 1
            except ValueError:
                break
 def getLocationByCode(self, code):
     """Returns JSON object of a location"""
     location = Location.findLocationByCode(code)
     if location:
         return location.json(), 201
     return {"message": "The location is not found in the database."}, 404
 def getAllLocations(self):
     """Returns JSON object of all locations"""
     return list(map(lambda x: x.json(), Location.findAllLocations()))
Esempio n. 32
0
def index():
    schema = LocationSchema(many=True)
    locations = Location.select()

    return schema.dumps(locations)
Esempio n. 33
0
 def __init__(self, row, column, walls=None, unbreakable=None):
     self.walls = self.create_walls_dir(walls, unbreakable)
     self.location = Location(row, column)
     self.has_treasure = False
     self.has_armoury = False