''' interfaces.py
A module containing two interfaces for the lunar lander game.
The graphic lander interface allows the game to be played graphically, while the text lander
interface allows the game to be played by text only through the terminal.
'''

import sys
try:
    import graphics
except ImportError:
    sys.stderr.write("Couldn't import graphics.py module.\n")
    sys.stderr.write("This is fine for Part I of the assignment.\n")
    sys.stderr.write("For Part II you should make sure that graphics.py" +
                                " is in the correct directory.\n")

class TextLanderInterface:
    '''Text-based interface for lander game. Use this one for testing'''

    def showInfo(self, lander):
        '''Display lander's status to user'''
        altitude = lander.getAltitude()
        velocity = lander.getVelocity()
        fuel = lander.getFuel()
        print("Altitude is", altitude, "meters.\nVelocity is", velocity, ".\nFuel left is", fuel)

    def getThrust(self):
        '''Get thrust amount from user. Returns thrust amount as an int.'''
        thrustAmountString = input("Thrust amount? ")
        if thrustAmountString == "":
            return 0
        return int(thrustAmountString)

    def showCrash(self):
        '''Display to user that we crashed'''
        print("Crash! Oh noes!")

    def showLanding(self):
        '''Display to user that we landed safely'''
        print("Hooray, the Eagle has landed!")

    def close(self):
        '''Close the interface'''
        print("Goodbye")

class GraphicLanderInterface:
    '''GraphicLanderInterface class is a graphical interface
        for your lunar lander game. Used in part 2 of the assignment.'''

    def __init__(self):
        '''Constructor that initializes the graphics window
        and shapes that we will use for drawing things'''

        # initialize window
        self.win = graphics.GraphWin("Lunar Lander Game", 320, 500)
        # transform coordinates
        self.win.setCoords(0, -10, 300, 600)

        self.background = graphics.Image(graphics.Point(500, 550), "largeSpace.gif")
        self.background.draw(self.win)

        self.surfacePolygon = self.createSurface()
        self.surfacePolygon.draw(self.win)

        self.landerPolygon = None

        self.text = None   #used to store displayed information about the lander
        self.descriptors = None

    def showInfo(self, lander):
        '''This method gets the lander's info and displays them to the user.
        Then a lander is drawn in the graphics window.'''
        self.text = graphics.Text(graphics.Point(80, 520), "")
        alt = lander.getAltitude()
        vel = lander.getVelocity()
        fuel = lander.getFuel()
        infoString = str(alt) + "                  " + str(vel) + "              " + str(fuel)
        self.text.setText(infoString)   #putting the lander's values into self.text
        self.text.setTextColor("white")
        self.text.setStyle("bold")
        self.text.draw(self.win)
        self.descriptors = graphics.Text(graphics.Point(85, 540), "Altitude       Velocity       Fuel")
        self.descriptors.setTextColor("white")
        self.descriptors.setStyle("bold")
        self.descriptors.draw(self.win)

        # if lander polygon is drawn, undraw it
        if self.landerPolygon:
            self.landerPolygon.undraw()
        self.landerPolygon = graphics.Polygon(graphics.Point(self.win.width / 2 - 10, alt),
                graphics.Point(self.win.width/2 - 3, alt + 10),
                graphics.Point(self.win.width/2 + 3, alt + 10),
                graphics.Point(self.win.width/2 + 10, alt))
        self.landerPolygon.setFill("gray")
        self.landerPolygon.draw(self.win)

    def getThrust(self):
        '''This method waits for a user's mouse click then returns
        an integer as the thrust amount. User has the option of using 0-3 units of thrust'''
        thrust1Button = graphics.Rectangle(graphics.Point(10, 410), graphics.Point(60, 450))
        thrust1Button.setFill("red")   #makes each button easier to differentiate
        thrust1Button.draw(self.win)
        thrust1Text = graphics.Text(graphics.Point(35, 400), "1 Thrust")
        thrust1Text.setTextColor("white")
        thrust1Text.setStyle('bold')
        thrust1Text.draw(self.win)

        thrust2Button = graphics.Rectangle(graphics.Point(70, 410), graphics.Point(120, 450))
        thrust2Button.setFill("blue")
        thrust2Button.draw(self.win)
        thrust2Text = graphics.Text(graphics.Point(95, 400), "2 Thrust")
        thrust2Text.setTextColor("white")
        thrust2Text.setStyle('bold')
        thrust2Text.draw(self.win)

        thrust3Button = graphics.Rectangle(graphics.Point(10, 350), graphics.Point(60, 390))
        thrust3Button.setFill("yellow")
        thrust3Button.draw(self.win)
        thrust3Text = graphics.Text(graphics.Point(35, 340), "3 Thrust")
        thrust3Text.setTextColor("white")
        thrust3Text.setStyle('bold')
        thrust3Text.draw(self.win)

        noThrustButton = graphics.Rectangle(graphics.Point(70, 350), graphics.Point(120, 390))
        noThrustButton.setFill("black")
        noThrustButton.draw(self.win)
        noThrustText = graphics.Text(graphics.Point(95, 340), "No thrust")
        noThrustText.setTextColor("white")
        noThrustText.setStyle('bold')
        noThrustText.draw(self.win)

        validClick = False
        while validClick == False:
            clickLocation = self.win.getMouse()
            clickX = clickLocation.getX()
            clickY = clickLocation.getY()
            if clickX >= 10 and clickX <= 60:  #checking which button the click's
                                               #coordinate matches
                if clickY >= 410 and clickY <= 450:
                    thrust1Text.undraw()
                    thrust2Text.undraw()
                    thrust3Text.undraw()
                    noThrustText.undraw()
                    self.text.undraw()
                    self.descriptors.undraw()
                    validClick = True  #a valid click is given, so the turn proceeds
                    return 1
                elif clickY >= 350 and clickY <= 390:
                    thrust1Text.undraw()
                    thrust2Text.undraw()
                    thrust3Text.undraw()
                    noThrustText.undraw()
                    self.text.undraw()
                    self.descriptors.undraw()
                    validClick = True
                    return 3
            elif clickX >= 70 and clickX <= 120:
                if clickY >= 410 and clickY <= 450:
                    thrust1Text.undraw()
                    thrust2Text.undraw()
                    thrust3Text.undraw()
                    noThrustText.undraw()
                    self.text.undraw()
                    self.descriptors.undraw()
                    validClick = True
                    return 2
                elif clickY >= 350 and clickY <= 390:
                    thrust1Text.undraw()
                    thrust2Text.undraw()
                    thrust3Text.undraw()
                    noThrustText.undraw()
                    self.text.undraw()
                    self.descriptors.undraw()
                    validClick = True
                    return 0

    def showCrash(self, lander):
        '''Crash message... displays an image of a crashed lunar lander and displays
        a graphical text to the user saying that the lander has crashed. Gives the user
        a score based on his / her performance.'''
        self.landerPolygon.undraw()
        self.landerPolygon = graphics.Polygon(graphics.Point(self.win.width / 2 - 13, 0),
                graphics.Point(self.win.width/2 - 6, 10),
                graphics.Point(self.win.width/2 - 3, 10),
                graphics.Point(self.win.width/2 - 3, 0))
        self.landerPolygon = graphics.Image(graphics.Point(100, 150), "explosion.gif")
        self.landerPolygon.draw(self.win)
        #displays an image of an explosion to show the crash of the lander
        crash = graphics.Text(graphics.Point(150, 460), "Crash! Oh noes!")
        crash.setStyle("bold")
        crash.setSize(30)
        crash.setFace("helvetica")
        crash.setTextColor("white")
        crash.draw(self.win)
        fuel = lander.getFuel()
        velocity = lander.getVelocity()
        scoreCalc = int(fuel + (100 / (-1 * velocity)))
        #self-derived formula for calculating a player's score. The higher the velocity,
        #the lower the score will be, (vel *-1 as vel will be negative upon reaching the surface).
        #Likewise, the more fuel left, the higher the score will be.
        scoreString = "Your overall score is: " + str(scoreCalc)
        score = graphics.Text(graphics.Point(150, 430), scoreString)
        score.setFill("red")
        score.draw(self.win)
        self.win.getMouse()
        if self.win.getMouse():
            self.win.close()

    def showLanding(self, lander):
        '''Landing message... displays a celebratory graphical text to inform the user that
        the lander has safely landed. Gives the user a score based on his / her performance.'''
        self.landerPolygon.undraw()
        self.landerPolygon = graphics.Polygon(graphics.Point(self.win.width / 2 - 10, 0),
                graphics.Point(self.win.width/2 - 3, 10),
                graphics.Point(self.win.width/2 + 3, 10),
                graphics.Point(self.win.width/2 + 10, 0))
        self.landerPolygon.setFill("gray")
        self.landerPolygon.draw(self.win)
        safe = graphics.Text(graphics.Point(150, 330), "Hooray,\n the Eagle has landed!")
        safe.setStyle('bold')
        safe.setTextColor('red')
        safe.setSize(30)
        safe.setFace('helvetica')
        fuel = lander.getFuel()
        velocity = lander.getVelocity()
        scoreCalc = int(fuel + (100 / (-1 * velocity)) + 20)   #bonus 20 points for
                                                               #successful landing
        scoreString = "Your overall score is: " + str(scoreCalc)
        score = graphics.Text(graphics.Point(150, 190), scoreString)
        score.setFill("red")
        score.draw(self.win)
        safe.draw(self.win)
        self.win.getMouse()
        if self.win.getMouse():  #waits for user mouse click before continuing
            self.win.close()

    def close(self):
        self.win.close()

    def createSurface(self):
        '''Draws the surface of the moon'''
        circ = graphics.Circle(graphics.Point(160, -795), 800)  #draws a curved moon
                                                                #surface to look more realistic
        circ.setFill("gray")
        return circ

Lunar Lander - Interface (Object Oriented).py


#!/usr/bin/env python3

# Chapter 10 Practice Debugging Coin Toss

import random

guess = ''
while guess not in (int(1), int(0)): #Changed heads and tails to 1 and 0 and made integers
    print('猜硬币，0或者1:') #Added 1 and 0
    guess = int(input()) #Turned string into integer

toss  = random.randint(0, 1) # 0 is tails, 1 is heads
if toss == guess:
    print('你赢了!')
else:
    print('错了，再猜!')
    guess = int(input()) #guess misspelled with three 's' instead of two and made guess integer
    if toss == guess:
        print('你赢了!')
    else:
        print('错了，表现糟糕.')


import sys, pdb, rdflib
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
import datetime, requests, json
from SPARQLWrapper import SPARQLWrapper, XML, JSON

def get_uri(term):
    # print(doc)
    results = []
    jsonDocs = {}
    term = (str(term))
    # print(term)
    url='http://fast.oclc.org/searchfast/fastsuggest?query='+term+'&queryIndex=suggestall   &queryReturn=suggestall,idroot,auth,tag,type,raw,breaker,indicator&suggest=autoSubject&rows=5'
    # print(term)
    r = requests.get(url)
    r.raise_for_status()
    rjson = r.json()
    # print(r.text)
    jsonDocs = rjson['response']['docs']
    # print(jsonDocs)
    fastValues = None
    if jsonDocs:
        for x in jsonDocs:
            # print(x)
            suggest = x['suggestall'][0]
            auth = x['auth']
            fastID = x['idroot']
            print('original: '+term +' | '+ 'FAST: '+ suggest +' ('+fastID+')')
            user_response = input("Select this FAST heading? [y/n/x]")
            if user_response.lower().startswith("y"):
                fastValues = fastID, suggest
                results.append(fastValues)
                break
            if user_response.lower().startswith("x"):
                fastValues = '',''

                results.append(fastValues)
                break
        if fastValues is None:
            print("No heading has been selected; '" + term +"' will be retained.")
            fastValues = '', term
            results.append(fastValues)
    else:
        print('No matches found for '+ term +'; the original term will be retained')

            # fastValues = '',term
            # results.append(fastValues)

    return results

def get_aat(term):

    # first method
    # s = sparql.Service('http://vocab.getty.edu/sparql', "utf-8", "GET")
    # query = ('select * {?term rdfs:label "' + term +'"@en}')
    # r = sparql.query('http://vocab.getty.edu/sparql', query)
    # for row in r:
    #     # print ('row:', row)
    #     values = sparql.unpack_row(row)
    #     print (values[0], "-", values[1])

#second method (doesnt work)
    # sparql = SPARQLWrapper("http://vocab.getty.edu")
    # sparql.setQuery('select * {?term rdfs:label "' + term +'"@en}')
    #
    # sparql.setReturnFormat(JSON)
    # results = sparql.query().convert()
    # print(results)

#third method - sort of works
    url = 'http://vocab.getty.edu/sparql'
    query = 'select ?term ?termLabel {?term rdfs:label "' + term +'"@en}'
    # print(query)
    r = requests.get(url, params = {'format': 'json', 'query': query})
    data = r.json()

    print(data)
    # results = term

    results=term

    return results

###
# ?x gvp:prefLabelGVP [xl:literalForm ?label]
#
#
#
# http://vocab.getty.edu/sparql.json?query=select+*+%7B%3Fx+luc%3Aterm+%22vincent+van+gogh%22%3Bskos%3AinScheme+ulan%3A%3Bgvp%3AprefLabelGVP%2Fxl%3AliteralForm+%3Fname%3Brdf%3Atype+gvp%3APersonConcept%7D&_implicit=false&implicit=true&_equivalent=false&_form=%2Fsparql

###

def getMetadata(infile_path):
    tree=ET.parse(infile_path)
    root=tree.getroot()
    doc = {}
    ns = {'mods':'http://www.loc.gov/mods/v3'}

#get topical subjects
    for subjects in root.findall('mods:subject',ns):
    #
    #     for topic in subjects.findall('mods:topic',ns):
    #         term = topic.text
    #
    #         if 'valueURI' not in topic.attrib:
    #             for result in get_uri(term):
    #                 if len(result[0]) > 0:
    #                     topic.set('authority', 'fast')
    #                     topic.text = result[1]
    #                     topic.set('valueURI','http://id.worldcat.org/fast/'+result[0])
    #                 else:
    #                     topic.text = result[1]
    #         else:
    #             continue

#get uris for geographic subjects
        # for place in subjects.findall('mods:geographic',ns):
        #     # print(place.text)
        #     placeTerm = place.text
        #     if 'valueURI' not in place.attrib:
        #         for result in get_uri(placeTerm):
        #             if len(result[0]) > 0:
        #                 place.set('authority', 'fast')
        #                 place.text = result[1]
        #                 place.set('valueURI','http://id.worldcat.org/fast/'+result[0])
        #             else:
        #                 place.text = result[1]
        #             # print(place.attrib)
        #
        #     else:
        #         continue

# get uris for subject names
        for name in subjects.findall('mods:name',ns):
            # print(name.attrib)
            for namePart in name.findall('mods:namePart',ns):
                if 'valueURI' not in name.attrib:
                    nameTerm = namePart.text
                    # print(nameTerm)
                    for result in get_uri(nameTerm):
                        if len(result[0]) > 0:
                            name.set('authority', 'fast')

                            name.set('valueURI','http://id.worldcat.org/fast/'+result[0])
                            namePart.text = result[1]
                        if len(result[1]) > 0:
                            namePart.text = result[1]
                        else:
                            continue

            else:
                continue

#get uris for any names not in subjects
    # for name in root.findall('mods:name',ns):
    #     # print(name.text)
    #     for namePart in name.findall('mods:namePart',ns):
    #         if 'valueURI' not in name.attrib:
    #             nameTerm = namePart.text
    #             # print(nameTerm)
    #             for result in get_uri(nameTerm):
    #                 if len(result[0]) > 0:
    #                     name.set('authority', 'fast')
    #
    #                     name.set('valueURI','http://id.worldcat.org/fast/'+result[0])
    #                     namePart.text = result[1]
    #                     # print(result[0])
    #                     # print(name.attrib)
    #
    #     else:
    #         continue

#get uris for place in originInfo
    # for place in root.findall('mods:originInfo/mods:place/mods:placeTerm',ns):
    #
    #     if 'valueURI' not in place.attrib:
    #         placeTerm = place.text.replace('-',' ')
    #
    #         # print(placeTerm)
    #         for result in get_uri(placeTerm):
    #             print(result)
    #             if len(result[0]) > 0:
    #                 place.set('authority', 'fast')
    #                 print(place.attrib)
    #                 place.text = result[1]
    #                 place.set('valueURI','http://id.worldcat.org/fast/'+result[0])
    #             else:
    #                 place.text = result[1]
    #             # print(place.attrib)
    #
    #     else:
    #         continue
    # return root

#get uris for _form
    for form in root.findall('mods:physicalDescription/mods:form',ns):
        # print(form.attrib)

        if 'valueURI' not in form.attrib:
            formTerm = form.text

            # print(formTerm)
            for result in get_aat(formTerm):
                x=1
        #         if len(result[0]) > 0:
        #             place.set('authority', 'fast')
        #             print(place.attrib)
        #             place.text = result[1]
        #             place.set('valueURI','http://id.worldcat.org/fast/'+result[0])
        #         else:
        #             place.text = result[1]
        #         # print(place.attrib)
        #
        # else:
        #     continue
    return root

def main():
    infile_path = sys.argv[1]
    outfile_path = 'mods_test'+sys.argv[1]

    doc=getMetadata(infile_path)
    tree=ET.ElementTree(doc)
    ET.register_namespace('mods',"http://www.loc.gov/mods/v3")

    tree.write('rev'+outfile_path, encoding="utf8")

if __name__ == '__main__':
    main()


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

def post_order(start, end):
    if start > end:
        return
    mid = end + 1
    for i in range(start + 1, end + 1):
        if tree[start] < tree[i]:
            mid = i
            break
    post_order(start + 1, mid - 1)
    post_order(mid, end)
    print(tree[start])

tree = []
while True:
    try:
        tree.append(int(input()))
    except:
        break

post_order(0, len(tree) - 1)


import pandas as pd
import numpy as np

appendix_1 = list()
appendix_1.append([])
appendix_1.append(pd.read_csv('Participium_deel_1.csv', index_col=0))
appendix_1.append(pd.read_csv('Participium_deel_2.csv', index_col=0))

def generate_word_list(sections_to_include):
    try:
        word_list_gen = pd.concat(sections_to_include)
    except TypeError:
        word_list_gen = sections_to_include
    return word_list_gen

def ask_a_participium():
    array_infinitives = word_list.index.to_numpy()
    infitinive = np.random.choice(array_infinitives)
    correct_answer = word_list.loc[infitinive, 'participium']
    answer = input(f'Wat is het participium van {infitinive}?\n')

    if answer == 'engels':
        english_word = word_list.loc[infitinive, 'engels']
        answer = input(f'Dat is \"{english_word}\" in het Engels. Wat is zijn participium?\n')

    if answer == correct_answer:
        print(':) Dat klopt!\n')
        return 1
    else:
        print(f':( Helaas, is dat niet het juiste antwoord. Het is {correct_answer}\n')
        return 0

n_points = 0
n_questions = 0

while True:
    n_questions += 1
    word_list = generate_word_list(appendix_1[2])
    n_points += ask_a_participium()
    print(f' SCORE: {n_points}/{n_questions} = {round(n_points/n_questions*100)} %')


from django.conf import settings
from django.contrib import admin
from django.urls import path, include
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from fcm_django.api.rest_framework import FCMDeviceAuthorizedViewSet
from rest_framework import permissions

from chat.views import open_chat

urlpatterns = [
    path('admin/', admin.site.urls),
    path('summernote/', include('django_summernote.urls')),
    path('api/users/', include('auth_user.urls')),
    path('api/locations/', include('location.urls')),
    path('api/main-page/', include('main_page.urls')),
    path('api/shop/', include('shop.urls')),
    path('api/promo/', include('promo.urls')),
    path('api/chat/', include('chat.urls')),
    path('api/contacts/', include('contact.urls')),
    path('api/filters/', include('app_filter.urls')),
    path('api/order/', include('order.urls')),
    path('api/external/', include('external.urls')),
    path('api/fcm-devices/', FCMDeviceAuthorizedViewSet.as_view({'post': 'create'}), name='create_fcm_device'),
    path('open-chat/', open_chat, name='open_chat'),
]

if settings.DEBUG:
    # try:
    #     import debug_toolbar
    #     urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]
    # except ImportError:
    #     pass

    schema_view = get_schema_view(
        openapi.Info(
            title="Small API",
            default_version='v2',
            description="",
            terms_of_service="https://www.google.com/policies/terms/",
            contact=openapi.Contact(email="hello@elefanto.kz"),
            license=openapi.License(name="Johny License"),
        ),
        public=True,
        permission_classes=[permissions.AllowAny],
    )

    urlpatterns += [path('api/swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger')]


import pytest
from flaskr.db import get_db

def test_index_view_contains_session_aware_data(client, auth):
	resp = client.get('/')
	assert b'Log In' in resp.data
	assert b'Register' in resp.data

	auth.login()
	resp = client.get('/')
	assert b'New' in resp.data
	assert b'Log Out' in resp.data
	assert b'test\nbody' in resp.data
	assert b'href="/1/update"' in resp.data

@pytest.mark.parametrize('path',(
	'/create',
	'/1/update',
	'/1/delete',
))
def test_login_required_to_see_restricted_routes(client, path):
	resp = client.post(path)
	assert resp.headers['Location'] == 'http://localhost/auth/login'

def test_author_required_for_restricted_actions(app, client, auth):
	with app.app_context():
		db = get_db()
		db.execute('UPDATE post SET author_id = 2 WHERE id = 1')
		db.commit()

	auth.login()
	assert client.post('/1/delete').status_code == 403
	assert client.post('/1/update').status_code == 403
	assert b'/1/update' not in client.get('/').data

@pytest.mark.parametrize('path', (
	'/2/update',
	'/2/delete',
))
def test_server_returns_not_found_when_no_post_exists(client, auth, path):
	auth.login()
	resp = client.post(path)
	assert resp.status_code == 404

def test_create_with_valid_data_succeeds(app, client, auth):
	auth.login()
	assert client.get('/create').status_code == 200

	resp = client.post('/create', data={
		'title': 'created',
		'body': ''
	})
	assert resp.status_code == 302 # redirect after success

	with app.app_context():
		db = get_db()
		count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]
		assert count == 2

def test_update_with_valid_data_succeeds(app, client, auth):
	auth.login()
	assert client.get('/1/update').status_code == 200

	resp = client.post('/1/update', data={
		'title': 'updated',
		'body': ''
	})
	assert resp.status_code == 302 # redirect after success

	with app.app_context():
		db = get_db()
		post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
		assert post['title'] == 'updated'

@pytest.mark.parametrize('path', (
	'/create',
	'/1/update',
))
def test_validation_prevents_invalid_creates_and_updates(client, auth, path):
	auth.login()

	resp = client.post(path, data={
		'title': '',
		'body': ''
	})

	assert  b'Title is required' in resp.data


import os
import sys
import time
from stormx_api_client.environments import SUPPORTED_ENVIRONMENTS
RUN_TESTS_HEADLESS = True
SINGLE_SIGN_ON_ENABLED = False

# NOTE: For running test without headless browser.
if sys.argv[2].lower() == 'false':
    RUN_TESTS_HEADLESS = False
FETCH_INSTANCE = sys.argv[1]  # Environment setup
# For running sso tests.
if 'sso' in sys.argv[3].lower():
    SINGLE_SIGN_ON_ENABLED = True
INVALID_URL_PARAMS = "/ABC/123"
BOOKING_PREVIOUS_DAY_INVENTORY_HOUR = 5
# STORMX_URL = os.getenv("URL", "http://192.168.56.101/")
STORMX_URL = SUPPORTED_ENVIRONMENTS[FETCH_INSTANCE]['php_host']
LOGOUT_URL = STORMX_URL + "/admin/index.php?logout=true"
IDP_URL = os.getenv("URL", "http://192.168.56.103/simplesaml/saml2/idp/SSOService.php?spentityid=stormx-sp")
MAX_EXPLICIT_WAIT = 10
SLEEP_SCALE_FACTOR = 1.0
SLEEP_ADDITIONAL_SECONDS = 0.0

def sleep(number_of_seconds):
    time.sleep(SLEEP_SCALE_FACTOR*number_of_seconds + SLEEP_ADDITIONAL_SECONDS)


import cv2
import numpy as np

def create_safe_zone(image, distance):

    # Return same image if no obstacles
    if not np.any(image): return image.astype(bool), image.astype(bool)

    # Load map as an image
    if image.dtype== bool: image = image.astype(np.uint8)

    #ret, original_img = cv2.threshold(image, 0, 1, cv2.THRESH_BINARY)

    img = image.copy()

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(distance,distance))  # Element for morph transformations

    full = cv2.dilate(img, kernel)

    #full_bool = np.logical_not(full.astype(bool))

    #ret, full = cv2.threshold(full, 0, 1, cv2.THRESH_BINARY_INV)

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))  # Element for morph transformations

    gradient = cv2.dilate(full, kernel)

    full = full.astype(bool)

    gradient = gradient.astype(bool) * np.logical_not(full)

    return full, gradient

if __name__ == '__main__':

    img = np.zeros((800,800), dtype=np.uint8)
    # Set obstacle
    img[200:600, 600:700] = 255
    full, gradient = create_safe_zone(img, 50)
    gradient = (gradient * 255).astype(np.uint8)
    full = (full * 255).astype(np.uint8)
    #vor[200:600, 600:700] = 100
    cv2.imshow("Image", img)
    cv2.imshow("Gradient", gradient)
    cv2.imshow("Dilation", full)
    cv2.waitKey(0)
    #print(vor)


import smbus
import time
bus = smbus.SMBus(1)
config = [0x00, 0x00]
bus.write_i2c_block_data(0x18, 0x01, config)

bus.write_byte_data(0x18, 0x08, 0x03)

time.sleep(.5)

data=bus.read_i2c_block_data(0x18, 0x05, 2)

ctemp = ((data[0] & 0x1F) * 256) +data[1]
print (ctemp)
if ctemp > 4095 :
    ctemp -= 8192
print (ctemp)
ctemp = ctemp / 16
print(ctemp)
ftemp = ctemp * 1.8 + 32
print(ftemp)

print("Temperature in Fahrenheit : ",ftemp)