import pygame

import time

import math

import collections

import random

ifsetup = True

thestat = 0

# setting up pygame stuff

pygame.init()

infoObject = pygame.display.Info()

height = infoObject.current_h

width = infoObject.current_w

print("Screen Resolution: %s, %s" % (infoObject.current_w, infoObject.current_h))

gameDisplay = pygame.display.set_mode((infoObject.current_w, infoObject.current_h), pygame.FULLSCREEN)

clock = pygame.time.Clock()

pygame.display.set_caption('UPlan')  # set window title

vertices = []  # where all the vertices are stored

warningMessages = []  # where all the warningMessages are stored

roads = []  # where all the roads are stored

cars = []  # where all the cars are stored

staticTexts = []

connections = {}

ncars=30

#2 vertice input, outputs array of vertices

def myBFScost(state,end):

    queue = PriorityQueue()

    visited = []

    queue.push((state, [],0),0)

    #print(queue.heap)

    while not queue.isEmpty():

        current = queue.pop()

        if current[0]==end:

            return current[1]

        successors = [(i, i,((i.x-current[0].x)**2+(i.x-current[0].x)**2)**0.5) for i in connections[current[0]]]

        successors.reverse()

        for i in successors:

            if i[0] not in visited:

                tempPush = (i[0], [j for j in current[1]],current[2]+i[2])

                tempPush[1].append(i[1])

                visited.append(i[0])

                queue.push(tempPush,tempPush[2])

    return [state,end]

def text_objects(text, font, color):

    textSurface = font.render(text, True, color)

    return textSurface, textSurface.get_rect()

class PriorityQueue:

    """

      Implements a priority queue data structure. Each inserted item

      has a priority associated with it and the client is usually interested

      in quick retrieval of the lowest-priority item in the queue. This

      data structure allows O(1) access to the lowest-priority item.

    """

    def  __init__(self):

        self.heap = []

    def push(self, item, priority):

        self.heap.append((item, priority))

        self.heap.sort(key=lambda x: x[1])

    def pop(self):

        temp=self.heap[0][0]

        self.heap=self.heap[1:]

        return temp

    def isEmpty(self):

        return len(self.heap) == 0

class Car():

    def __init__(self, v1, v2, path=[], v=0, a=0.075):

        if path==[]:

            self.path=myBFScost(v1,v2)

            self.path.insert(0,v1)

            self.v1 = self.path[0]

            self.v2 = self.path[1]

        else:

            self.path=path

            self.v1 = v1

            self.v2 = v2

        self.pos = (v1.x,v1.y)

        self.endpos = (self.path[1].x,self.path[1].y)

        #self.path=myBFScost(v1,v2)

        self.v = v

        self.a = a

        self.t=0

        self.boost = False

        self.boostval = 0

        for r in roads:

            if (self.pos==(int(r.x),int(r.y)) and self.endpos==(int(r.x1),int(r.y1))) or (self.endpos==(int(r.x),int(r.y)) and self.pos==(int(r.x1),int(r.y1))):

                r.onRoad.append(self)

                self.road = r

                break

        #print(self.road)

        self.order=connections[self.v2].index(self.v1)

        self.maxorder=len(connections[self.v2])

        cars.append(self)

    def __str__(self):

        print(self.pos, self.endpos)

    def isTouching(self, x1, y1):

        tempD = ((x1 - self.pos[0]) ** 2 + (y1 - self.pos[1]) ** 2) ** 0.5  # Find distance between them

        if tempD <= 20:

            return True

        else:

            return False

class WarningMessage():

    def __init__(self, message):

        self.message = message

        self.timer = 100  # initialize timer for warning

        warningMessages.append(self)  # add it to the vertices list

    def __str__(self):

        return "[Warning Message: " + self.message  # Prints this when printing warning obj

class StaticText():

    def __init__(self, message):

        self.message = message

        staticTexts.append(self)  # add it to the vertices list

    def __str__(self):

        return "[Static Text: " + self.message  # Prints this when printing warning obj

class Road():

    def __init__(self, x, y, x1, y1):

        self.x, self.y = x, y

        self.x1, self.y1 = x1, y1

        self.width = int(infoObject.current_w / 373.6) * 4

        self.right=[i for i in range(0,self.length()+1)]

        self.left = [i for i in range(0, self.length() + 1)]

        self.onRoad = []

        roads.append(self)

    def __str__(self):

        return "[Road: %s, %s]" % ((self.x, self.y), (self.x1, self.y1))  # Prints this when printing vertex obj

    def length(self):

        return int(((self.x+self.x1)^2+(self.y+self.y1)^2)**0.5)

    def isTouching(self, x3, y3):

        def isTouching(self, x3, y3):

            x1 = self.x1

            x2 = self.x2

            y1 = self.y1

            y2 = self.y2

            slope1 = (y2 - y1) / (x2 - x1)

            slope2 = (1 / slope1) * -1

            c1 = y1 - (slope1 * x1)

            c2 = y3 - (slope2 * x3)

            x4 = (c2 - c1) / (slope1 - slope2)

            y4 = slope1 * x4 + c1

            distance = ((x4 - x3) ** 2 + (y4 - y3) ** 2) ** 1 / 2

            if distance > self.width:

                return False

            c1 = y1 - slope2 * x1

            c2 = y2 - slope2 * x2

            liney1 = slope2 * x1 + c1

            liney2 = slope2 * x2 + c2

            if (liney1 > y3 and liney2 < y3) or (liney1 < y3 and liney2 > y3):

                return True

            else:

                return False

class Vertex():

    def __init__(self, x, y):

        self.x = x

        self.y = y

        self.radius = int(infoObject.current_w / 373.6)  # keeps a constant pixel radius

        self.timer = 100  # time left before disappear

        self.traffic=0

        self.roads = 0

        vertices.append(self)  # add it to the vertices list

        connections[self] = []

    def __str__(self):

        return "[Vertex: %s, %s]" % (self.x, self.y)  # Prints this when printing vertex obj

    def isTouching(self, x1, y1):

        tempD = ((x1 - v.x) ** 2 + (y1 - v.y) ** 2) ** 0.5  # Find distance between them

        if tempD <= v.radius:

            return True

        else:

            return False

def RenderVertices():

    for v in vertices:

        if v.timer%300==0 and v in connections.keys():

            v.traffic = (v.traffic + 1) % (len(connections[v]) + 1)

        v.timer+=1

        if len(connections[v]) > 0:

            pygame.draw.circle(gameDisplay, (0, 0, 0), (v.x, v.y), v.radius * 2)

        if v == vertexSelected:

            pygame.draw.circle(gameDisplay, (0, 255, 0), (v.x, v.y), v.radius)

        else:

            pygame.draw.circle(gameDisplay, (0, 0, 255), (v.x, v.y), v.radius)

def RenderWarningMessages():

    for w in warningMessages:

        font1 = pygame.font.Font('freesansbold.ttf', 40)  # creates a font

        TextSurf, TextRect = text_objects(w.message, font1, (255, 0, 0))  #

        TextRect.center = ((infoObject.current_w / 2), (infoObject.current_h / 2))  # set the center

        gameDisplay.blit(TextSurf, TextRect)  # put it on the screen

        w.timer -= 1

        # print(w.timer)

        if w.timer == 0:

            warningMessages.remove(w)

def RenderStaticText():

    for w in staticTexts:

        font1 = pygame.font.Font('freesansbold.ttf', 40)  # creates a font

        TextSurf, TextRect = text_objects(w.message, font1, (0, 0, 0))  #

        TextRect.center = ((infoObject.current_w / 2), (infoObject.current_h / 2))  # set the center

        gameDisplay.blit(TextSurf, TextRect)  # put it on the screen

def RenderMisc():

    return

def RenderRoads():

    for r in roads:

        pygame.draw.line(gameDisplay, (0, 0, 0), (r.x, r.y), (r.x1, r.y1), r.width*2)

def RenderCars():

    global thestat

    for c in cars:

        #print(c.pos)

        if (abs(round(c.pos[0], 0)) - c.endpos[0])**2 + (abs(round(c.pos[1], 0)) - c.endpos[1])**2<=100:

      # if ((c.pos[0]-c.endpos[0])**2 + (c.pos[1]-c.endpos[1])**2)**0.5<=30:

            if len(c.path)>=3:

                Car(c.path[1],c.path[2],c.path[1:])

            else:

                makeRandomCar()

            cars.remove(c)

            c.road.onRoad.remove(c)

        dx = c.endpos[0] - c.pos[0]

        dy = c.endpos[1] - c.pos[1]

        angle = abs(math.atan(dy / dx))

        vy = math.sin(angle) *c.v

        vx = math.cos(angle) *c.v

        ay = math.sin(angle) *c.a

        ax = math.cos(angle) * c.a

        if dy <= 0 and dx <= 0:

            vy *= -1

            ay *= -1

            ax *= -1

            vx *= -1

        elif dy <= 0 and dx >= 0:

            ay *= -1

            vy *= -1

        elif dy >= 0 and dx <= 0:

            ax *= -1

            vx *= -1

        elif dy >= 0 and dx >= 0:

            ax *= 1

            vx *= 1

        update=True

        for c1 in c.road.onRoad:

                if c!=c1:

                    if ((c1.pos[0]-c.pos[0])**2+(c1.pos[1]-c.pos[1])**2)**0.5<=30 and c.endpos==c1.endpos and c!=c1:

                        if (vx > 0 and c1.pos[0] > c.pos[0]) or (vx < 0 and c1.pos[0] < c.pos[0]):

                            update=False

                            c.t=0

                            c.v=0

                            break

        if update:

            if ((c.endpos[0] - c.pos[0]) ** 2 + (c.endpos[1] - c.pos[1]) ** 2) ** 0.5 <= 60 and c.maxorder>2 and c.v2.traffic!=c.order:

                update=False

                c.t = 0

                c.v = 0

                #print('nope')

        if update:

            if c.v < 2:

                if c.t < 50:

                    c.t += 1

                else:

                    c.v = ((vy + ay) ** 2 + (vx + ax) ** 2) ** 0.5

            c.pos = (c.pos[0] + vx, c.pos[1] + vy)

        if not update:

            v=0

            c.t=0

            #print('nope')

        if abs(dy)>abs(dx):

            if dy<0:

                pygame.draw.circle(gameDisplay, (255, 0, 0), (int(c.pos[0]+10), int(c.pos[1])), 10)

            else:

                pygame.draw.circle(gameDisplay, (255, 0, 0), (int(c.pos[0]-10), int(c.pos[1])), 10)

        else:

            if dx<0:

                pygame.draw.circle(gameDisplay, (255, 0, 0), (int(c.pos[0]), int(c.pos[1]+10)), 10)

            else:

                pygame.draw.circle(gameDisplay, (255, 0, 0), (int(c.pos[0]), int(c.pos[1]-10)), 10)

        thestat += c.v

        #if c.boost == False:

        #    if vx > 0:

        #       c.pos = (c.pos[0], c.pos[1]+20)

        #    else:

        #       c.pos = (c.pos[0],c.pos[1]-20)

        #    c.boost = True

def makeRandomCar():

    keys = [i for i in connections.keys()]

    if len(keys) > 1:

        v1 = keys[random.randint(0, len(keys) - 1)]

        v2 = keys[random.randint(0, len(keys) - 1)]

        while not [i.isTouching(v2.y, v2.x) for i in cars] == [False for i in cars]:

            v2 = keys[random.randint(0, len(keys) - 1)]

        while True:

            if not [i.isTouching(v1.y, v1.x) for i in cars] == [False for i in cars]:

                v1 = keys[random.randint(0, len(keys) - 1)]

            elif len(connections[v1])>1:

                v1 = keys[random.randint(0, len(keys) - 1)]

            elif v1 == v2:

                v1 = keys[random.randint(0, len(keys) - 1)]

            else:

                break

        return Car(v1, v2)

v1 = Vertex(int(infoObject.current_w / 2), int(infoObject.current_h / 2))  # creates new vertex at (0,0)

# w1 = WarningMessage("ERROR: ewyurhbfm,sdfsd")

#r1 = Road(int(infoObject.current_w/2), int(infoObject.current_h/2),1000,1000)

#c1 = Car((1000,700),(700,1000),0,0.075,r1)

# t1 = StaticText("hewo worwd")

windowExit = False

vertexSelected = None

keys = pygame.key.get_pressed()

#print(connections[v1])

ihadtodoittoem=True

shiftheld = False

statstimer=0

while not windowExit:

    #print(len(cars))

    if ifsetup == True:

        # print(keys)

        for event in pygame.event.get():

            keys = pygame.key.get_pressed()

            if event.type == pygame.KEYDOWN and event.key == pygame.K_1:

                ifsetup = False

            if event.type == pygame.KEYDOWN and event.key == pygame.K_LSHIFT:

                shiftheld = True

            if event.type == pygame.KEYUP and event.key == pygame.K_LSHIFT:

                shiftheld = False

            if event.type == pygame.QUIT:

                windowExit = True

            if event.type == pygame.MOUSEBUTTONDOWN:

                if event.button == 1:  # left click

                    if shiftheld == True:

                        if vertexSelected is not None:

                            for v in vertices:

                                if v.isTouching(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]):

                                    connections[vertexSelected].append(v)

                                    connections[v].append(vertexSelected)

                                    tempR = Road(v.x, v.y, vertexSelected.x, vertexSelected.y)

                                    vertexSelected = None

                                    break

                    else:

                        place = True

                        for v in vertices:

                            if v.isTouching(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]):

                                place = False

                                vertexSelected = v

                                break

                        if place:

                            tempV = Vertex(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])

                            vertexSelected = None

                if event.button == 3:  # right click

                    for v in vertices:

                        if v.isTouching(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]):

                            vertices.remove(v)

                            connections[v] = []

                            connections.pop(v,None)

                            for key in connections.keys():

                                if v in connections[key]:

                                    connections[key].remove(v)

                    for r in roads:

                        if r.isTouching(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]):

                            roads.remove(r)

                            v1=None

                            v2=None

                            for v in vertices:

                                if (r.x1,r.y1)==(v.x,v.y) or (r.x1,r.y1)==(v.x,v.y):

                                    if v1==None:

                                        v1=v

                                    else:

                                        v2=v

                            connections[v1].remove(v2)

                            connections[v2].remove(v1)

    if ifsetup == False:

        statstimer += 1

    if statstimer%10000 == 9999:

        print(thestat/statstimer)

    if ifsetup == False and ihadtodoittoem:

        ihadtodoittoem=False

        while len(cars)<ncars:

            makeRandomCar()

                                    # print(event)

    # print(cars)

    # Layers

    # print(t1,staticTexts)

    gameDisplay.fill((255, 255, 255))  # make background white

    RenderRoads()  # Draw Roads

    RenderVertices()  # Draw Vertices

    RenderCars()  # Draw Cars

    RenderMisc()

    RenderStaticText()

    RenderWarningMessages()  # DrawWarningMessages

    pygame.display.update()


from rest_framework import serializers
from .models import Order, OrderItem
from django.db import transaction

class OrderItemSerializer(serializers.ModelSerializer):
    price = serializers.DecimalField(max_digits=8, decimal_places=2)

    class Meta:
        model = OrderItem
        fields = ("price", "product", "quantity")

class OrderSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True)

    class Meta:
        model = Order
        fields = (
            "first_name",
            "last_name",
            "email",
            "address",
            "zipcode",
            "place",
            "phone",
            "stripe_token",
            "items",
        )

    def get_items(self, instance):
        return OrderItemSerializer(instance=instance.items, many=True).data

    @transaction.atomic
    def create(self, validated_data):
        items = validated_data.pop("items")
        paid_amount = sum(
            [item["quantity"] * item.pop("price") for item in items]
        )
        order = Order.objects.create(
            **validated_data,
            user=self.context["user"],
            paid_amount=paid_amount
        )
        for item in items:
            OrderItem.objects.create(order=order, **item)

        return order


'''
Created on 2020-08-22

@author: wf
'''
import os
import yaml
#from wikibot.mwTable import MediaWikiTable
# redundant copy in this library to avoid dependency issues
# original is at
from lodstorage.mwTable import MediaWikiTable
class Query(object):
    ''' a Query e.g. for SPAQRL '''

    def __init__(self,name,query,lang='sparql',debug=False):
        '''
        constructor
        Args:
            name(string): the name of the query
            query(string): the native Query text e.g. in SPARQL
            lang(string): the language of the query e.g. SPARQL
            debug(boolean): true if debug mode should be switched on
        '''
        self.name=name
        self.lang=lang
        self.query=query
        self.debug=debug

    def asWikiSourceMarkup(self):
        '''
        convert me to Mediawiki markup for syntax highlighting using the "source" tag

        Returns:
            string: the Markup
        '''
        markup="<source lang='%s'>\n%s\n</source>\n" %(self.lang,self.query)
        return markup

    def asWikiMarkup(self,listOfDicts):
        '''
        convert the given listOfDicts result to MediaWiki markup
        Args:
            listOfDicts(list): the list of Dicts to convert to MediaWiki markup
        Returns:
            string: the markup
        '''
        if self.debug:
            print(listOfDicts)
        mwTable=MediaWikiTable()
        mwTable.fromListOfDicts(listOfDicts)
        markup=mwTable.asWikiMarkup()
        return markup

class QueryManager(object):
    '''
    manages prepackaged Queries
    '''

    def __init__(self,lang='sql',debug=False,path=None):
        '''
        Constructor
        Args:
            lang(string): the language to use for the queries sql or sparql
            debug(boolean): True if debug information should be shown
        '''
        self.queriesByName={}
        self.lang=lang
        self.debug=debug
        queries=QueryManager.getQueries(path=path)
        for name,queryDict in queries.items():
            if self.lang in queryDict:
                queryText=queryDict[self.lang]
                query=Query(name,queryText,lang=self.lang,debug=self.debug)
                self.queriesByName[name]=query

    @staticmethod
    def getQueries(path=None):
        if path is None:
            path=os.path.dirname(__file__)+"/.."
        queriesPath=path+"/queries.yaml"
        with open(queriesPath, 'r') as stream:
            examples = yaml.safe_load(stream)
        return examples


import tornado.web
from . import device_manager
from .global_namespace import *

class BaseHandler(tornado.web.RequestHandler):
    def end_with_json(self, code, data=None, message=None):
        request_url = self.request.uri
        result_dict = {
            'code': code,
            'data': data or {},
            'message': message or {},
        }
        logger.info(TAG_REQUEST_END, code=code, data=data, message=message, request_url=request_url)
        self.finish(result_dict)

class MainHandler(BaseHandler):
    def get(self):
        self.end_with_json(FLAG_HTTP_OK)

class DeviceHandler(BaseHandler):
    def get(self):
        # get usable devices
        device_dict = device_manager.get_available_device(auth=True, to_string=True)
        self.end_with_json(FLAG_HTTP_OK, data=device_dict)

    def post(self):
        # confirm device connection
        target_device_id = self.get_argument('deviceID', '')
        target_device_ip = self.get_argument('deviceIP', '')
        device_manager.auth_device(target_device_id, target_device_ip)
        self.end_with_json(FLAG_HTTP_OK)

__all__ = [
    'MainHandler',
    'DeviceHandler',
]


def the3N1P(n):
    count = 1
    while n != 1:
        if n % 2 == 0: # even
            n = n / 2
        else: # odd
            n = 3*n + 1
        count += 1
    return count

def max3N1P(n):
    max_number = 0 # the number that produces the longest sequence
    max_length = 0 # the length of the longest sequence
    for i in range(1, n):
        length = the3N1P(i)
        if length > max_length:
            max_length = length
            max_number = i
    return (max_number, max_length)


import asyncio
import aiocoap

import logging
import time
import os
import re
import hashlib
import aiocoap.resource as resource
logging.basicConfig(level=logging.DEBUG,format='%(levelname)s %(message)s')
logger = logging.getLogger('lwm2mserver')

class Hasher(object):
    def __init__(self, seed):
        self.seed = seed

    def hash_for(self, string):
        assert string is not None
        h = hashlib.new("sha1")
        h.update(string.encode())
        h.update(self.seed)
        return h.hexdigest()

class Registry_device():
    def getByName(self,registrys,devicename):
        for k in registrys:
            if registrys[k]["endpoint"]==devicename:
                return registrys[k]

    def unregister(self,registrys,id):
        if registrys.get(id):
            del registrys[id]
        else:
            logger.error("not found the id ")
    def register(self,registrys,idnum,device):
        registrys[idCounter]=device
        registrys[idCounter]['id']=idCounter

    def clean(self,registrys):
        registrys={}

    def getObject(self,registrys,id):
        if registrys.get(id):
            return registrys[id]
        else:
            return None

    def update(self,registrys,id,obj):
        if registrys.get(id):
            registrys[id]=obj
        else:
            logger.error("not found the id")
    def list(self,registrys):
        print(registrys)
    def stopLifetimeCheck(self):
        pass
    def checkLifetime(self):
        pass

class WithAsyncloop():
    def __init__(self):
        self.loop=asyncio.get_event_loop()

class WithClient(WithAsyncloop):
    def __init__(self):
        super(WithClient,self).__init__()
        self.client=self.loop.run_until_complete(aiocoap.Context.create_client_context())

    def close(self):
        self.loop.run_until_complete(self.client.shutdown())

    def fetch_response(self,request,exchange_monitor_factory=lambda x:None):
        return self.loop.run_until_complete(self.client.request(request, exchange_monitor_factory=exchange_monitor_factory).response)

class DeviceManagement(WithClient,Registry_device):
    def __init__(self):
        super(DeviceManagement,self).__init__()
    def read(self,registrys,deviceId, objectType, objectId, resourceId):
        obj=self.getByName(registrys,deviceId)
        print(obj)
        request=aiocoap.Message(code=aiocoap.GET)
        request.remote=obj["address"]
        request.opt.uri_host=obj["host"]
        request.opt.uri_port=obj["port"]
        request.opt.uri_path=(objectType, objectId, resourceId)
        return request
    def write(self,registrys,deviceId, objectType, objectId, resourceId, value):
        obj=self.getByName(registrys,deviceId)
        request=aiocoap.Message(code=aiocoap.PUT)
        request.payload=value
        request.remote=obj["address"]
        request.opt.uri_host=obj["host"]
        request.opt.uri_port=obj["port"]
        request.opt.uri_path=(objectType, objectId, resourceId)
        return request

    def execute(self,registrys,deviceId, objectType, objectId, resourceId, value):
        obj=self.getByName(registrys,deviceId)
        request=aiocoap.Message(code=aiocoap.POST)
        request.payload=value
        request.remote=obj["address"]
        request.opt.uri_host=obj["host"]
        request.opt.uri_port=obj["port"]
        request.opt.uri_path=(objectType, objectId, resourceId)
        return request
    def writeAttributes(deviceId, objectType, objectId, resourceId, attributes):
            pass
    def discover(self,registrys,deviceId, objectType, objectId, resourceId):
        obj=self.getByName(registrys,deviceId)
        logger.debug('Executing a resource discover operation on resource')

        request=aiocoap.Message(code=aiocoap.GET)
        request.remote=obj["address"]
        request.opt.uri_host=obj["host"]
        request.opt.uri_port=obj["port"]
        print(obj["objects"])
        request.opt.accept=aiocoap.numbers.media_types_rev['application/link-format']
        if obj["objects"].get(objectType):
            if obj["objects"][objectType].get(objectId):
                if obj["objects"][objectType][objectId]==resourceId:
                    request.opt.uri_path=(objectType,objectId,resourceId)
                else:
                    request.opt.uri_path=(objectType,objectId)
            else:
                request.opt.uri_path=(objectType,)
        return request
    def create(self,registrys,deviceId, objectType, objectId):
        obj=self.getByName(registrys,deviceId)
        logger.debug('Creating a new instance of object type [%s] in the device [%d] with instance id [%s]',objectType, deviceId, objectId)
        request=aiocoap.Message(code=aiocoap.POST)
        request.remote=obj["address"]
        request.opt.uri_host=obj["host"]
        request.opt.uri_port=obj["port"]
        request.opt.uri_path=(deviceId, objectType)
        return request
    def remove(self,deviceId, objectType, objectId):
        pass
    def observe_parseId():
        pass
    def observe(self,registrys,deviceId, objectType, objectId,resourceId):
        obj=self.getByName(registrys,deviceId)
        serveraddress = "::1"
        servernetloc = "[%s]"%serveraddress
        logger.debug('Observing value from resource /%s/%s/%s in device [%d]',objectType, objectId, resourceId, deviceId)
        request = aiocoap.Message(code=aiocoap.GET)
        request.unresolved_remote = servernetloc
        request.remote=obj["address"]
        request.opt.uri_host=obj["host"]
        request.opt.uri_port=obj["port"]
        request.opt.uri_path = (objectType,objectId,resourceId)
        request.opt.observe = 1
        return request

    def list_observe(self):
    	print(subscriptions)
    def clean_observe(self):
    	subscriptions={}
    def cancel_observe(self,deviceId, objectType, objectId, resourceId):
    	pass

class Server(DeviceManagement,resource.ObservableResource):
    host='localhost'
    port=5683
    lifetime=86400
    version='1.0.0'
    log_level="DEBUG"
    ENDPOINT = "ep"
    LIFETIME = "lt"
    BINDING_MODE = "b"
    SMS = "sms"
    LWM2M_VERSION = "lwm2m"
    DEFAULT_VERSION = "1.0"
    DEFAULT_LIFETIME = 86400
    CLEANER_PERIOD_SECONDS = 10
    site=aiocoap.resource.Site()
    registry={}
    idCounter=1
    subscriptions = {}

    def __init__(self):
        super(Server,self).__init__()
        logger.debug("creating server instance")
        self.hasher = Hasher(os.urandom(30))
        self.site = resource.Site()
        self.site.add_resource((self.get_path(),), self)
        self.handle=None

    def notify(self):
        self.updated_state()
        self.reschedule()

    def reschedule(self):
        self.handle = asyncio.get_event_loop().call_later(5, self.notify)

    def update_observation_count(self, count):
        if count and self.handle is None:
            print("Starting the clock")
            self.handle = self.reschedule()
        if count == 0 and self.handle:
            print("Stopping the clock")
            self.handle.cancel()
            self.handle = None

    async def render_get(self, request):
        payload = datetime.datetime.now().\
                strftime("%Y-%m-%d %H:%M").encode('ascii')
        return aiocoap.Message(payload=payload)

    @staticmethod
    def get_path():
        return "rd"

    def get_device_location(self,location):
        for k in self.registry:
            if self.registry[k]['location']==location:
                return self.registry[k]
    async def render_post(self, request):
        print(request.opt.uri_host)
        print(request.opt.uri_port)
        address=request.remote
        opts = dict(x.split("=") for x in request.opt.uri_query)
        logger.debug("POST called with options %s" % opts)

        if self.ENDPOINT not in opts:
            return self.bad_request(b"endpoint name is required")

        client = dict()
        client["address"]=address
        client["host"]=self.host
        client["port"]=self.port
        client["endpoint"] = opts[self.ENDPOINT]
        client["lifetime"] = self._get_lifetime(opts, self.DEFAULT_LIFETIME)

        client["lwm2m_version"] = opts[self.LWM2M_VERSION] if self.LWM2M_VERSION in opts else self.DEFAULT_VERSION
        client["sms"] = opts[self.SMS] if self.SMS in opts else None
        client["binding_mode"] = self.get_binding_mode(
            opts[self.BINDING_MODE]) if self.BINDING_MODE in opts else "U"
        payload = request.payload.decode()
        if payload == "":
            return self.bad_request(b"payload must contain object links")

        client["objects"] = self.get_object_links(request.payload.decode())
        client["time"] = asyncio.get_event_loop().time()
        location=self.hasher.hash_for(opts[Server.ENDPOINT])

        client['location']=location
        self.registry[self.idCounter]=client
        registrys=self.registry

        self.idCounter +=1

        self.site.add_resource((self.get_path(), location), self)
        response = aiocoap.Message(code=aiocoap.CREATED)
        return response

    def _get_lifetime(self, opts, default_lifetime):
        if self.LIFETIME in opts:
            try:
                lifetime = int(opts[Server.LIFETIME])
            except ValueError:
                return Server.bad_request(b"non-numeric lifetime value")

            if lifetime <= 0:
                return Server.bad_request(b"lifetime value out of range")
            else:
                return lifetime
        else:
            return default_lifetime

    def _remove_client(self, location):
        self.site.remove_resource((self.get_path(), location))

    @staticmethod
    def get_binding_mode(bmode):
        modes = ["U", "UQ", "S", "SQ", "US", "UQS"]
        return bmode if bmode in modes else "U"

    @staticmethod
    def get_object_links(payload):
        objs = dict()
        for link in payload.split(","):
            m = re.match("^<(/(\d+))(/(\d+))*>.*$", link)
            if m.group(4) is not None:
                obj_id = str(m.group(2))
                instance_id = str(m.group(4))
                if obj_id in objs:
                    objs[obj_id][instance_id] = instance_id
                else:
                    objs[obj_id] = {instance_id: instance_id}
            else:
                obj_id = str(m.group(2))
                if obj_id in objs:
                    objs[obj_id]["0"] = "0"
                else:
                    objs[obj_id] = {"0": "0"}

        return objs

    @staticmethod
    def bad_request(payload=None):
        response = aiocoap.Message(code=aiocoap.BAD_REQUEST)
        if payload is not None:
            response.payload = payload
        return response

    @asyncio.coroutine
    def render_put(self, request):
        location = request.opt.uri_path[-1]
        logger.debug("PUT called for location %s" % location)
        opts = dict(x.split("=") for x in request.opt.uri_query)
        client = self.get_device_location(location)# self.client_persistence.get_client_for_location(location)
        client["time"] = asyncio.get_event_loop().time()
        client["lifetime"] = self._get_lifetime(opts, client["lifetime"])
        client["binding_mode"] = self.get_binding_mode(
            opts[self.BINDING_MODE]) if self.BINDING_MODE in opts else client["binding_mode"]
        client["sms"] = opts[self.SMS] if self.SMS in opts else client["sms"]
        payload = request.payload.decode()
        if payload != "":
            client["objects"] = self.get_object_links(payload)
        registrys=self.registry

        response = aiocoap.Message(code=aiocoap.CHANGED)
        return response

    @asyncio.coroutine
    def render_delete(self, request):
        location = request.opt.uri_path[-1]
        logger.debug("DELETE called for location %s" % location)
        self._remove_client(location)
        response = aiocoap.Message(code=aiocoap.DELETED)
        return response

    def notify(self):
        self.updated_state()
        self.reschedule()

    def cleaner(self):
        logger.debug("running periodic cleaner")
        to_delete = list()
        for k in self.registry:
            time = asyncio.get_event_loop().time()
            if time - self.registry[k]["time"] > self.registry[k]["lifetime"]:
                to_delete.append(self.registry[k]["location"])
        for location in to_delete:
            logger.debug("removing dead client (location %s)" % location)
            self._remove_client(location)
        # reschedule the cleaner
        asyncio.get_event_loop().call_later(self.CLEANER_PERIOD_SECONDS, self.cleaner)
    async def start(self):
        self.protocol= await aiocoap.Context.create_server_context(self.site,bind=(self.host, self.port))
        self.protocol1=await aiocoap.Context.create_client_context()
        # asyncio.ensure_future(self.protocol)
        # self.server = self.loop.run_until_complete(self.protocol)
    def stop(self):
        self.loop.run_until_complete(asyncio.sleep(CLEANUPTIME))
        self.loop.run_until_complete(self.server.shutdown())


#!/usr/bin/env python

import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

def callback(dt):
    print ('-------------------------------------------')
    print ('Range data at 0 deg:   {}'.format(dt.ranges[0]))
    print ('Range data at 15 deg:  {}'.format(dt.ranges[15]))
    print ('Range data at 345 deg: {}'.format(dt.ranges[345]))
    print ('-------------------------------------------')

    thr1 = 0.8
    thr2 = 0.8

    if dt.ranges[0]>thr1 and dt.ranges[15]>thr2 and dt.ranges[345]>thr2:
        move.linear.x = 0.5
        move.angular.z = 0.0
    else:
        move.linear.x = 0.0
        move.angular.z = 0.5
        if dt.ranges[0]>thr1 and dt.ranges[15]>thr2 and dt.ranges[345]>thr2:
            move.linear.x = 0.5
            move.angular.z = 0.0
    pub.publish(move)

if __name__ == '__main__':
    move = Twist()
    rospy.init_node('obstacle_avoidance_node')
    pub = rospy.Publisher("/cmd_vel", Twist, queue_size=10)
    sub = rospy.Subscriber("/scan", LaserScan, callback)
    rospy.spin()


import os
import sys
import json
from zipfile import ZipFile
import argparse
import boto3
import spacy
import pprint
sys.path.append(os.path.join(os.path.dirname(__file__), "../../"))
from yans.storage import Storage
from yans.data.train import Evaluator, make_data

def main(model_path, data_path,
         num_limit, local):

    bucket = "yans.2019.js"
    storage = Storage()

    # Load model
    s3 = boto3.resource("s3")
    print(f"Load model from {model_path}")
    if not local:
        _model_path = storage.path(f"model/{os.path.basename(model_path)}")
        if not os.path.exists(_model_path):
            s3.Bucket(bucket).download_file(model_path, _model_path)
    else:
        _model_path = storage.path(model_path)

    expand_path, _ = os.path.splitext(_model_path)
    if not os.path.exists(expand_path):
        with ZipFile(_model_path) as f:
            f.extractall(storage.path("model"))

    nlp = spacy.load(expand_path)

    # Load Data
    print(f"Get data from {data_path}")
    _data_path = data_path
    if not local:
        _data_path = storage.path(f"raw/{os.path.basename(data_path)}")
        if not os.path.exists(_data_path):
            s3.Bucket(bucket).download_file(data_path, _data_path)

    # Evaluate
    print("Evaluator model")
    data = make_data(_data_path)
    if num_limit > 0:
        data = data[:num_limit]
    evaluator = Evaluator(data)
    score = evaluator.evaluate(nlp)
    pprint.pprint(score)

    file_name = f"{os.path.basename(model_path)}_{os.path.basename(data_path)}.json"
    with open(file_name, mode="w", encoding="utf-8") as f:
        json.dump(score, f, indent=4)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--model_path", type=str)
    parser.add_argument("--data_path", type=str)
    parser.add_argument("--num_limit", type=int, default=-1)
    parser.add_argument("--local", action="store_true")
    args = parser.parse_args()

    main(args.model_path,
         args.data_path,
         args.num_limit,
         args.local)


# logicPlan.py
# ------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

"""
In logicPlan.py, you will implement logic planning methods which are called by
Pacman agents (in logicAgents.py).
"""

import util
import sys
import logic
import game

from logic import conjoin, disjoin
from logic import PropSymbolExpr, Expr, to_cnf, pycoSAT, parseExpr

import itertools
import copy

pacman_str = 'P'
food_str = 'FOOD'
wall_str = 'WALL'
pacman_wall_str = pacman_str + wall_str
ghost_pos_str = 'G'
ghost_east_str = 'GE'
pacman_alive_str = 'PA'
DIRECTIONS = ['North', 'South', 'East', 'West']
blocked_str_map = dict([(direction, (direction + "_blocked").upper()) for direction in DIRECTIONS])
geq_num_adj_wall_str_map = dict([(num, "GEQ_{}_adj_walls".format(num)) for num in range(1, 4)])
DIR_TO_DXDY_MAP = {'North':(0, 1), 'South':(0, -1), 'East':(1, 0), 'West':(-1, 0)}

class PlanningProblem:
    """
    This class outlines the structure of a planning problem, but doesn't implement
    any of the methods (in object-oriented terminology: an abstract class).

    You do not need to change anything in this class, ever.
    """

    def getStartState(self):
        """
        Returns the start state for the planning problem.
        """
        util.raiseNotDefined()

    def getGhostStartStates(self):
        """
        Returns a list containing the start state for each ghost.
        Only used in problems that use ghosts (FoodGhostPlanningProblem)
        """
        util.raiseNotDefined()

    def getGoalState(self):
        """
        Returns goal state for problem. Note only defined for problems that have
        a unique goal state such as PositionPlanningProblem
        """
        util.raiseNotDefined()

def tinyMazePlan(problem):
    """
    Returns a sequence of moves that solves tinyMaze.  For any other maze, the
    sequence of moves will be incorrect, so only use this for tinyMaze.
    """
    from game import Directions
    s = Directions.SOUTH
    w = Directions.WEST
    return  [s, s, w, s, w, w, s, w]

# **************
#  Question 1
# **************
def sentence1():
    """Returns a Expr instance that encodes that the following expressions are all true.

    A or B
    (not A) if and only if ((not B) or C)
    (not A) or (not B) or C
    """
    "*** BEGIN YOUR CODE HERE ***"
    A = logic.Expr("A")
    B = logic.Expr("B")
    C = logic.Expr("C")
    L = [logic.disjoin(A, B), ~A % (~B | C), logic.disjoin(~A, ~B, C)]
    return logic.conjoin(L[0], L[1], L[2])
    "*** END YOUR CODE HERE ***"

# **************
#  Question 1
# **************
def sentence2():
    """Returns a Expr instance that encodes that the following expressions are all true.

    C if and only if (B or D)
    A implies ((not B) and (not D))
    (not (B and (not C))) implies A
    (not D) implies C
    """
    "*** BEGIN YOUR CODE HERE ***"
    A = logic.Expr("A")
    B = logic.Expr("B")
    C = logic.Expr("C")
    D = logic.Expr("D")
    L = [C % (B | D), A >> (~B & ~D), ~(B & ~C) >> A, ~D >> C]
    return logic.conjoin(L[0], L[1], L[2], L[3])
    "*** END YOUR CODE HERE ***"

# **************
#  Question 1
# **************
def sentence3():
    """Using the symbols PacmanAlive[1], PacmanAlive[0], PacmanBorn[0], and PacmanKilled[0],
    created using the PropSymbolExpr constructor, return a PropSymbolExpr
    instance that encodes the following English sentences (in this order):

    Pacman is alive at time 1 if and only if Pacman was alive at time 0 and it was
    not killed at time 0 or it was not alive at time 0 and it was born at time 0.

    Pacman cannot both be alive at time 0 and be born at time 0.

    Pacman is born at time 0.
    """
    "*** BEGIN YOUR CODE HERE ***"
    A = logic.PropSymbolExpr("PacmanAlive[0]")
    B = logic.PropSymbolExpr("PacmanAlive[1]")
    C = logic.PropSymbolExpr("PacmanBorn[0]")
    D = logic.PropSymbolExpr("PacmanKilled[0]")
    one = B % ((A & ~D) | (~A & C))
    two = ~(A & C)
    three = C
    return logic.conjoin(one, two, three)
    "*** END YOUR CODE HERE ***"

# **************
#  Question 1
# **************
def findModel(sentence):
    """Given a propositional logic sentence (i.e. a Expr instance), returns a satisfying
    model if one exists. Otherwise, returns False.
    """
    "*** BEGIN YOUR CODE HERE ***"
    sentence_cnf = logic.to_cnf(sentence)
    sat_model = logic.pycoSAT(sentence_cnf)
    return sat_model
    "*** END YOUR CODE HERE ***"

def modelToString(model):
    """Converts the model to a string for printing purposes. The keys of a model are
    sorted before converting the model to a string.

    model: Either a boolean False or a dictionary of Expr symbols (keys)
    and a corresponding assignment of True or False (values). This model is the output of
    a call to pycoSAT.
    """
    if model == False:
        return "False"
    else:
        # Dictionary
        modelList = sorted(model.items(), key=lambda item: str(item[0]))
        return str(modelList)

# **************
#  Question 2
# **************
def atLeastOne(literals):
    """
    Given a list of Expr literals (i.e. in the form A or ~A), return a single
    Expr instance in CNF (conjunctive normal form) that represents the logic
    that at least one of the literals in the list is true.
    >>> A = PropSymbolExpr('A');
    >>> B = PropSymbolExpr('B');
    >>> symbols = [A, B]
    >>> atleast1 = atLeastOne(symbols)
    >>> model1 = {A:False, B:False}
    >>> print(pl_true(atleast1,model1))
    False
    >>> model2 = {A:False, B:True}
    >>> print(pl_true(atleast1,model2))
    True
    >>> model3 = {A:True, B:True}
    >>> print(pl_true(atleast1,model2))
    True
    """
    "*** BEGIN YOUR CODE HERE ***"
    return logic.disjoin(literals)
    "*** END YOUR CODE HERE ***"

# **************
#  Question 2
# **************
def atMostOne(literals):
    """
    Given a list of Expr literals, return a single Expr instance in
    CNF (conjunctive normal form) that represents the logic that at most one of
    the expressions in the list is true.
    """
    "*** BEGIN YOUR CODE HERE ***"
    literals_negations = [~literal for literal in literals]
    pairs_disj = [disjoin(list(pair)) for pair in itertools.combinations(literals_negations, 2)]
    return conjoin(pairs_disj)
    "*** END YOUR CODE HERE ***"

# **************
#  Question 2
# **************
def exactlyOne(literals):
    """
    Given a list of Expr literals, return a single Expr instance in
    CNF (conjunctive normal form)that represents the logic that exactly one of
    the expressions in the list is true.
    """
    "*** BEGIN YOUR CODE HERE ***"
    return conjoin(atLeastOne(literals), atMostOne(literals))
    "*** END YOUR CODE HERE ***"

def extractActionSequence(model, actions):
    """
    Convert a model in to an ordered list of actions.
    model: Propositional logic model stored as a dictionary with keys being
    the symbol strings and values being Boolean: True or False
    Example:
    >>> model = {"North[2]":True, "P[3,4,0]":True, "P[3,3,0]":False, "West[0]":True, "GhostScary":True, "West[2]":False, "South[1]":True, "East[0]":False}
    >>> actions = ['North', 'South', 'East', 'West']
    >>> plan = extractActionSequence(model, actions)
    >>> print(plan)
    ['West', 'South', 'North']
    """
    plan = [None for _ in range(len(model))]
    for sym, val in model.items():
        parsed = parseExpr(sym)
        if type(parsed) == tuple and parsed[0] in actions and val:
            action, time = parsed
            plan[int(time)] = action
    #return list(filter(lambda x: x is not None, plan))
    return [x for x in plan if x is not None]

def pacmanSuccessorStateAxioms(x, y, t, walls_grid, var_str=pacman_str):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    Available actions are ['North', 'East', 'South', 'West']
    Note that STOP is not an available action.
    """
    possibilities = []
    if not walls_grid[x][y+1]:
        possibilities.append( PropSymbolExpr(var_str, x, y+1, t-1)
                            & PropSymbolExpr('South', t-1))
    if not walls_grid[x][y-1]:
        possibilities.append( PropSymbolExpr(var_str, x, y-1, t-1)
                            & PropSymbolExpr('North', t-1))
    if not walls_grid[x+1][y]:
        possibilities.append( PropSymbolExpr(var_str, x+1, y, t-1)
                            & PropSymbolExpr('West', t-1))
    if not walls_grid[x-1][y]:
        possibilities.append( PropSymbolExpr(var_str, x-1, y, t-1)
                            & PropSymbolExpr('East', t-1))

    if not possibilities:
        return None

    return PropSymbolExpr(var_str, x, y, t) % disjoin(possibilities)

def pacmanSLAMSuccessorStateAxioms(x, y, t, walls_grid, var_str=pacman_str):
    """
    Similar to `pacmanSuccessorStateAxioms` but accounts for illegal actions
    where the pacman might not move timestep to timestep.
    Available actions are ['North', 'East', 'South', 'West']
    """
    moved_tm1_possibilities = []
    if not walls_grid[x][y+1]:
        moved_tm1_possibilities.append( PropSymbolExpr(var_str, x, y+1, t-1)
                            & PropSymbolExpr('South', t-1))
    if not walls_grid[x][y-1]:
        moved_tm1_possibilities.append( PropSymbolExpr(var_str, x, y-1, t-1)
                            & PropSymbolExpr('North', t-1))
    if not walls_grid[x+1][y]:
        moved_tm1_possibilities.append( PropSymbolExpr(var_str, x+1, y, t-1)
                            & PropSymbolExpr('West', t-1))
    if not walls_grid[x-1][y]:
        moved_tm1_possibilities.append( PropSymbolExpr(var_str, x-1, y, t-1)
                            & PropSymbolExpr('East', t-1))

    if not moved_tm1_possibilities:
        return None

    moved_tm1_sent = conjoin([~PropSymbolExpr(var_str, x, y, t-1) , ~PropSymbolExpr(wall_str, x, y), disjoin(moved_tm1_possibilities)])

    unmoved_tm1_possibilities_aux_exprs = [] # merged variables
    aux_expr_defs = []
    for direction in DIRECTIONS:
        dx, dy = DIR_TO_DXDY_MAP[direction]
        wall_dir_clause = PropSymbolExpr(wall_str, x + dx, y + dy) & PropSymbolExpr(direction, t - 1)
        wall_dir_combined_literal = PropSymbolExpr(wall_str + direction, x + dx, y + dy, t - 1)
        unmoved_tm1_possibilities_aux_exprs.append(wall_dir_combined_literal)
        aux_expr_defs.append(wall_dir_combined_literal % wall_dir_clause)

    unmoved_tm1_sent = conjoin([
        PropSymbolExpr(var_str, x, y, t-1),
        disjoin(unmoved_tm1_possibilities_aux_exprs)])

    return conjoin([PropSymbolExpr(var_str, x, y, t) % disjoin([moved_tm1_sent, unmoved_tm1_sent])] + aux_expr_defs)

# **************
#  Question 3
# **************
def pacphysics_axioms(t, all_coords, non_outer_wall_coords):
    """
    Given:
        t: timestep
        all_coords: list of (x, y) coordinates of the entire problem
        non_outer_wall_coords: list of (x, y) coordinates of the entire problem,
            excluding the outer border (these are the actual squares pacman can
            possibly be in)
    Return a logic sentence containing all of the following:
        - for all (x, y) in all_coords:
            If a wall is at (x, y) --> Pacman is not at (x, y)
        - Pacman is at exactly one of the squares at timestep t.
        - Pacman takes exactly one action at timestep t.
    """
    pacphysics_sentences = []

    "*** BEGIN YOUR CODE HERE ***"
    pac_pos_list = []
    pac_act_list = []
    for x, y in all_coords:
        A = PropSymbolExpr(pacman_str, x, y, t) # whether or not Pacman is at (x, y) at time t
        B = PropSymbolExpr(wall_str, x, y) # whether or not a wall is at (x, y)
        pacphysics_sentences.append(B >> ~A)
    for x, y in non_outer_wall_coords:
        A = PropSymbolExpr(pacman_str, x, y, t) # whether or not Pacman is at (x, y) at time t
        pac_pos_list.append(A)
    pacphysics_sentences.append(exactlyOne(pac_pos_list))
    for action in DIRECTIONS:
        C = PropSymbolExpr(action, t) # whether or not pacman takes action action at time t, where action is an element of DIRECTIONS
        pac_act_list.append(C)
    pacphysics_sentences.append(exactlyOne(pac_act_list))
    "*** END YOUR CODE HERE ***"

    return conjoin(pacphysics_sentences)

# **************
#  Question 3
# **************
def check_location_satisfiability(x1_y1, x0_y0, action0, action1, problem):
    """
    Given:
        - x1_y1 = (x1, y1), a potential location at time t = 1
        - x0_y0 = (x0, y0), Pacman's location at time t = 0
        - action0 = one of the four items in DIRECTIONS, Pacman's action at time t = 0
        - problem = An instance of logicAgents.LocMapProblem
    Return:
        - a model proving whether Pacman is at (x1, y1) at time t = 1
        - a model proving whether Pacman is not at (x1, y1) at time t = 1
    """
    walls_grid = problem.walls
    walls_list = walls_grid.asList()
    all_coords = list(itertools.product(range(problem.getWidth()+2), range(problem.getHeight()+2)))
    non_outer_wall_coords = list(itertools.product(range(1, problem.getWidth()+1), range(1, problem.getHeight()+1)))
    KB = []
    x0, y0 = x0_y0
    x1, y1 = x1_y1

    # We know which coords are walls:
    map_sent = [PropSymbolExpr(wall_str, x, y) for x, y in walls_list]
    KB.append(conjoin(map_sent))

    "*** BEGIN YOUR CODE HERE ***"
    t = 0
    KB.append(PropSymbolExpr(pacman_str, x0, y0, t))
    KB.append(pacphysics_axioms(t, all_coords, non_outer_wall_coords))
    KB.append(PropSymbolExpr(action0, t))
    KB.append(allLegalSuccessorAxioms(t+1, walls_grid, non_outer_wall_coords))
    t = 1
    KB.append(pacphysics_axioms(t, all_coords, non_outer_wall_coords))
    KB.append(PropSymbolExpr(action1, t))
    A = PropSymbolExpr(pacman_str, x1, y1, t)  # whether or not Pacman is at (x, y) at time t
    model1 = KB.copy()
    model2 = KB.copy()
    model1.append(~A)
    model2.append(A)
    return (findModel(conjoin(model1)), findModel(conjoin(model2)))
    "*** END YOUR CODE HERE ***"

# **************
#  Question 4
# **************
def positionLogicPlan(problem):
    """
    Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal.
    Available actions are ['North', 'East', 'South', 'West']
    Note that STOP is not an available action.
    """
    walls = problem.walls
    width, height = problem.getWidth(), problem.getHeight()
    walls_list = walls.asList()
    x0, y0 = problem.startState
    xg, yg = problem.goal

    # Get lists of possible locations (i.e. without walls) and possible actions
    all_coords = list(itertools.product(range(width + 2),
            range(height + 2)))

    non_wall_coords = [loc for loc in all_coords if loc not in walls_list]
    actions = [ 'North', 'South', 'East', 'West' ]
    KB = []

    "*** BEGIN YOUR CODE HERE ***"
    t = 0
    KB.append(PropSymbolExpr(pacman_str, x0, y0, t))
    for t in range(51):
        pac_pos_list = []
        for x, y in non_wall_coords:
            A = PropSymbolExpr(pacman_str, x, y, t)  # whether or not Pacman is at (x, y) at time t
            pac_pos_list.append(A)
        KB.append(exactlyOne(pac_pos_list))
        if findModel(conjoin(KB + [PropSymbolExpr(pacman_str, xg, yg, t)])):
            return extractActionSequence(findModel(conjoin(KB + [PropSymbolExpr(pacman_str, xg, yg, t)])), actions)
        pac_act_list = []
        for action in actions:
            C = PropSymbolExpr(action, t)  # whether or not pacman takes action action at time t, where action is an element of DIRECTIONS
            pac_act_list.append(C)
        KB.append(exactlyOne(pac_act_list))
        for x, y in non_wall_coords:
            KB.append(pacmanSuccessorStateAxioms(x, y, t+1, walls, var_str=pacman_str))
    "*** END YOUR CODE HERE ***"

# Helpful Debug Method
def visualize_coords(coords_list, problem):
    wallGrid = game.Grid(problem.walls.width, problem.walls.height, initialValue=False)
    for (x, y) in itertools.product(range(problem.getWidth()+2), range(problem.getHeight()+2)):
        if (x, y) in coords_list:
            wallGrid.data[x][y] = True
    print(wallGrid)

# Helpful Debug Method
def visualize_bool_array(bool_arr, problem):
    wallGrid = game.Grid(problem.walls.width, problem.walls.height, initialValue=False)
    wallGrid.data = copy.deepcopy(bool_arr)
    print(wallGrid)

def sensorAxioms(t, non_outer_wall_coords):
    all_percept_exprs = []
    combo_var_def_exprs = []
    for direction in DIRECTIONS:
        percept_exprs = []
        dx, dy = DIR_TO_DXDY_MAP[direction]
        for x, y in non_outer_wall_coords:
            combo_var = PropSymbolExpr(pacman_wall_str, x, y, t, x + dx, y + dy)
            percept_exprs.append(combo_var)
            combo_var_def_exprs.append(combo_var % (
                PropSymbolExpr(pacman_str, x, y, t) & PropSymbolExpr(wall_str, x + dx, y + dy)))

        percept_unit_clause = PropSymbolExpr(blocked_str_map[direction], t)
        all_percept_exprs.append(percept_unit_clause % disjoin(percept_exprs))

    return conjoin(all_percept_exprs + combo_var_def_exprs)

def four_bit_percept_rules(t, percepts):
    """
    Localization and Mapping both use the 4 bit sensor, which tells us True/False whether
    a wall is to pacman's north, south, east, and west.
    """
    assert isinstance(percepts, list), "Percepts must be a list."
    assert len(percepts) == 4, "Percepts must be a length 4 list."

    percept_unit_clauses = []
    for wall_present, direction in zip(percepts, DIRECTIONS):
        percept_unit_clause = PropSymbolExpr(blocked_str_map[direction], t)
        if not wall_present:
            percept_unit_clause = ~PropSymbolExpr(blocked_str_map[direction], t)
        percept_unit_clauses.append(percept_unit_clause) # The actual sensor readings
    return conjoin(percept_unit_clauses)

def num_adj_walls_percept_rules(t, percepts):
    """
    SLAM uses a weaker num_adj_walls sensor, which tells us how many walls pacman is adjacent to
    in its four directions.
        000 = 0 adj walls.
        100 = 1 adj wall.
        110 = 2 adj walls.
        111 = 3 adj walls.
    """
    assert isinstance(percepts, list), "Percepts must be a list."
    assert len(percepts) == 3, "Percepts must be a length 3 list."

    percept_unit_clauses = []
    num_adj_walls = sum(percepts)
    for i, percept in enumerate(percepts):
        n = i + 1
        percept_literal_n = PropSymbolExpr(geq_num_adj_wall_str_map[n], t)
        if not percept:
            percept_literal_n = ~percept_literal_n
        percept_unit_clauses.append(percept_literal_n)
    return conjoin(percept_unit_clauses)

def allLegalSuccessorAxioms(t, walls_grid, non_outer_wall_coords):
    all_xy_succ_axioms = []
    for x, y in non_outer_wall_coords:
        xy_succ_axiom = pacmanSuccessorStateAxioms(
            x, y, t, walls_grid, var_str=pacman_str)
        if xy_succ_axiom:
            all_xy_succ_axioms.append(xy_succ_axiom)
    return conjoin(all_xy_succ_axioms)

# Abbreviations
plp = positionLogicPlan
# Sometimes the logic module uses pretty deep recursion on long expressions
sys.setrecursionlimit(100000)

Pacman intelligent agents AI/Project 3: Propositional logic-based agents/logicPlan.py


import math
s=input()
m=[]
k=s.split(" ")
print(k)
for i in k:
    try:
       if i[0].isalpha():
           m.append(i.title())
       else:
           m.append(i)
    except:
          m.append(" ")
          continue
print(m)
print(" ".join(m))


# import the necessary packages
import numpy as np
import cv2
import sqlite3
import io

def convert_array(text):
    out = io.BytesIO(text)
    out.seek(0)
    return np.load(out)

class CoverMatcher:
    def __init__(self, descriptor, ratio = 0.7, minMatches = 40, useHamming = True):
        # store the descriptor, book cover paths, ratio and minimum
        # number of matches for the homography calculation, then
        # initialize the distance metric to be used when computing
        # the distance between features
        self.descriptor = descriptor
        self.ratio = ratio
        self.minMatches = minMatches
        self.distanceMethod = "BruteForce"

        # if the Hamming distance should be used, then update the
        # distance method
        if useHamming:
            self.distanceMethod += "-Hamming"

    def search(self, queryKps, queryDescs):
        # Converts TEXT to np.array when selecting
        sqlite3.register_converter("array", convert_array)

        # initialize the dictionary of results
        results = {}
        conn = sqlite3.connect('db', detect_types=sqlite3.PARSE_DECLTYPES)
        c = conn.cursor()
        res = c.execute("SELECT * FROM images").fetchall()
        c.fetchall()

        # loop over the images stored in database
        for image in res:
            # load the query image, convert it to grayscale, and
            # extract keypoints and descriptors

            #cover = cv2.imread(image[0])
            #gray = cv2.cvtColor(cover, cv2.COLOR_BGR2GRAY)
            #(kps, descs) = self.descriptor.describe(gray)

            # determine the number of matched, inlier keypoints,
            # then update the results

            kps = image[3]
            descs = image[4]

            score = self.match(queryKps, queryDescs, kps, descs)
            results[image[0]] = score
            print(image[0] + ": " + str(score))

        # if matches were found, sort them
        if len(results) > 0:
            results = sorted([(v, k) for (k, v) in results.items() if v > 0],
                reverse = True)

        # return the results
        return results

    def match(self, kpsA, featuresA, kpsB, featuresB):
        # compute the raw matches and initialize the list of actual
        # matches
        matcher = cv2.DescriptorMatcher_create(self.distanceMethod)
        rawMatches = matcher.knnMatch(featuresB, featuresA, 2)
        matches = []

        # loop over the raw matches
        for m in rawMatches:
            # ensure the distance is within a certain ratio of each
            # other
            if len(m) == 2 and m[0].distance < m[1].distance * self.ratio:
                matches.append((m[0].trainIdx, m[0].queryIdx))

        # check to see if there are enough matches to process
        if len(matches) > self.minMatches:
            # construct the two sets of points
            ptsA = np.float32([kpsA[i] for (i, _) in matches])
            ptsB = np.float32([kpsB[j] for (_, j) in matches])

            # compute the homography between the two sets of points
            # and compute the ratio of matched points
            (_, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, 4.0)

            # return the ratio of the number of matched keypoints
            # to the total number of keypoints
            return float(status.sum()) / status.size

        # no matches were found
        return -1.0


from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from ..views.common import *
import json

class UserMiddleware(MiddlewareMixin):
	"""Checks if the user is allowed to access the page they are requesting."""

	def process_request(self, request):
		"""The main part of the middleware, called each time a user makes a request."""
		# Initialization.
		url = request.path
		urls = url.replace("//", "/").split("/")
		first_url = urls[1]

		if 'HTTP_AUTHORIZATION' in request.META or "api" in first_url:
			return None

		if first_url == 'superradmin':
			return None

		not_required_session = [
			"register",
			"login",
			"logout",
			"landingpage",
			"superradmin",
		]

		no_action = [
			"logout",
			"",
			"/",
			# "apiv1",
		]

		if first_url not in not_required_session and not request.user.id:
			if request.method == "GET":
				if first_url not in no_action:
					return redirect("loginpage")

		if first_url in not_required_session and request.user.id:
			if request.method == "GET":
				if first_url not in no_action:
					return redirect("home")

		return None


import os
import sys
import json
import argparse

def write_ts_interface(name, content, outdir="./"):
	if outdir[-1] != "/":
		outdir += "/"

	iname = "I{}".format(name)
	filename = "{}{}.d.ts".format(outdir, iname)
	output = "export default interface {} {{\n".format(iname)

	for key in content.keys():

		if type(content[key]) is dict:
			iname_tmp = "I{}".format(key.title())
			output = "import {name} from './{name}';\n{out}\t{k}: {name};\n".format(name=iname_tmp, out=output, k=key)
			write_ts_interface(iname_tmp[1:], content[key], outdir)

		elif type(content[key]) is list:
			tmp = content[key]
			if len(tmp):
				if type(tmp[0]) is dict:
					iname_tmp = "I{}".format(key.title())
					output = "import {name} from './{name}';\n{out}\t{k}: {name}[];\n".format(name=iname_tmp, out=output, k=key)
					write_ts_interface(iname_tmp[1:], tmp[0], outdir)

				else:
					output += "\t{}: {}[];\n".format(key, str(content[key]))

		else:
			output += "\t{}: {};\n".format(key, content[key])

	output += "}\n"
	with open(filename, "w") as file:
		file.write(output)

	print(filename)

def parse_json_file(filepath, outdir="./"):
	filename = os.path.basename(filepath)
	tsname = filename

	if ".json" in filename:
		for s in ("DTO", "_", ".json"):
			tsname = tsname.replace(s, "");

		try:
			with open(filepath) as jfile:
				content = json.load(jfile)
				write_ts_interface(tsname, content, outdir)
		except Exception as e:
			print(filename, e)

def init_parser():
	parser = argparse.ArgumentParser(description="Convert json to typescript interface")
	parser.add_argument("inputFile", help="Path to the json files", nargs="*")
	parser.add_argument("-o", "--output", help="Output directory")

	return parser

def main():
	parser = init_parser()
	parser = parser.parse_args(sys.argv[1:])

	if parser.output and os.path.exists(parser.output):
		outdir = parser.output
	else:
		outdir = "./"

	for file in parser.inputFile:
		if os.path.exists(file):
			parse_json_file(file, outdir)

if __name__ == "__main__":
	main()