Example #1
0
def location_list(request):
    if request.method == 'GET':
        return get_location_list()

    if request.method == 'POST':
        if not request.user.is_authenticated(request):
            return HttpResponse('Unauthorized', status=401)
        
        data = json.loads(request.body)
        l = None
        if not data.get('id'):
            l = Location(user=request.user, data=json.dumps(data), name=data['name'])
            l.save()
            data["id"] = l.id
            l.data = json.dumps(data)
            l.save()
        else:
            l = Location.objects.get(pk=int(data['id']))
            if (request.user.is_staff == False):
                if (l.user.pk != request.user.pk):
                    return HttpResponse(json.dumps({'error': 'not authorized'}), content_type="application/json")
            l.data = json.dumps(data)
            l.name = data['name']
            l.save()
        return HttpResponse(json.dumps(l.data), content_type="application/json")



    return HttpResponse(json.dumps({'error': 'must be get or post request'}), content_type="application/json")
    def test_create_and_read(self):
        """Test create user"""

        user = User(name='Nicholas Cage', age=49, gender='m')

        db.session.add(user)
        db.session.commit()

        user = User.query.filter_by(name='Nicholas Cage').first()

        location1 = Location(city="Los Angeles",
                             latitude=34.063566,
                             longitude=-118.421092)

        location2 = Location(city="San Francisco",
                             latitude=37.69841,
                             longitude=-122.454232)

        user.locations.extend([location1, location2])

        db.session.add(user)
        db.session.commit()

        user = User.query.filter_by(name='Nicholas Cage').first()

        locations = Location.query.all()

        self.assertGreater(len(locations), 2)

        location = Location.query.filter_by(city='Los Angeles').first()
        self.assertEqual(location.city, 'Los Angeles')
        self.assertEqual(location.latitude, 34.062264)
        self.assertEqual(location.longitude, -118.340361)
def admin_home():
    locform = LocationForm()
    if locform.validate_on_submit() :
        ids = request.form.getlist('id')
        name = request.form.getlist('name')
        longitude = request.form.getlist('longitude')
        latitude = request.form.getlist('latitude')
        type = request.form.getlist('types')        
        for (i, id) in enumerate(ids) :
            if id.isdigit() :
                loc = Location.query.get(id)
                loc.longitude = longitude[i]
                loc.latitude = latitude[i]
                loc.name = name[i]
                loc.type = type[i].lower()
                db.session.commit()
            else :
                if longitude[i] and latitude[i] and name[i] :
                    loc = Location(float(longitude[i]), float(latitude[i]), name[i], 'N/A', 'N/A')
                    loc.type = type[i].lower()
                    db.session.add(loc)
                    db.session.commit()
    locations = Location.query.all()
    type_list = list()
    
    for type in location_type._asdict().values():
        type_list.append(type.capitalize())
    return render_template('admin.html', locations=locations, location_types=type_list, form=locform, username=current_user.username)
Example #4
0
 def test01_setup(self):
     "Setting up for related model tests."
     for name, state, lon, lat in cities:
         loc = Location(point=Point(lon, lat))
         loc.save()
         c = City(name=name, state=state, location=loc)
         c.save()
Example #5
0
    def save(self, eventperson):
        eventperson.attended = self.cleaned_data['attended']

        try:
            person = eventperson.person
        except Person.DoesNotExist:
            person, created = Person.objects.get_or_create(
                first_name = self.cleaned_data['first_name'],
                last_name = self.cleaned_data['last_name'],
                email = self.cleaned_data['email'],
                )

        for a in self.people_attrs:
            setattr(person,a,self.cleaned_data[a])

        if any([self.cleaned_data.get(a,None) for a in self.address_attrs]):
            address = person.address
            if not address:
                address = Location()

            for a in self.address_attrs:
                setattr(address,a,self.cleaned_data[a])

            address.save()
            person.address = address

        person.save()
        eventperson.person = person
        eventperson.save()
def admin_home():
    locform = LocationForm()
    if locform.validate_on_submit():
        ids = request.form.getlist('id')
        name = request.form.getlist('name')
        longitude = request.form.getlist('longitude')
        latitude = request.form.getlist('latitude')
        type = request.form.getlist('types')
        for (i, id) in enumerate(ids):
            if id.isdigit():
                loc = Location.query.get(id)
                loc.longitude = longitude[i]
                loc.latitude = latitude[i]
                loc.name = name[i]
                loc.type = type[i].lower()
                db.session.commit()
            else:
                if longitude[i] and latitude[i] and name[i]:
                    loc = Location(float(longitude[i]), float(latitude[i]),
                                   name[i], 'N/A', 'N/A')
                    loc.type = type[i].lower()
                    db.session.add(loc)
                    db.session.commit()
    locations = Location.query.all()
    type_list = list()

    for type in location_type._asdict().values():
        type_list.append(type.capitalize())
    return render_template('admin.html',
                           locations=locations,
                           location_types=type_list,
                           form=locform,
                           username=current_user.username)
Example #7
0
def add_location(request, loc):
    context = {}
    my_location = Location.objects.get(id=loc)
    context['curr_location'] = my_location
    context['parent'] = my_location.parent
    context['lat'] = my_location.latitude
    context['lon'] = my_location.longitude
    context['zoom'] = my_location.density   
    if request.method == 'POST': # If the form has been submitted...
        form = LocationForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            name = form.cleaned_data['name']
            latitude = form.cleaned_data['latitude']
            longitude = form.cleaned_data['longitude']
            density = form.cleaned_data['density']
            venue = form.cleaned_data['venue']
            parent = form.cleaned_data['parent']
            l = Location(name=name, parent=parent, latitude=latitude, longitude=longitude, density=density, venue=venue)
            l.save()

            return HttpResponseRedirect('/') # Redirect after POST
    else:
        context['form'] = LocationForm(initial={'parent':my_location.id}) # An unbound form


    return render_to_response('www/place/add.html', context, context_instance=RequestContext(request))
Example #8
0
 def test01_setup(self):
     "Setting up for related model tests."
     for name, state, lon, lat in cities:
         loc = Location(point=Point(lon, lat))
         loc.save()
         c = City(name=name, state=state, location=loc)
         c.save()
Example #9
0
    def post(self):
        messageid = self.request.get("messageid")
        if messageid == "":
            rawCharacter =  cgi.escape(self.request.get("character"), quote = True)
            rawLocation =   cgi.escape(self.request.get("address"), quote = True)
            # Validate character
            (character, charError) = map.validateCharacter(rawCharacter)
            # Validate location
            location = map.validateLocation(rawLocation)
            error, msgError = "", ""

            # Check validation errors and format error message
            if character == None:
                msgChar = rawCharacter
            else:
                msgChar = str(character.name)

            if charError != "":
                error = charError
                msgError = error
            if location.status != "OK":
                error = (error + " " + location.status.encode('utf_8')).decode('utf_8')
                msgError = error
            if (charError == "") and (location.status == "OK"):
                error = ("Move %s to %s. Got it!" % (msgChar, location.address.encode('utf_8'))).decode('utf_8')
                msgError = ""

            print datetime.datetime.utcnow()
            print "error: " + error.encode('utf_8')
            print type(error)
            print "msgError: " + msgError.encode('utf_8')
            print type(msgError)
            # Store in Message store
            if recordMessage("WebForm", None, self.request.remote_addr, msgChar, location, rawCharacter+" "+rawLocation, msgError):
                print "IN APP:"
                top_msgs(True)
                self.writeHTML(error=error, character=character, location=location)
            else:
                error = "App Error: Failed to insert message."
                self.writeHTML(error=error, character=character, location=location)

        else:
            # Validate messageid and get message
            messagekey = ndb.Key(urlsafe=messageid)
            message = Message()
            message = messagekey.get()
            character = Character.query(Character.name == message.character).get()
            location = Location()
            location.address = message.address
            location.latlng = message.latlng

            # If message found
            if not message:
                error = "App Error: Cannot get message."
                self.writeHTML(error=error, character=None, location=None)

            # If message not found
            else:
                # Write
                self.writeHTML(error="", character=character, location=location)
Example #10
0
def get_all_locations():
    # Open a connection to the database
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute("""
        SELECT
            l.id,
            l.name,
            l.address
        FROM location l
        """)

        # Initialize an empty list to hold all location representations
        locations = []
        dataset = db_cursor.fetchall()

        # Iterate all rows of data returned from database
        for row in dataset:

            # Create an location instance from the current row
            location = Location(row['name'], row['address'])
            location.id = row['id']

            locations.append(location.__dict__)

    return json.dumps(locations)
Example #11
0
 def test_save_location(self, downloader_obj, modifier_obj):
     modifier_obj.execute_modifications()
     dict_obj = modifier_obj._data[0]
     save_obj = ApiDataSave(downloader_obj, 'results')
     p = save_obj.save_person(dict_obj)
     save_obj.save_location(dict_obj, p)
     assert len(
         Location.select()) == 1, 'The Location object has not been saved'
     location = Location.select()[0]
     error = 'Invalid data has been written'
     assert location.number == dict_obj['location']['street'][
         'number'], error
     assert location.street == dict_obj['location']['street']['name'], error
     assert location.city == dict_obj['location']['city'], error
     assert location.state == dict_obj['location']['state'], error
     assert location.country == dict_obj['location']['country'], error
     assert location.postcode == str(
         dict_obj['location']['postcode']), error
     assert location.timezone_offset == dict_obj['location']['timezone'][
         'offset'], error
     assert location.timezone_description == dict_obj['location'][
         'timezone']['description'], error
     assert str(location.coordinates_latitude
                ) == dict_obj['location']['coordinates']['latitude'], error
     assert str(location.coordinates_longitude
                ) == dict_obj['location']['coordinates']['longitude'], error
     assert location.person == p, error
Example #12
0
def add(request, form_class=AddLocationForm, template='maps/add_location.html'):
    center_obj = DEFAULT_CENTER_OBJ
    if request.method == 'POST': # If the form has been submitted...
        form = form_class(request.user, request.POST)
        if form.is_valid():
            
            location = form.save(commit=False)
            location.user = request.user
            location.save()
            msg = _("%(name)s has been saved.") %{'name': location.name}
            messages.add_message(request, messages.SUCCESS, msg)
            
            if request.session.has_key('next'):
                redirect_url = request.session.get('next')
                return HttpResponseRedirect(redirect_url)
            return HttpResponseRedirect(reverse('locations_list'))
        else:
            # We re-pass the default location if the form is not valid
            location = Location()
            location.marker = Point(DEFAULT_CENTER_OBJ['x'], DEFAULT_CENTER_OBJ['y'])
        
    else:
        # A dynamically loaded form
        location = Location()
        location.marker = Point(DEFAULT_CENTER_OBJ['x'], DEFAULT_CENTER_OBJ['y'])
        form = form_class(initial={'user' : request.user,
                                   'marker' : location.marker})
        if request.GET.has_key('next'):
            request.session['next'] = request.GET['next']
        
    return render_to_response(template,
                              { "form": form, 
                                "location": location,
                               },
                              context_instance=RequestContext(request))
Example #13
0
    def test_delete_restaurant(self):
        '''
        removes all instances of the above created restaurant objects
        includes: [restaurant, location, restaurant_info]
        '''
        ins_restaurant = Restaurant('John Doe', '5103388949')
        ins_restaurant.insert()
        restaurant_id = ins_restaurant.id
        print(f'INSERTED for DELETION: {restaurant_id}')
        ins_location = Location(restaurant_id=restaurant_id,
                                address='1234 John Doe Ave',
                                city='San Francisco',
                                zipcode=94502,
                                state='CA')
        ins_ri = RestaurantInfo(restaurant_id=restaurant_id,
                                website='DELETION',
                                description='John Doe Bakery',
                                classification='type_all',
                                yelp_link='yelp.com/1')
        ins_location.insert()
        ins_ri.insert()

        print(ins_ri)

        res = self.client().delete(f'/restaurants/{restaurant_id}')
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
Example #14
0
def take_suggestions():
	if os.path.exists(LATESTFILE_SUG):
		fp = open(LATESTFILE_SUG)
		lastid = fp.read().strip()
		fp.close()
		
		if lastid == '':
			lastid = 0
	else:
		lastid = 0
		
	result = api.GetMentions(since_id = lastid)
	#No mention, no suggestion
	print lastid
	if len(result) == 0:
		print "No mention received"
		return []
	else :
		fp = open(LATESTFILE_SUG, 'w')
		fp.write(str(max([x.id for x in result])))
		fp.close()
		entry = History.query.descending('mongo_id').first()
		for x in result:
			print x.text
		#Somebody already suggested..
		if entry.next_location.name != entry.suggested_location.name :
			print "There already is a suggestion. Fitz is currently headed to "+entry.next_location.name
			return []
		else :
			candidates = {}
			#Walk through all the mentions we got here..
			
			for x in result :
				mention_entry = x.text.split(' ')
				s_user = x.user.screen_name
				#Locations have to be proposed in a form of "Check out ***"
				if mention_entry[1] == 'Check' and mention_entry[2] == 'out':
					s_key = s_user + ":" + ' '.join(mention_entry[3:])
					s_geo = geocoder(' '.join(mention_entry[3:]))
					distance = gcd(entry.next_location.geocode[0], entry.next_location.geocode[1], s_geo[1], s_geo[2])
					candidates[s_key] = distance
			#Got somethin' but no useful words
			if len(candidates) == 0:
				print "Got some words, but no suggestions.."
				return []
			#Got somewhere to go!
			else :
				next_move = min(candidates, key=candidates.get)
				print candidates[candidates.keys()[0]] > candidates[candidates.keys()[1]]
				print next_move		
				l = Location()
				l.name = next_move.split(':')[1]
				l.geocode = geocoder(next_move.split(':')[1])[1:]
				entry.suggested_location = l
				entry.suggested_by = next_move.split(':')[0]
				entry.save()
				user_sug = []
				user_sug.append(next_move.split(':')[0])
				user_sug.append(next_move.split(':')[1])
				return user_sug
    def test_users_show_location(self):
        """This test method will confirm that a 
            logged in user location is displayed 
            on the page when a user logs in.
        """
        L = Location(name="Home",
                     address="False Test Creek SW, Long Beach CA",
                     long=143.12,
                     lat=-234.5,
                     city="Long Beach",
                     state="CA",
                     user_id=self.testuser_id)
        L_id = 124
        L.id = L_id

        db.session.add(L)
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.testuser_id
                sess[CURR_LOCATION] = L_id

            resp = c.get("/users/datelocations")

            self.assertIn("False Test Creek SW, Long Beach CA", str(resp.data))
            self.assertIn("Home", str(resp.data))
Example #16
0
def addLocation(_, info, **kwargs):
    print("kwargs>>", kwargs)
    new_location_dict = {x: kwargs[x] for x in kwargs}
    print("new_location_dict>>>", new_location_dict)
    newlocation = Location(**new_location_dict)
    newlocation.save()
    return newlocation
Example #17
0
def addEditObstacle(oid):
    obstacle = None
    form = ObstacleForm()  
    if oid is not None:
        obstacle = Obstacle.query.get(oid)  # @UndefinedVariable
        
    if request.method == 'GET':
        if obstacle is None:
            form.new.data = True
        else:  
            form.new.data = False    
            form.id.data = obstacle.id
            form.location.lat.data = obstacle.location.lat
            form.location.lon.data = obstacle.location.lon    
    if request.method == 'POST' and form.validate():  # @UndefinedVariable
        if obstacle is None:
            #new obstacle has passed validation, add to db
            location = Location(lat=form.location.lat.data, lon=form.location.lon.data)
            db.session.add(location)  # @UndefinedVariable
            obstacle= Obstacle(location=location)
            db.session.add(obstacle)  # @UndefinedVariable
            db.session.commit()  # @UndefinedVariable
            flash("Obstacle has been created")
        else: 
            #node has been updated. save updates
            location = Location.query.get(obstacle.loc_id)  # @UndefinedVariable
            location.lat = form.location.lat.data
            location.lon = form.location.lon.data
            db.session.commit()  # @UndefinedVariable
            flash("Obstacle has been updated")
        
        # after creating the new state, redirect them back to dce config page
        return redirect(url_for("obstaclePage"))    
    return render_template("obstacleForm.html", form=form) 
Example #18
0
def new_location(request):
    """
    New Location
    """
    data = {}
    template = 'itembase/simpleform.djhtml'
    data['message'] = None
    data['headstring'] = 'New Location'
    if request.method == "POST":
        form = LocationForm(request.POST)
        if form.is_valid():
            location = Location(lc_name=form.cleaned_data['lc_name'],
                                lc_geo=form.cleaned_data['lc_geo'],
                                lc_adr=form.cleaned_data['lc_adr'],
                                lc_city=form.cleaned_data['lc_city'],
                                lc_www=form.cleaned_data['lc_www'],
                                lc_mail=form.cleaned_data['lc_mail'],
                                lc_info=form.cleaned_data['lc_info'],
                                )
            location.save()
            print(location)
            membership = Membership(me_user = request.user,
                                    me_location = location,
                                    me_trust1 = request.user,
                                    me_trust2 = request.user,
            )
            membership.save()
            print membership
            return redirect('itembase/home')
        return redirect('itembase/home')
    else:
        data['form'] = LocationForm()
    return render(request, template, data)
Example #19
0
def new_location(request):
    """
    New Location
    """
    data = {}
    template = 'itembase/simpleform.djhtml'
    data['message'] = None
    data['headstring'] = 'New Location'
    if request.method == "POST":
        form = LocationForm(request.POST)
        if form.is_valid():
            location = Location(
                lc_name=form.cleaned_data['lc_name'],
                lc_geo=form.cleaned_data['lc_geo'],
                lc_adr=form.cleaned_data['lc_adr'],
                lc_city=form.cleaned_data['lc_city'],
                lc_www=form.cleaned_data['lc_www'],
                lc_mail=form.cleaned_data['lc_mail'],
                lc_info=form.cleaned_data['lc_info'],
            )
            location.save()
            print(location)
            membership = Membership(
                me_user=request.user,
                me_location=location,
                me_trust1=request.user,
                me_trust2=request.user,
            )
            membership.save()
            print membership
            return redirect('itembase/home')
        return redirect('itembase/home')
    else:
        data['form'] = LocationForm()
    return render(request, template, data)
Example #20
0
async def clone_location(sid: str, data: LocationCloneData):
    pr: PlayerRoom = game_state.get(sid)
    if pr.role != Role.DM:
        logger.warning(f"{pr.player.name} attempted to clone locations.")
        return
    try:
        room = Room.select().where((Room.name == data["room"])
                                   & (Room.creator == pr.player))[0]
    except IndexError:
        logger.warning(f"Destination room {data['room']} not found.")
        return

    src_location = Location.get_by_id(data["location"])
    new_location = Location.create(room=room,
                                   name=src_location.name,
                                   index=room.locations.count())

    new_groups = {}

    for prev_floor in src_location.floors.order_by(Floor.index):
        new_floor = new_location.create_floor(prev_floor.name)
        for prev_layer in prev_floor.layers:
            new_layer = new_floor.layers.where(
                Layer.name == prev_layer.name).get()
            for src_shape in prev_layer.shapes:
                new_group = None
                if src_shape.group:
                    group_id = src_shape.group.uuid
                    if group_id not in new_groups:
                        new_groups[group_id] = src_shape.group.make_copy()
                    new_group = new_groups[group_id]

                src_shape.make_copy(new_layer, new_group)
Example #21
0
 def post(self):
     """ Create a new location (or override existing) """
     try:
         Location.save_from_request(self.request)
     except Exception as e:
         self.error(403)
         self.response.out.write(e)
         return
     self.redirect('/')
Example #22
0
    def test_list_recommendations(self):
        """This test method tests to confirm that the logged in user can only
        view recommendations in their state and city."""

        L = Location(name="Home",
                     address="False Test Creek SW, Long Beach CA",
                     long=143.12,
                     lat=-234.5,
                     city="Long Beach",
                     state="CA",
                     user_id=self.testuser_id)
        L_id = 124
        L.id = L_id

        db.session.add(L)
        db.session.commit()

        r1 = Recommendation(
            title="Fire Doughnuts in LA",
            content=
            "Bro these mf doughnuts be smacking like gahdamn!. Check out Leonards bro!",
            business_name="Leonards",
            business_address="2345 Rodeo Ave",
            business_city="Long Beach",
            business_state="CA",
            business_country="US",
            business_rating=5,
            user_id=self.testuser_id)

        r2 = Recommendation(
            id=365,
            title="Deep Dish Pizza in Edmonton, Canada",
            content=
            "Looking for delicious deep dish pizza?, Chicago 001 has the best on Whyte Ave",
            business_name="Chicago 001",
            business_address="1946 Whyte Ave NW",
            business_city="Edmonton",
            business_state="Alberta",
            business_country="Canada",
            business_rating=5,
            user_id=self.u2id)

        db.session.add_all([r1, r2])
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.testuser_id
                sess[CURR_LOCATION] = L_id

            resp = c.get("/recommendations/list")

            self.assertEqual(resp.status_code, 200)
            self.assertIn("Fire Doughnuts in LA", str(resp.data))
            self.assertNotIn("Deep Dish Pizza in Edmonton, Canada",
                             str(resp.data))
Example #23
0
def locations_add(jwt):
    try:
        body = request.get_json()
        new_name = body.get('name', None)
        new_location = Location(name=new_name)
        new_location.insert()
        return jsonify({"success": True, "new_id": new_location.id})
    except Exception as e:
        print(e)
        abort(422)
Example #24
0
def test_get_location_coordinates(app):
    location = Location(location='POINT(-94.782234 38.880684)')
    coords = location.coords
    assert coords.get('latitude') == 38.880684
    assert coords.get('longitude') == -94.782234

    bad_location = Location(location=None)
    bad_coords = bad_location.coords
    assert bad_coords.get('latitude') == None
    assert bad_coords.get('longitude') == None
Example #25
0
def home(request):
    # create a location for no particular reason
    if Location.objects.count() == 0:
        loc = Location(name="Microsoft NERD Center",
                       street="1 Memorial Drive",
                       city="Cambridge",
                       state="MA",
                       country="US")
        loc.save()
    return render_to_response('home.html')
Example #26
0
def suggest():
	entry = History.query.descending('mongo_id').first()
	suggested_point = app.config['SUGGESTED_POINT']
	geocode = geocoder(suggested_point)
	location = Location()
	location.name = geocode[0]
	location.geocode = (geocode[1],geocode[2])
	entry.suggested_location = location
	entry.save()
	return suggested_point + " suggested!"
Example #27
0
def add():
    simpizza = Location()
    simpizza.configure("Sim-pizza",
                       "De Pintelaan 252 9000 Gent, tel: 09/321.02.00",
                       "http://simpizza.be")
    db.session.add(simpizza)

    for pizza in pizzas:
        entry = Product()
        entry.configure(simpizza, pizza, 1195)
        db.session.add(entry)
Example #28
0
def search():
    if 'query' not in request.args or not request.args['query']:
        return json.dumps({
            'meta': {
                'code': 400,
                'errorType': 'param_error',
                'errorDetail': 'Missing or empty query parameter'
            },
        }), 400

    limit = 10
    if 'limit' in request.args and request.args['limit'] and request.args[
            'limit'].isdigit():
        limit = int(request.args['limit'])

    # Replacing whitespace with .* to offer more flexibility in what schools get
    # returned in the search. ex: If the query is "Belleville High School", we'd
    # still want it to return "Belleville Senior High School" as a result.
    name_regex = request.args['query']
    name_regex = name_regex.replace(' ', '.*')

    query = {
        'name': {
            '$regex': '%s' % name_regex,
            '$options': 'i'
        }
    }

    if 'state' in request.args:
        query['state'] = request.args['state']

    total_results = Location.objects(__raw__=query).count()
    locations = Location.objects(__raw__=query).limit(limit)
    results = []
    for location in locations:
        results.append({
            'name': location.name,
            'street': location.street,
            'city': location.city,
            'state': location.state,
            'zip': location.zip,
            'lat': location.lat,
            'lon': location.lon,
            'country': location.country,
            'gsid': location.gsid
        })
    return json.dumps({
        'meta': {
            'code': 200,
            'more_results': len(results) < total_results,
            'total_results': total_results
        },
        'results': results
    }), 200
Example #29
0
def construct_Location():
    location_dict = {}
    u_locations =list(set([row['work_location2'] for index, row in complete_data2.iterrows()]))
    for u_location in u_locations:
        geo = geocoder.google(u_location).latlng
        if not type(geo) == type(geocoder.google('').latlng):
            location_dict[u_location] = Location(address = u_location, lat = geo[0], long = geo[1], geocodeBool = 1)
        else:
            location_dict[u_location] = Location(address = u_location, geocodeBool = 0)
        time.sleep(2)
    db.session.add_all([location_dict[key] for key in location_dict.keys()])
    db.session.commit()
Example #30
0
    def save(self,*args,**kwargs):
        if any([self.cleaned_data.get(a) for a in self.address_attrs]):
            address = self.instance.address
            if not address:
                address = Location()

            [setattr(address,a,self.cleaned_data[a]) for a in self.address_attrs]

            address.save()
            self.instance.address = address

        return super(PersonForm,self).save(*args,**kwargs)
Example #31
0
def add_location(name, latitude, longitude):
    """
    @summary: Add the location to the database
    @param name : Location name
    @type name: str
    @param latitude: latitude of the location as float
    @type latitude: float
    @param longitude: longitude of the location as float
    @type longitude: float
    """
    loc = Location(name=name,latitude=latitude, longitude=longitude)
    loc.save()
def addAfhalen():
    primadonna_afhalen = Location()
    primadonna_afhalen.configure(
        "Primadonna (bellen en afhalen)",
        "Overpoortstraat 46 9000 Gent, tel: 0475 40 13 00",
        "http://primadonnagent.be/Menu.html")
    db.session.add(primadonna_afhalen)

    for pizza, price in pizzasAfhalen.items():
        entry = Product()
        entry.configure(primadonna_afhalen, pizza, price)
        db.session.add(entry)
def addTA():
    primadonna_takeaway = Location()
    primadonna_takeaway.configure(
        "Primadonna (takeaway laten bezorgen)",
        "Overpoortstraat 46 9000 Gent, tel: 0475 40 13 00",
        "https://www.takeaway.com/be-en/prima-donna")
    db.session.add(primadonna_takeaway)

    for pizza, price in pizzasTA.items():
        entry = Product()
        entry.configure(primadonna_takeaway, pizza, price)
        db.session.add(entry)
Example #34
0
 def test_save_data_to_db(self, downloader_obj, modifier_obj):
     persons = len(Person.select())
     contacts = len(Contact.select())
     logins = len(Login.select())
     localizations = len(Location.select())
     modifier_obj.execute_modifications()
     save_obj = ApiDataSave(downloader_obj, 'results')
     save_obj.save_data_to_db()
     error = 'Incorrect number of objects saved in the database'
     assert len(Person.select()) == persons + API_PERSONS, error
     assert len(Contact.select()) == contacts + API_PERSONS, error
     assert len(Login.select()) == logins + API_PERSONS, error
     assert len(Location.select()) == localizations + API_PERSONS, error
Example #35
0
def insert_json_data():
    '''JSON データを location テーブルに全件挿入する
    '''
    locations = prepare_locations(load_locations())

    for l in locations:
        location = {
            'title': l['title'],
            'year': int(l['year']),
            'locations': l['locations'],
        }
        # print(location)
        Location.create(**location)
Example #36
0
def add() -> None:
    "Add Fitchen to the database"
    fitchen = Location()
    fitchen.configure("Fitchen", "?", "?", "https://www.fitchen.be/")
    db.session.add(fitchen)

    for menuitem in menuitems:
        for size, price in pricedict.items():
            for container in ["bowl", "wrap"]:
                name = "%s %s in %s" % (size, menuitem, container)
                entry = Product()
                entry.configure(fitchen, name, price)
                db.session.add(entry)
Example #37
0
    def post(self, request):
        try:
            wechat.parse_data(request.body)
        except ParseError:
            return HttpResponse('Invalid Body Text')

        id = wechat.message.id              # MsgId
        target = wechat.message.target      # ToUserName
        source = wechat.message.source      # FromUserName
        time = wechat.message.time          # CreateTime
        type = wechat.message.type          # MsgType
        raw = wechat.message.raw            # 原始 XML 文本

        # get_or_create会得到一个tuple (object, created)
        fowler = Fowler.objects.get_or_create(OpenID=source)[0]

        if isinstance(wechat.message, TextMessage):
            keywords = [func.keyword for func in Function.objects.all()]
            content = wechat.message.content                # 对应于 XML 中的 Content
            if content in keywords:
                reply = Function.objects.get(keyword=content).explain
            else:
                reply = '本公众号支持的回复有: \n' + ' '.join(keywords)

            dialog = Dialog(message=content, reply=reply, fowler=fowler)
            dialog.save()
            response_xml = wechat.response_text(content=reply, escape=True)
            return HttpResponse(response_xml)

        elif isinstance(wechat.message, LocationMessage):
            location = wechat.message.location              # Tuple(Location_X, Location_Y)
            scale = wechat.message.scale                    # 地图缩放大小
            label = wechat.message.label                    # 地理位置

            loc = Location(fowler=fowler, x=location[0], y=location[1], label=label)
            loc.save()
            response_xml = wechat.response_text(content='已收到您的地理位置')
            return HttpResponse(response_xml)

        elif isinstance(wechat.message, EventMessage):
            if wechat.message.type == 'subscribe':
                fowler.activate = 1
                fowler.save()
                response_xml = wechat.response_text(content='欢迎关注本公众号 具体功能请回复‘功能’')
                return HttpResponse(response_xml)
            elif wechat.message.type == 'unsubscribe':
                fowler.activate = 0
                fowler.save()
        else:
            response_xml = wechat.response_text(content="回复'功能'了解本公众号提供的查询功能")
            return HttpResponse(response_xml)
Example #38
0
def test_get_locations_list(app):
    """
    GIVEN a Flask application
    WHEN the '/locations' page is requested (GET)
    THEN check the response is valid
    """

    # insert a location into the database
    location_1 = Location(address='123 test street',
                          city='Kansas City',
                          state='MO',
                          zip_code=66213,
                          location='POINT(-83.123456 39.123432)')

    location_2 = Location(address='456 test way',
                          city='Kansas City',
                          state='KS',
                          zip_code=66210,
                          location='POINT(-83.654321 39.654321)')

    db.session.add(location_1)
    db.session.add(location_2)
    db.session.commit()
    with app.test_client() as client:
        response = client.get('/locations')
        assert response.status_code == 200
        data = response.get_json()
        resp_locations = sorted(data.get('locations'),
                                key=itemgetter('address'))
        assert resp_locations is not None

        test_location1 = {
            "id": resp_locations[0].get("id"),
            "address": "123 test street",
            "city": "Kansas City",
            "state": "MO",
            "zipCode": 66213,
            "longitude": -83.123456,
            "latitude": 39.123432
        }
        test_location2 = {
            "id": resp_locations[1].get("id"),
            "address": "456 test way",
            "city": "Kansas City",
            "state": "KS",
            "zipCode": 66210,
            "longitude": -83.654321,
            "latitude": 39.654321
        }
        assert resp_locations == [test_location1, test_location2]
Example #39
0
def search():
    if 'query' not in request.args or not request.args['query']:
        return json.dumps({
            'meta': {
                'code': 400,
                'errorType': 'param_error',
                'errorDetail': 'Missing or empty query parameter'
            },
        }), 400

    limit = 10
    if 'limit' in request.args and request.args['limit'] and request.args['limit'].isdigit():
        limit = int(request.args['limit'])

    # Replacing whitespace with .* to offer more flexibility in what schools get
    # returned in the search. ex: If the query is "Belleville High School", we'd
    # still want it to return "Belleville Senior High School" as a result.
    name_regex = request.args['query'];
    name_regex = name_regex.replace(' ', '.*');

    query = {'name':{'$regex': '%s' % name_regex, '$options': 'i'}};

    if 'state' in request.args:
        query['state'] = request.args['state'];

    total_results = Location.objects(__raw__=query).count()
    locations = Location.objects(__raw__=query).limit(limit)
    results = []
    for location in locations:
        results.append(
            {
                'name': location.name,
                'street': location.street,
                'city': location.city,
                'state': location.state,
                'zip': location.zip,
                'lat': location.lat,
                'lon': location.lon,
                'country': location.country,
                'gsid': location.gsid
            }
        )
    return json.dumps({
        'meta': {
            'code': 200,
            'more_results': len(results) < total_results,
            'total_results': total_results
        },
        'results': results
    }), 200
Example #40
0
def admin_api(request):

    if request.POST['method'] == 'add_location':
        try:
            l = Location()
            l.location = request.POST['location']
            l.page = Page.objects.filter(id=request.POST['page']).get()
            l.save()
        except Exception, e:
            print e
        return HttpResponse(json.dumps({
            'location': l.location,
            'id': l.id,
            }))
Example #41
0
def add() -> None:
    testlocation = Location()
    testlocation.configure(
        "Testlocation",
        "Please ignore!",
        "0469 69 69 69",
        "http://localhost:8000/",
    )
    db.session.add(testlocation)

    for stuff in STUFFS:
        entry = Product()
        entry.configure(testlocation, *stuff)
        db.session.add(entry)
Example #42
0
async def connect(sid, environ):
    user = await authorized_userid(environ["aiohttp.request"])
    if user is None:
        await sio.emit("redirect", "/", room=sid, namespace="/planarally")
    else:
        ref = unquote(environ["HTTP_REFERER"]).strip("/").split("/")
        room = (Room.select().join(User).where((Room.name == ref[-1])
                                               & (User.name == ref[-2]))[0])
        if room.creator == user:
            location = Location.get(room=room, name=room.dm_location)
        else:
            location = Location.get(room=room, name=room.player_location)

        state.add_sid(sid, user=user, room=room, location=location)

        logger.info(f"User {user.name} connected with identifier {sid}")

        sio.enter_room(sid, location.get_path(), namespace="/planarally")
        await sio.emit("Username.Set",
                       user.name,
                       room=sid,
                       namespace="/planarally")
        await sio.emit(
            "Room.Info.Set",
            {
                "name": room.name,
                "creator": room.creator.name,
                "invitationCode": str(room.invitation_code),
            },
            room=sid,
            namespace="/planarally",
        )
        await sio.emit(
            "Notes.Set",
            [
                note.as_dict()
                for note in Note.select().where((Note.user == user)
                                                & (Note.room == room))
            ],
            room=sid,
            namespace="/planarally",
        )
        await sio.emit(
            "Asset.List.Set",
            Asset.get_user_structure(user),
            room=sid,
            namespace="/planarally",
        )
        await load_location(sid, location)
Example #43
0
File: app.py Project: Leny73/fsnd
    def add_location(jwt):
        body = request.get_json()
        new_name = body.get('name', None)
        new_location = body.get('location', None)

        try:
            location = Location(name=new_name, location=new_location)
            print(location)
            location.insert()

            return jsonify({
                'success': True,
            })
        except Exception as e:
            print(e)
Example #44
0
def add() -> None:
    "Add Simpizza to the database"
    simpizza = Location()
    simpizza.configure(
        "Sim-pizza",
        "De Pintelaan 252 9000 Gent",
        "tel: 09/321.02.00",
        "http://simpizza.be",
    )
    db.session.add(simpizza)

    for pizza in pizzas:
        entry = Product()
        entry.configure(simpizza, pizza, 1195)
        db.session.add(entry)
Example #45
0
def addAfhalen() -> None:
    "Add Primadonna to takeaway to the database"
    primadonna_afhalen = Location()
    primadonna_afhalen.configure(
        "Primadonna (bellen en afhalen)",
        "Overpoortstraat 46 9000 Gent",
        "tel: 0475 40 13 00",
        "http://primadonnagent.be/Menu.html",
    )
    db.session.add(primadonna_afhalen)

    for pizza, price in pizzasAfhalen.items():
        entry = Product()
        entry.configure(primadonna_afhalen, pizza, price)
        db.session.add(entry)
Example #46
0
def index(request):
    fields = Location.get_filter_fields()
    st = ''
    selected = '2'

    if request.POST and 'searchText' in request.POST:
        st = request.POST['searchText']
        selected = request.POST['searchRadius']

    ctx = RequestContext(request, {
        'fields': fields,
        'searchText': st,
        'options': get_opts(selected),
        'mapbarEnabled': True
    })

    response = render_to_response('index.html', context_instance=ctx)

    # cookie for splash screen, defaults to true
    try:
        show_splash = request.COOKIES['show_splash']
        if show_splash == 'true':
            expires = datetime.utcnow() + timedelta(seconds=60 * 60)
            response.set_cookie('show_splash', 'false', expires=expires, httponly=False)
    except:
        response.set_cookie('show_splash', 'true')

    return response
Example #47
0
 def get(self):
     puzzles = Puzzle.gql("ORDER BY name ASC")
     pieces = self.get_pieces()
     locations = Location.gql("ORDER BY x ASC")
     svg_path = os.path.join(os.path.dirname(__file__), 'templates/puzzle.svg')
     svg_values = {
         "pieces": pieces,
         "locations": locations,
         "width": 641,
         "height": 481
     }
     svg_text = template.render(svg_path, svg_values)
     try:
         first_puzzle = puzzles[0]
     except IndexError:
         first_puzzle = "None"
     template_values = {
         "title": "HTML5 Hacks: SVG",
         "puzzles": puzzles,
         "first_puzzle": first_puzzle,
         "host": os.environ["HTTP_HOST"],
         "config": config,
         "svg_text": svg_text,
         "is_dev": IS_DEV,
         "rows": ["A", "B", "C", "D", "E", "F", "G", "H"],
         "cols": ["1", "2", "3", "4", "5", "6", "7", "8"],
     }
     path = os.path.join(os.path.dirname(__file__), 'templates/svg.html')
     self.response.out.write(template.render(path, template_values))
Example #48
0
def render_search():
    create_whoosh_dir()
    rest_ix = get_restaurant_index()
    loc_ix = get_location_index()
    cat_ix = get_category_index()

    restSearchableFields = ["name","phonenum"]
    locSearchableFields = ["address","neighborhood", "zipcode"]
    catSearchableFields = ["name"]

    restDataList = []
    locDataList = []
    catDataList = []

    if request.method == 'POST':
        search_query = request.form['search']
        restDataList = search_results(rest_ix, search_query, restSearchableFields)
        locDataList = search_results(loc_ix, search_query, locSearchableFields)
        catDataList = search_results(cat_ix, search_query, catSearchableFields)
        constructRelatedModels(restDataList, locDataList, catDataList)

    return render_template('search_results.html',
        restDataNames=Restaurant.getDataNames() + ["context"],
        restDataList=restDataList,
        locDataNames=Location.getDataNames() + ["context"],
        locDataList=locDataList,
        catDataNames=Category.getDataNames() + ["context"],
        catDataList=catDataList)
Example #49
0
def browse(request):
    # If a search query was passed in, see if we can find a matching location
    query = request.GET.get('lq', '').strip()
    if query:
        locations = Location.objects.filter(
            site_name__icontains=query,
            accepted=True
        ).values(
            'id',
            'site_name',
        )

        if len(locations) > 0:
            loc = locations[0]
            return redirect(
                'location-view',
                location_id=loc['id'],
                slug=slugify(loc['site_name']),
            )

    fields = Location.get_filter_fields()

    return render(request, 'browse.html', {
        'filters_main': fields[:6],
        'filters_more': fields[6:],
    })
Example #50
0
def get_single_location(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute(
            """
        SELECT
            a.id,
            a.name,
            a.address
        FROM location a
        WHERE a.id = ?
        """, (id, ))

        # Load the single result into memory
        data = db_cursor.fetchone()

        # Create an location instance from the current row
        location = Location(
            data['id'],
            data['name'],
            data['address'],
        )

        return json.dumps(location.__dict__)
Example #51
0
def get_all_employees():
    with sqlite3.connect("./kennel.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
            e.id,
            e.name,
            e.location_id,
            l.name location_name,
            l.address location_address
        FROM Employee e
        JOIN Location l
            ON l.id = e.location_id""")

        employees = []

        dataset = db_cursor.fetchall()

        for row in dataset:

            employee = Employee(row['id'], row['name'], row['location_id'])

            location = Location(row['location_id'], row['location_name'], row['location_address'])

            employee.location = location.__dict__

            employees.append(employee.__dict__)

    return json.dumps(employees)
Example #52
0
def addlocation(request):
    request.session.set_expiry(0)
    
    location = Location()
    location.name = request.POST['name']
    location.locationImg = request.POST['locationImg']
    location.description = request.POST['description']
    location.locationLink = request.POST['locationLink']
    location.longitude = request.POST['longitude']
    location.latitude = request.POST['latitude']
    user_id = request.POST['sel1']
    userUser = User.objects.get(id = user_id)
    user = User_Regular.objects.get(user = userUser)
    location.owner = user
    location.save() 

    return redirect('admin')
Example #53
0
        def put(self):
                """Add a location to the database"""
                building = self.request.get('building')
                floor = self.request.get('floor')
                location = Location.create() # todo AM

                db.put(location)
                memcache.delete(MC_LOCATIONS_KEY)
Example #54
0
 def get(self):
     logging.info("In HomeHandler")
     locations = Location.get_all()
     trips, params = StarTrip.query_from_request(self.request)
     template_values = {'trips': trips, 'locations': locations}
     template_values.update(params)
     html = render('home.html', template_values)
     self.response.write(html)
Example #55
0
def show_userlist():
    if auth.get_logged_in_user().admin:
        user_list = Location.select(Location.username, Location.device, Location.topic).distinct().order_by(Location.username.asc())
        return render_template('userlist.html', users = user_list, cur_user = auth.get_logged_in_user())
    else:
        # Only admins can get the full userlist
        # so go away. shoo, shoo.
        return redirect('/devicelist/%s' % auth.get_logged_in_user().username, 302)
Example #56
0
def newHop(request):
    title = "New Hop"
    if request.method=='POST':
        form = HopForm(request.POST)
        if form.is_valid():
            secretID = form.cleaned_data['secretID']
            oid = request.POST['object']
            object = get_object_or_404(Object, id=int(oid))
            if secretID == object.secretID:
                country = form.cleaned_data['country']
                city = form.cleaned_data['city']
                zipcode = form.cleaned_data['zipcode']
                street = form.cleaned_data['street']
                housenumber = form.cleaned_data['housenumber']
                longitude, latitude = util.getLonLat(country, city, zipcode, street, housenumber)
                l = Location(
                            country = country,
                            city = city,
                            zipcode = zipcode,
                            street = street,
                            housenumber = housenumber,
                            longitude = longitude,
                            latitude = latitude
                )
                l.save()
                note = form.cleaned_data['note']
                hop = Hop(objectID=object, user=request.user, location=l, note=note, submissionDate=datetime.datetime.now())
                hop.save()
                return redirect("/object/{0}".format(object.id))
            else:
                message = "The SecretID wasn't correct. Are you shure you have the object?"
        else:
            message = "The entered information wasn't valid. please check it."
        t = loader.get_template('main/newhop.html')
        context = util.generateContext(request, contextType = 'RequestContext', form=form, message=message, title=title)
        return HttpResponseServerError(t.render(context))
    else:
        form = HopForm()
        if request.method == 'GET':
            try:
                object = request.GET['obj']
            except:
                return redirect("/")
    context = util.generateContext(request, contextType = 'RequestContext', form = form, obj=object, title=title)
    return render_to_response('main/newhop.html', context)
Example #57
0
def airport_profile(request, navaid, ident):
    
    from plane.models import Plane
    from logbook.models import Flight
    from django.contrib.auth.models import User
    from django.http import Http404
    

    loc = Location.goof(loc_class__in=(1,2), identifier=ident)
    
    if loc.loc_class == 1 and navaid:
        raise Http404
    
    if loc.loc_class == 2 and not navaid:
        raise Http404
    
    users = Location.get_profiles(ident, 'identifier')
    
    tailnumbers = Plane.objects\
                       .exclude(tailnumber="")\
                       .values_list('tailnumber', flat=True)\
                       .filter(flight__route__routebase__location__identifier=ident)\
                       .order_by('tailnumber')\
                       .distinct()
                       
    t_flights = Flight.objects\
                      .filter(route__routebase__location__identifier=ident)\
                      .count()
                      
    lc = loc.get_loc_class_display().lower()
    
    previous_identifiers = HistoricalIdent.objects\
                               .filter(current_location=loc)
    
    if navaid:
        ty = 'navaid'
    else:
        ty = 'airport'
    
    kwargs ={'ident': loc.identifier, 'type': ty}
    
    kml_url = reverse("routes_for_location-kml", kwargs=kwargs)
    print kml_url
    
    return locals()
Example #58
0
    def get(self):
        location_key = ndb.Key('Location', 'HomeBase')
        exit_key = ndb.Key('Exit', 'HomeBase')


        # LOCATION_MAP = [ home_base, kitchen]
        command = self.request.get("command")

        exit = Exit(name="exit", description="exit desc", command="go exit")
        exit_key= exit.put()
        home_base = Location(name="asd", description="DESC", exits=exit_key)
        exit = exit_key.get()
        home_key = home_base.put()
        exit.target_loc = home_key
        exit_key = exit.put()


        user = users.get_current_user() #is this supposed to be None?

        if user is None:
            self.response.write('Please log in to continue...')
            self.response.headers['Content-Type'] = 'text/plain'
            return

        self.response.write('>> ' + command + "<br>")

        if None not in USERS:
            #set up initial user
            USERS[None] = home_base
            current_location = home_base
        else:
            current_location = USERS[None]

        self.request.current_location = current_location
        user = users.get_current_user()
        if command == "look":
            self.look()
        exit = current_location.exits.get()
        if command == exit.command:
            self.response.write("Changing location")
            USERS[None] = exit.target_loc.get()
            self.request.current_location = exit.target_loc.get()
            self.look()

        self.response.headers['Content-Type'] = 'text/plain'
Example #59
0
  def post(self, request_id):
    location = self.request.get('location')
    # Get request
    request = ndb.Key(urlsafe=request_id).get()
    location = location.split('^')

    # Check if location has been previously used
    existing_location = Location.query(Location.name == location[0], Location.address == location[1]).get()
    if existing_location is None:
      # Add new location
      categories = location[3].split(',')
      coordinates = location[4].split(' ')
      new_location = Location()
      new_location.name = location[0]
      new_location.address = location[1]
      new_location.image_url = location[2]
      for c in categories:
        new_location.categories.append(c)
      new_location.longitude = float(coordinates[0])
      new_location.latitude = float(coordinates[1])
      new_location.put()
      
    else:
      new_location = existing_location

    if request != None:
      # Check if already appended
      add = True
      if len(request.bidders) > 0:
        for bid in request.bidders:
          bid = bid.get()
          if bid.name == self.user_model.username:
            print "Already bid"
            add = False
      if add is True:
          print "Haven't bid"
          bidder = Bidder()
          bidder.sender = self.user_model.key
          bidder.location = new_location.key
          bidder.name = self.user_model.username
          bidder.bid_time = datetime.datetime.now() - datetime.timedelta(hours=8)
          bidder.price = request.price
          bidder.put()
          request.bidders.append(bidder.key)
          request.status = "pending"
          request.put()
    else:
      print "Already connected"

    self.redirect('/feed')