コード例 #1
0
ファイル: views.py プロジェクト: isbm/swg
def list_apartment(request):
    places = Places(get_connection(request))
    ret = list()
    for apartment in places.list_apartments():
        data = {
            'address': {
                'city': apartment.address.city,
                'street': apartment.address.street,
                'housenumber': apartment.address.housenumber,
            },
            'contact': {
                'phone': apartment.contact.phone,
                'nickname': apartment.contact.nickname,
                'email': apartment.contact.email,
                'person_name': apartment.contact.person_name,
            },
            'info': {
                'memo': apartment.info.memo,
                'price': apartment.info.price,
                'available_since': str(apartment.info.available_since),
                'rooms': apartment.info.rooms,
                'sqm': apartment.info.sqm,
            },
        }
        ret.append(data)
    return ret
コード例 #2
0
ファイル: views.py プロジェクト: isbm/swg
def add_apartment(request):
    ret = dict()
    places = Places(get_connection(request))

    if len(request.json_body) != 4:
        ret['error_code'] = 1
        ret['error_message'] = "JSON request is not correctly encoded"
    else:
        errors = list()
        rq_addr,rq_contact, rq_info, rq_apt = request.json_body

        rq_addr, err = _get_address(rq_addr)
        errors.append(err)
        rq_contact, err = _get_contact(rq_contact)
        errors.append(err)
        rq_info = _get_info(rq_info)
        if rq_addr and rq_contact and rq_info:
            rq_apt = _get_apartment(rq_apt, rq_addr, rq_contact, rq_info)
        else:
            rq_apt = None

        errors = [item for item in errors if item]
        if not errors and rq_apt:
            places.add_apartment(rq_apt)
            places.commit()
            ret['error_code'] = 0
            ret['error_message'] = 'Apartment has been added'
        else:
            ret['error_code'] = 2
            ret['error_message'] = ', '.join(errors)

    return ret
コード例 #3
0
def get_places():
    """
    This API analyses an image an returns the scenic place classification
    ---
    tags:
      - Image Analyzer
    consumes:
      - multipart/form-data
    produces: 
      -application/json
    parameters:
      - in: formData
        name: upfile
        type: file
        required: true
        description: Image file to analyse
    responses:
      500:
        description: Error, something went wrong!
      200:
        description: Detection success!
    """
    #logger=logging.getLogger(__name__)
    #logger.debug("Calling /places")
    model = Places()
    query_class = request.args.get('class')
    iFile = request.files.getlist('upfile')[0]
    img = load_image(iFile)
    img = rotate_image(img, iFile)
    img = limit_size_image(img)
    response = model.get_tags(img, query_class)
    return jsonify(response)
コード例 #4
0
def next_recommendation(m, user_id):
    global cat, counter, name, address, latitude, longitude
    loc = users.get_user_location_by_user_id(m.chat.id)
    result = nearby_places(loc.latitude, loc.longitude, cat)

    if result is None:
        bot.send_message(m.chat.id, "Lo siento, cerca de tu localización no encuentro ningún/ninguna "
                         + Places.get_instance().get_place_name(cat))
        bot.send_sticker(m.chat.id, PEPE_CRY, reply_markup=types.ReplyKeyboardRemove())
        users.store_step(user_id, START)

    else:
        if counter >= len(result):
            bot.send_message(m.chat.id, "Lo siento, no encuentro más resultados en tu zona")
            bot.send_sticker(m.chat.id, PEPE_CRY, reply_markup=types.ReplyKeyboardRemove())
            users.store_step(user_id, START)
            counter = 0
            return
        loc = result[counter].get('geometry').get('location')
        name = result[counter].get('name')
        address = result[counter].get('vicinity')
        latitude = loc.get('lat')
        longitude = loc.get('lng')
        bot.send_location(m.chat.id, latitude, longitude)
        bot.send_message(m.chat.id, "He encontrado este " + Places.get_instance().get_place_name(cat)
                         + " cerca de ti, ¿Qué te parece?\n*" + name
                         + "*\nDirección: _" + address + "_",
                         reply_markup=user_likes.recommendation_select, parse_mode="Markdown")
        counter += 1
        users.store_step(user_id, RECOMMENDATIONS)
コード例 #5
0
 def __init__(self, access_token=''):
     self.Account = Account(access_token=access_token)
     self.Apps = Apps(access_token=access_token)
     self.Audio = Audio(access_token=access_token)
     self.Auth = Auth(access_token=access_token)
     self.Board = Board(access_token=access_token)
     self.Database = Database(access_token=access_token)
     self.Docs = Docs(access_token=access_token)
     self.Other = Other(access_token=access_token)
     self.Fave = Fave(access_token=access_token)
     self.Friends = Friends(access_token=access_token)
     self.Gifts = Gifts(access_token=access_token)
     self.Groups = Groups(access_token=access_token)
     self.Likes = Likes(access_token=access_token)
     self.Market = Market(access_token=access_token)
     self.Messages = Messages(access_token=access_token)
     self.Newsfeed = Newsfeed(access_token=access_token)
     self.Notes = Notes(access_token=access_token)
     self.Notifications = Notifications(access_token=access_token)
     self.Pages = Pages(access_token=access_token)
     self.Photos = Photos(access_token=access_token)
     self.Places = Places(access_token=access_token)
     self.Polls = Polls(access_token=access_token)
     self.Search = Search(access_token=access_token)
     self.Stats = Stats(access_token=access_token)
     self.Status = Status(access_token=access_token)
     self.Storage = Storage(access_token=access_token)
     self.Users = Users(access_token=access_token)
     self.Utils = Utils(access_token=access_token)
     self.Video = Video(access_token=access_token)
     self.Wall = Wall(access_token=access_token)
     self.Widgets = Widgets(access_token=access_token)
コード例 #6
0
def recommendations_yes_or_no(m):
    global cat, name, address, latitude, longitude
    cid = m.chat.id
    user_id = users.get_user_by_id(cid)

    text = m.text
    bot.send_chat_action(cid, 'typing')
    time.sleep(0.5)

    if text == 'Me gusta 😍':
        end_message(m, user_id)

        categories = Places.get_instance().get_category(cat)

        for category in categories:
            PlacesController.get_instance().create_place(name, latitude, longitude, address, category, cat, user_id)

    elif text == 'Prueba con otro 🔄':
        bot.send_message(cid, "Vamos a ver...", reply_markup=types.ReplyKeyboardRemove())
        bot.send_chat_action(cid, 'typing')
        time.sleep(0.5)
        next_recommendation(m, user_id)
        users.store_step(user_id, RECOMMENDATIONS)
    elif text == 'Cancelar ❌':
        command_text_bye(m)
    else:
        bot.send_message(cid, "Por favor, utiliza solo los botones")
コード例 #7
0
    def __init__(self):
        self.client = zulip.Client(site="https://saharsh.zulipchat.com/api/")
        self.subscribe_all()
        self.trans = Translate()
        self.tw = Twimega()
        self.pnr = Pnr()
        self.weather = Weather()
        self.geo = Geocode()
        self.searching = Places()
        self.help = Help()

        print("Initialization Done ...")
        self.subkeys = [
            "translate", "weather", "pnr", "post", "post_image", "twitter",
            "help", "search"
        ]
コード例 #8
0
 def __init__(self, server, id_, start_production, end_production):
     self.id_ = id_
     self.start_production = datetime(int(start_production[:4]),
             int(start_production[4:6]), int(start_production[6:8]))
     self.end_production = datetime(int(end_production[:4]),
             int(end_production[4:6]), int(end_production[6:8]))
     self.stop_areas = StopAreas(server, self)
     self.places = Places(self.stop_areas)
     self.journeys = Journeys(self)
     self.server = server
コード例 #9
0
ファイル: osmhandler.py プロジェクト: KDE/silk
    def __init__(self, types, location, parent=None):
        """Initialize Places.

        @param types: list of allowed types of places
        @type types: list
        @param location: location from main aplication, needed for fall back
        @type location: Location
        @param parent: parent object
        @type parent: OSM
        """
        QXmlDefaultHandler.__init__(self)
        self._location = location
        self._parent = parent
        self._place = ""
        self._places = Places()
        self._valid_types = types
        self._error_str = ""
        self._reverse_geo = False
        self._current_text = ""
        self._querystring = ""
        self._osm_id = 0
コード例 #10
0
class ZulipBot(object):
    def __init__(self):
        self.client = zulip.Client(site="https://saharsh.zulipchat.com/api/")
        self.subscribe_all()
        self.trans = Translate()
        self.tw = Twimega()
        self.pnr = Pnr()
        self.weather = Weather()
        self.geo = Geocode()
        self.searching = Places()
        self.help = Help()

        print("Initialization Done ...")
        self.subkeys = [
            "translate", "weather", "pnr", "post", "post_image", "twitter",
            "help", "search"
        ]

    def subscribe_all(self):
        json = self.client.get_streams()["streams"]
        streams = [{"name": stream["name"]} for stream in json]
        self.client.add_subscriptions(streams)

    def process(self, msg):
        content = msg["content"].split()
        sender_email = msg["sender_email"]
        ttype = msg["type"]
        stream_name = msg['display_recipient']
        stream_topic = msg['subject']
        if sender_email == BOT_MAIL:
            return
        if content[0].lower() == "ninjas33" or content[0] == "@**ninjas33**":
            if content[1].lower() == "translate":
                ip = content[2:]
                ip = " ".join(ip)
                message = self.trans.translate(ip)

                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "pnr":
                message = self.pnr.get_pnr(content[2])
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "twitter":
                if len(content) > 2 and content[2] == "post":
                    if self.tw.stream == msg["display_recipient"]:
                        status = self.tw.post(" ".join(content[3:]))
                        x = json.dumps(status._json)
                        x = json.loads(x)
                        message = "https://twitter.com/{}/status/{}".format(
                            x["user"]["screen_name"], x["id_str"])
                        message = "Tweet Posted\n" + message
                        self.client.send_message({
                            "type": "stream",
                            "subject": msg["subject"],
                            "to": msg["display_recipient"],
                            "content": message
                        })
                    else:
                        message = "Use the stream **{}** to post a tweet".format(
                            self.tw.stream)
                        self.client.send_message({
                            "type": "stream",
                            "to": sender_email,
                            "content": message
                        })

            if len(content) > 2 and content[2] == "post_image":
                if self.tw.stream == msg["display_recipient"]:
                    status = self.tw.post_image(content[3],
                                                " ".join(content[4:]))
                    if isinstance(status, str):
                        message = status
                    else:
                        x = json.dumps(status._json)
                        x = json.loads(x)
                        message = "https://twitter.com/{}/status/{}".format(
                            x["user"]["screen_name"], x["id_str"])
                        message = "Tweet Posted\n" + message
                    self.client.send_message({
                        "type": "stream",
                        "subject": msg["subject"],
                        "to": msg["display_recipient"],
                        "content": message
                    })
                else:
                    message = "Use the stream **{}** to post a tweet".format(
                        self.tw.stream)
                    self.client.send_message({
                        "type": "private",
                        "to": sender_email,
                        "content": message
                    })

            if content[1].lower() == "help" and len(content) == 2:
                message = self.help.get_help()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "weather":
                place = " ".join(content[2:])
                try:
                    result = self.weather.getWeather(self.geo.convert(place))
                    message = "**" + "Weather update of " + place + "**" + "\n" + "Summary : " + "**" + result[
                        "currently"][
                            "summary"] + "**" + "\n" + "Temparature : " + "**" + str(
                                result["currently"]["temperature"]
                            ) + "**" + '\n' + "Apparent Temparature : " + "**" + str(
                                result["currently"]["apparentTemperature"]
                            ) + "**" + "\n" + "Dew Point : " + "**" + str(
                                result["currently"]["dewPoint"]
                            ) + "**" + "\n" + "Humidity : " + "**" + str(
                                result["currently"]["humidity"]) + "**"
                except KeyError:
                    message = "Not Working Right Now"
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "search":
                place = " ".join(content[2:])
                try:
                    result = self.searching.getPlaces(place)
                    y = result['results']
                    message = "Result for search \n"
                    #print(result)
                    for i in range(len(y)):
                        message += str(
                            i + 1) + ". " + y[i]['name'] + " , Rating:" + str(
                                y[i]['rating']
                            ) + " \n Address : " + y[i]['formatted_address']
                        message += "\n"
                except KeyError:
                    message = "Not Working Right Now"
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1] not in self.subkeys:
                ip = content[1:]
                ip = " ".join(ip)
                message = self.chatbot.get_response(ip).text
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

        elif "ninjas33" in content and content[0] != "ninjas33":
            self.client.send_message({
                "type": "stream",
                "subject": msg["subject"],
                "to": msg["display_recipient"],
                "content": "Hey there! :blush:"
            })
        else:
            return
コード例 #11
0
ファイル: test.py プロジェクト: isbm/swg
from places import Places
from places import place


places = Places("db/places")
for x in range(10):
    address = place.Address('Erlangen', 'Scheissstrasse', x)
    contact = place.Contact('123-123-123', '*****@*****.**', 'foobar', 'N/A')
    info = place.Info(700, rooms=2, sqm=50, day=16, month=5, memo='some free text here, e.g. your mama is fat!')
    apartment = place.Apartment(address=address, contact=contact, info=info, rating=3)
    places.add_apartment(apartment)
places.commit()

print "-" * 80
print "Found apartments:"
print "-" * 80
for apartment in places.list_apartments():
    print "Address:", apartment.address
    print "Contact:", apartment.contact
    print "Info:", apartment.info
    print "." * 80
コード例 #12
0
ファイル: plot.py プロジェクト: tafseerahmed/WIDEhackathon
import sys, json
import plotly.offline as py

from places import Places
from search import paged_search, vectorized

if len(sys.argv) != 2:
    print('Usage: %s <subject>' % sys.argv[0])
    sys.exit(1)

SUBJECT = sys.argv[1]

places = Places('yso-paikat-skos.rdf')
results = paged_search(SUBJECT, places)
print(results)
vector = vectorized(results, places)
print(vector)

points = []
for point in vector:
    points.append(list(point))

basemap = []
with open('finland.geojson', 'r') as f:
    geojson = json.load(f)

    for feature in geojson['features']:
        if feature['geometry']['type'] == 'Polygon':
            basemap.extend(feature['geometry']['coordinates'][0])
            basemap.append([None, None])
コード例 #13
0
    def setUp(self):
        """Set up Places object with test data."""

        TestFile.create_test_json()
        self.testplaces: Places = Places("tests/test.json")
コード例 #14
0
ファイル: osmhandler.py プロジェクト: KDE/silk
 def clear_places(self):
     """Resets places."""
     self._places = Places()
コード例 #15
0
ファイル: osmhandler.py プロジェクト: KDE/silk
class OSMHandler(QXmlDefaultHandler):

    """Class processing XML data from OSM service and holding places.

    Class is procesing data from xapi.openstreetmap.org and from
    nominatim.openstreetmap.org.
    """

    def __init__(self, types, location, parent=None):
        """Initialize Places.

        @param types: list of allowed types of places
        @type types: list
        @param location: location from main aplication, needed for fall back
        @type location: Location
        @param parent: parent object
        @type parent: OSM
        """
        QXmlDefaultHandler.__init__(self)
        self._location = location
        self._parent = parent
        self._place = ""
        self._places = Places()
        self._valid_types = types
        self._error_str = ""
        self._reverse_geo = False
        self._current_text = ""
        self._querystring = ""
        self._osm_id = 0

    def startElement(self, namespaceURI, localName, name, attrs):
        """Called on every start element of XML file.

        On elements from xapi creates Place object and set attributes.
        On elements from nominatim sets display_name(address) and if place
        is valid, add it to the Places.
        """
        # Node from xapi - create Place
        if name == "node":
            self._place = Place(str(attrs.value("id")))
            self._place.set_lat(str(attrs.value("lat")))
            self._place.set_lon(str(attrs.value("lon")))
        # Tag from xapi - assign name and type
        elif name == "tag":
            if attrs.value("k") == "name":
                self._place.set_name(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "amenity":
                if str(attrs.value("v")) in self._valid_types:
                    self._place.set_amenity(str(attrs.value("v")))
            elif attrs.value("k") == "website":
                self._place.set_website(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "cuisine":
                self._place.set_cuisine(unicode(attrs.value("v"), "utf-8"))
            elif attrs.value("k") == "opening_hours":
                self._place.set_opening_hours(unicode(attrs.value("v"),
                "utf-8"))
        # Place from nominatim - set display_name
        elif name == "reversegeocode":
            self._reverse_geo = True
            self._querystring = attrs.value("querystring")
        elif name == "result":
            if self._reverse_geo:
                self._osm_id = str(attrs.value("osm_id"))
        self._current_text = ""
        return True

    def endElement(self, namespaceURI, localName, name):
        """Called on every end element of XML file."""
        # When we are at the end of node from xapi add place to places.
        if name == "node" and self._place.is_valid():
            self._places.add(self._place)
        # End of data from nominatim
        elif name == "result":
            if self._reverse_geo:
                self._places.set_display_name(self._osm_id, self._current_text)
                # Send places to dataengine
                self._parent.send_place(self._osm_id)
        elif name == "reversegeocode":
            self._reverse_geo = False
            self._osm_id = 0
        elif name == "error":
            if self._reverse_geo:
                self._error_str = self._current_text
                return False
        return True

    def characters(self, string):
        """Remember XML values."""
        self._current_text += unicode(string, "utf-8")
        return True

    def fatalError(self, exception):
        """Called in case of error.

        If nominatim can't find the id, try fall back mode.
        """
        if self._error_str == "OSM ID Not Found":
            try:
                (rest, osm_id) = str(self._querystring).rsplit("=", 1)
                self._places.set_display_name(osm_id, "%s, %s, %s" % \
                (self._places.search(osm_id).get_name(),
                self._location.getCity(), self._location.getCountry()), True)
                self._parent.send_place(osm_id)
            except Exception:
                pass
            return True
        raise Exception(self._error_str)

    def errorString(self):
        """Returns error string.

        @return: error string
        @rtype:str
        """
        return self._error_str

    def get_places(self):
        """Returns places.

        @return: places
        @rtype: Places
        """
        return self._places

    def clear_places(self):
        """Resets places."""
        self._places = Places()
コード例 #16
0
    MessageEvent, TextMessage, TextSendMessage, SourceUser, SourceGroup,
    SourceRoom, TemplateSendMessage, ConfirmTemplate, MessageAction,
    ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URIAction,
    PostbackAction, DatetimePickerAction, CarouselTemplate, CarouselColumn,
    PostbackEvent, StickerMessage, StickerSendMessage, LocationMessage,
    LocationSendMessage, ImageMessage, VideoMessage, AudioMessage, FileMessage,
    ImageSendMessage, UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent,
    BeaconEvent, FlexSendMessage, BubbleContainer, ImageComponent,
    BoxComponent, TextComponent, SpacerComponent, IconComponent,
    ButtonComponent, SeparatorComponent, CarouselContainer, QuickReply,
    QuickReplyButton, LocationAction, CameraAction, CameraRollAction,
    ImagemapSendMessage)

app = Flask(__name__)
weather = Weather()
places = Places()
flight_api = FlightApi()
weather_aqi = WeatherAQI()
channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)

if channel_secret is None:
    print('Specify LINE_CHANNEL_SECRET as environment variable.')
    sys.exit(1)
if channel_access_token is None:
    print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
    sys.exit(1)
static_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp')

line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)
コード例 #17
0
def parse_place(s):
    return Places(s, 0, 0)
コード例 #18
0
ファイル: main.py プロジェクト: ashley190/travelapp
from users import User
from userfile import UserFile
from places import Places
from get_poi import TripAdvisorApi
from poi_data import PoiData

# Initialise user object and conduct API_key_check
# If no API key, user given instructions to subscribe.
# API_key saved as a persistent environment variable in src/.env and
# application rebooted, If there is a stored API_key, application
# will proceed.
user = User()

# place selection
place = Places()
selected_region = place.select_region()

# userfile object creation to search past history and display result if exists
user_file = UserFile(selected_region, user.path)
user_file.searchfile = f"{user_file.region[0]}-{user_file.region[1]}.json"

# history check at region level
history_check = user_file.search_and_display_data(selected_region)

# history check at city level
if not history_check:
    user_file.city = place.select_city(user_file.region)
    user_file.searchfile = f"{user_file.city[0]}-{user_file.city[1]}.json"
    history_check = user_file.search_and_display_data(user_file.city)

# look up TripAdvisorAPI if region and city does not exist in cached file