"""
Copyright (C) 2018 Bricks Brought to Life
http://bblanimation.com/
chris@bblanimation.com

Created by Christopher Gearhart

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

# System imports
import bmesh
import math
import time
import sys
import random
import json
import copy
import numpy as np

# Blender imports
import bpy
from mathutils import Vector, Matrix

# Addon imports
from .hashObject import hash_object
from ..lib.Brick import Bricks
from ..lib.bricksDict import *
from .common import *
from .wrappers import *
from .general import *
from ..lib.caches import bricker_mesh_cache

def drawBrick(cm, cm_id, bricksDict, key, loc, i, dimensions, zStep, brickSize, brickType, split, lastSplitModel, customData, brickScale, bricksCreated, allMeshes, logo, logo_details, mats, brick_mats, internalMat, brickHeight, logoResolution, logoDecimate, loopCut, buildIsDirty, materialType, materialName, randomMatSeed, studDetail, exposedUndersideDetail, hiddenUndersideDetail, randomRot, randomLoc, logoType, logoScale, logoInset, circleVerts, randS1, randS2, randS3):
    brickD = bricksDict[key]
    # check exposure of current [merged] brick
    if brickD["top_exposed"] is None or brickD["bot_exposed"] is None or buildIsDirty:
        topExposed, botExposed = setAllBrickExposures(bricksDict, zStep, key)
    else:
        topExposed, botExposed = isBrickExposed(bricksDict, zStep, key)

    # get brick material
    mat = getMaterial(cm, bricksDict, key, brickSize, zStep, materialType, materialName, randomMatSeed, brick_mats=brick_mats, seedInc=i)

    # set up arguments for brick mesh
    useStud = (topExposed and studDetail != "NONE") or studDetail == "ALL"
    logoToUse = logo if useStud else None
    undersideDetail = exposedUndersideDetail if botExposed else hiddenUndersideDetail

    ### CREATE BRICK ###

    # add brick with new mesh data at original location
    if brickD["type"].startswith("CUSTOM"):
        m = customData[int(brickD["type"][-1]) - 1]
    else:
        # get brick mesh
        m = getBrickData(brickD, randS3, dimensions, brickSize, brickType, brickHeight, logoResolution, logoDecimate, circleVerts, loopCut, undersideDetail, logoToUse, logoType, logo_details, logoScale, logoInset, useStud)
    # apply random rotation to edit mesh according to parameters
    randomRotMatrix = getRandomRotMatrix(randomRot, randS2, brickSize) if randomRot > 0 else None
    # get brick location
    locOffset = getRandomLoc(randomLoc, randS2, dimensions["width"], dimensions["height"]) if randomLoc > 0 else Vector((0, 0, 0))
    brickLoc = getBrickCenter(bricksDict, key, loc, zStep) + locOffset

    if split:
        print(1)
        brick = bpy.data.objects.get(brickD["name"])
        if brick:
            # NOTE: last brick mesh is left in memory (faster)
            # set brick.data to new mesh (resets materials)
            print(2)
            brick.data = m
            # add/remove edge split modifier if necessary
            print(3)
            eMod = brick.modifiers.get('Edge Split')
            if not eMod and useEdgeSplitMod(cm, brickD):
                addEdgeSplitMod(brick)
            elif eMod and not useEdgeSplitMod(cm, brickD):
                brick.modifiers.remove(eMod)
            print(4)
        else:
            # create new object with mesh data
            brick = bpy.data.objects.new(brickD["name"], m)
            brick.cmlist_id = cm_id
            print(5)
            # add edge split modifier
            if useEdgeSplitMod(cm, brickD):
                addEdgeSplitMod(brick)
            print(6)
        # rotate brick by random rotation
        if randomRotMatrix is not None:
            brick.matrix_world = Matrix.Identity(4) * randomRotMatrix
        print(6)
        # set brick location
        brick.location = brickLoc
        print(7)
        # set brick material
        if len(m.materials) > 0 or len(brick.material_slots) > 0:
            m.materials.clear(1)
        print(8)
        if mat is not None or internalMat is not None:
            m.materials.append(mat or internalMat)
            brick.material_slots[0].link = 'OBJECT'
            brick.material_slots[0].material = mat or internalMat
        print(9)
        # append to bricksCreated
        bricksCreated.append(brick)
        print(10)
    else:
        # duplicates mesh – prevents crashes (TODO: test without this line in 2.8)
        print(1)
        print(m)
        m = m.copy()
        print(m)
        print(2)
        # apply rotation matrices to edit mesh
        if randomRotMatrix is not None:
            m.transform(randomRotMatrix)
        print(3)
        # transform brick mesh to coordinate on matrix
        m.transform(Matrix.Translation(brickLoc))

        print(4)
        # set to internal mat if material not set
        internal = False
        if mat is None:
            mat = internalMat
            internal = True
        print(5)

        # keep track of mats already used
        if mat in mats:
            matIdx = mats.index(mat)
        elif mat is not None:
            mats.append(mat)
            matIdx = len(mats) - 1
        print(6)

        # set material
        if mat is not None:
            # set material name in dictionary
            print(7)
            if not internal:
                brickD["mat_name"] = mat.name
            print(8)
            # point all polygons to target material (index will correspond in allMeshes object)
            for p in m.polygons:
                p.material_index = matIdx

        # append mesh to allMeshes bmesh object
        print(9)
        allMeshes.from_mesh(m)

        # remove duplicated mesh (TODO: test without this line in 2.8)
        print(10)
        bpy.data.meshes.remove(m)
        # NOTE: The following lines clean up the mesh if not duplicated
        # # reset polygon material mapping
        # if mat is not None:
        #     for p in m.polygons:
        #         p.material_index = 0
        #
        # # reset transformations for reference mesh
        # m.transform(Matrix.Translation(-brickLoc))
        # if randomRotMatrix is not None:
        #     randomRotMatrix.invert()
        #     m.transform(randomRotMatrix)
    print(11)

    return bricksDict

def useEdgeSplitMod(cm, brickD):
    typ = brickD["type"]
    if ("CUSTOM" not in brickD["type"] or
        (typ == "CUSTOM 1" and cm.customObjectName1.startswith("Bricker_")) or
        (typ == "CUSTOM 2" and cm.customObjectName2.startswith("Bricker_")) or
        (typ == "CUSTOM 3" and cm.customObjectName3.startswith("Bricker_"))):
        return True
    else:
        return False

def addEdgeSplitMod(obj):
    """ Add edge split modifier """
    eMod = obj.modifiers.new('Edge Split', 'EDGE_SPLIT')
    eMod.split_angle = math.radians(44)

def mergeWithAdjacentBricks(brickD, bricksDict, key, keysNotChecked, defaultSize, zStep, randS1, buildIsDirty, brickType, maxWidth, maxDepth, legalBricksOnly, mergeInconsistentMats, mergeInternals, materialType, mergeVertical=True):
    if brickD["size"] is None or buildIsDirty:
        preferLargest = brickD["val"] > 0 and brickD["val"] < 1
        brickSize = attemptMerge(bricksDict, key, keysNotChecked, defaultSize, zStep, randS1, brickType, maxWidth, maxDepth, legalBricksOnly, mergeInconsistentMats, mergeInternals, materialType, preferLargest=preferLargest, mergeVertical=mergeVertical, height3Only=brickD["type"] in getBrickTypes(height=3))
    else:
        brickSize = brickD["size"]
    return brickSize

def updateKeysLists(bricksDict, size, zStep, key, loc, availableKeys):
    keysChecked = getKeysInBrick(bricksDict, size, zStep, key, loc)
    for k in keysChecked:
        # remove key if it exists in availableKeys
        remove_item(availableKeys, k)

def skipThisRow(timeThrough, lowestZ, z, offsetBrickLayers):
    if timeThrough == 0:  # first time
        if (z - offsetBrickLayers - lowestZ) % 3 in (1, 2):
            return True
    else:  # second time
        if (z - offsetBrickLayers - lowestZ) % 3 == 0:
            return True
    return False

def getRandomLoc(randomLoc, rand, width, height):
    """ get random location between (0,0,0) and (width/2, width/2, height/2) """
    loc = Vector((0,0,0))
    loc.xy = [rand.uniform(-(width/2) * randomLoc, (width/2) * randomLoc)]*2
    loc.z = rand.uniform(-(height/2) * randomLoc, (height/2) * randomLoc)
    return loc

def getRandomRotMatrix(randomRot, rand, brickSize):
    """ get rotation matrix randomized by randomRot """
    denom = 0.75 if max(brickSize) == 0 else brickSize[0] * brickSize[1]
    mult = randomRot / denom
    # calculate rotation angles in radians
    x = rand.uniform(-math.radians(11.25) * mult, math.radians(11.25) * mult)
    y = rand.uniform(-math.radians(11.25) * mult, math.radians(11.25) * mult)
    z = rand.uniform(-math.radians(45)    * mult, math.radians(45)    * mult)
    # get rotation matrix
    x_mat = Matrix.Rotation(x, 4, 'X')
    y_mat = Matrix.Rotation(y, 4, 'Y')
    z_mat = Matrix.Rotation(z, 4, 'Z')
    combined_mat = x_mat * y_mat * z_mat
    return combined_mat

def prepareLogoAndGetDetails(scn, logo, detail, scale, dimensions):
    """ duplicate and normalize custom logo object; return logo and bounds(logo) """
    if logo is None:
        return None, logo
    # duplicate logo object
    logo = duplicate(logo, link_to_scene=True)
    if detail != "LEGO":
        # disable modifiers for logo object
        for mod in logo.modifiers:
            mod.show_viewport = False
        # apply logo object transformation
        logo.parent = None
        apply_transform(logo)
    safeUnlink(logo)
    # get logo details
    logo_details = bounds(logo)
    m = logo.data
    # select all verts in logo
    for v in m.vertices:
        v.select = True
    # create transform and scale matrices
    t_mat = Matrix.Translation(-logo_details.mid)
    distMax = max(logo_details.dist.xy)
    lw = dimensions["logo_width"] * (0.78 if detail == "LEGO" else scale)
    s_mat = Matrix.Scale(lw / distMax, 4)
    # run transformations on logo mesh
    m.transform(t_mat)
    m.transform(s_mat)
    return logo_details, logo

def getBrickData(brickD, rand, dimensions, brickSize, brickType, brickHeight, logoResolution, logoDecimate, circleVerts, loopCut, undersideDetail, logoToUse, logoType, logo_details, logoScale, logoInset, useStud):
    # get bm_cache_string
    bm_cache_string = ""
    if "CUSTOM" not in brickType:
        custom_logo_used = logoToUse is not None and logoType == "CUSTOM"
        bm_cache_string = json.dumps((brickHeight, brickSize, undersideDetail,
                                      logoResolution if logoToUse is not None else None,
                                      logoDecimate if logoToUse is not None else None,
                                      logoInset if logoToUse is not None else None,
                                      hash_object(logoToUse) if custom_logo_used else None,
                                      logoScale if custom_logo_used else None,
                                      logoType, useStud, circleVerts,
                                      brickD["type"], loopCut, dimensions["gap"],
                                      brickD["flipped"] if brickD["type"] in ("SLOPE", "SLOPE_INVERTED") else None,
                                      brickD["rotated"] if brickD["type"] in ("SLOPE", "SLOPE_INVERTED") else None))

    # check for bmesh in cache
    meshes = bricker_mesh_cache.get(bm_cache_string)
    # if not found create new brick mesh(es) and store to cache
    if meshes is None:
        # create new brick bmeshes
        bms = Bricks.new_mesh(dimensions, brickType, size=brickSize, type=brickD["type"], flip=brickD["flipped"], rotate90=brickD["rotated"], loopCut=loopCut, logo=logoToUse, logoType=logoType, logoScale=logoScale, logoInset=logoInset, all_vars=logoToUse is not None, logo_details=logo_details, undersideDetail=undersideDetail, stud=useStud, circleVerts=circleVerts)
        # create edit mesh for each bmesh
        meshes = []
        for i,bm in enumerate(bms):
            # create new mesh and send bm to it
            bmcs_hash = hash_str(bm_cache_string)
            meshName = "%(bmcs_hash)s_%(i)s" % locals()
            m = bpy.data.meshes.get(meshName)
            # create new edit mesh and send bmesh data to it
            if m is None:
                m = bpy.data.meshes.new(meshName)
                bm.to_mesh(m)
                # center mesh origin
                centerMeshOrigin(m, dimensions, brickSize)
            meshes.append(m)
        # store newly created meshes to cache
        if brickType != "CUSTOM":
            bricker_mesh_cache[bm_cache_string] = meshes

    # pick edit mesh randomly from options
    m0 = meshes[rand.randint(0, len(meshes))] if len(meshes) > 1 else meshes[0]

    return m0

def getMaterial(cm, bricksDict, key, size, zStep, materialType, materialName, randomMatSeed, brick_mats=None, seedInc=None):
    mat = None
    highestVal = 0
    matsL = []
    matDirty = cm.materialIsDirty or cm.matrixIsDirty or cm.buildIsDirty
    if bricksDict[key]["custom_mat_name"] and not matDirty:
        mat = bpy.data.materials.get(bricksDict[key]["mat_name"])
    elif materialType == "CUSTOM":
        mat = bpy.data.materials.get(materialName)
    elif materialType == "SOURCE":
        # get most frequent material in brick size
        keysInBrick = getKeysInBrick(bricksDict, size, zStep, key)
        for key0 in keysInBrick:
            curBrickD = bricksDict[key0]
            if curBrickD["val"] >= highestVal:
                highestVal = curBrickD["val"]
                matName = curBrickD["mat_name"]
                if curBrickD["val"] == 1:
                    matsL.append(matName)
        # if multiple shell materials, use the most frequent one
        if len(matsL) > 1:
            matName = most_common(matsL)
        mat = bpy.data.materials.get(matName)
    elif materialType == "RANDOM" and brick_mats is not None and len(brick_mats) > 0:
        if len(brick_mats) > 1:
            randState = np.random.RandomState(0)
            randState.seed(randomMatSeed + seedInc)
            randIdx = randState.randint(0, len(brick_mats))
        else:
            randIdx = 0
        matName = brick_mats[randIdx]
        mat = bpy.data.materials.get(matName)
    return mat

def updateBrickSizesAndTypesUsed(cm, sz, typ):
    bsu = cm.brickSizesUsed
    btu = cm.brickTypesUsed
    cm.brickSizesUsed += sz if bsu == "" else ("|%(sz)s" % locals() if sz not in bsu else "")
    cm.brickTypesUsed += typ if btu == "" else ("|%(typ)s" % locals() if typ not in btu else "")


def check(l:int, r:int, L:int, R:int):
    if ((r - l + 1) % (R - L + 1)!=0): return 0;
    for i in range(l, r + 1):
        if (s[i] != s[(i - l) % (R - L + 1) + L]): return 0;
    return 1;

def dfs(l:int, r:int):
    if  l == r : return "".join(s[l:l + 1]);
    if  len(f[l][r]) > 0 : return f[l][r];
    f[l][r] = "".join(s[l:l + r - l + 1]);
    for i in range(l, r):
        if (len(f[l][r]) >( len(dfs(l, i)) + len(dfs(i + 1, r)))):
            f[l][r] = dfs(l, i) + dfs(i + 1, r);
    for i in range(l, r):
        if (check(l, i, i + 1, r) == 1):  # daozheli
            strtemp = str(int((r - l + 1) / (r - i))) + "(" + dfs(i + 1, r) + ")";
            if (len(f[l][r]) > len(strtemp)):
                f[l][r] = strtemp;
    return f[l][r];

s = list(input());
lenngthmy = len(s);
f = [] ;
for i in range(100):
    f.append([""] * (100));
# f[0][17]="agfdsag";
# print(len(f[0][17]))
print(dfs(0, lenngthmy - 1));


def formula(x):
    return (x ** 3) - (3 * x ** 2) - 12 * x + 10

hazard_level = float(input('Введите максимально допустимый уровень опасности:'))

minimum_depth = 0
maximum_depth = 4

middle = minimum_depth + (maximum_depth - minimum_depth) / 2
lvl_danger = formula(middle)

while abs(lvl_danger) > hazard_level:
    if lvl_danger > 0:
        minimum_depth = middle
    else:
        maximum_depth = middle
    middle = minimum_depth + (maximum_depth - minimum_depth) / 2
    lvl_danger = formula(middle)

print('Приблизительная глубина безопасной кладки:', middle)


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from BITEhack.forms import ContactForm, SnippetForm, Plot2dForm
from .models import  DefaultUser, Project, Folder, Event
from django.contrib.auth.decorators import login_required, permission_required
from django.core import serializers
from . import forms
from django.contrib.auth import authenticate, login

def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            print(name, email)

    form = ContactForm()
    return render(request, 'form.html', {'form': form})

def snippet_detail(request):
    if request.method == "POST":
        form = SnippetForm(request.POST)
        if form.is_valid():
            form.save()
            print('WE GOOD BOI')

    form = SnippetForm()
    return render(request, 'form.html', {'form': form})

def index(request):
    return render(request, 'index.html')

@login_required
def test(request):
    return HttpResponse("TEST")

def create_user(request):
    if request.method == 'POST':
        user_form = forms.UserForm(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data['password'])
            new_user.save()
            return render(request, 'base.html')
    else:
        user_form = forms.UserForm
    return render(request, 'add_user.html', {'user_form': user_form})

@login_required
def user_profile(request):
    def create_project_dict(project_model):
        return {'name': project_model.name, 'desc': project_model.description }
    def create_friend_dict(user_model):
        return {'name': user_model.username }
    user = DefaultUser.objects.get(username=request.user.username)
    projects = user.projects.all()
    projects_table = [create_project_dict(project) for project in projects]
    friends = user.friends.all()
    friends_table = [create_friend_dict(user) for user in friends]
    return render(request, 'user_profile.html', {'projects': projects_table, 'friends':friends_table})

def wall(request):
    def create_event_dict(event_model):
        return {'name': event_model.project.name,
                'action': event_model.action,
                'time': str(event_model.date)}
    events = Event.objects.all()
    events_table = [create_event_dict(event) for event in events]
    return render(request, 'wall.html', {'events': events_table})

class clusterer():

    def create(self, *args, **kwargs):
        from sklearn.cluster import KMeans
        self.cls = KMeans(*args, **kwargs)
        print("Clustering algorithm prepared")

    def train(self, data):
        self.cls.fit(data)
        print("Training has concluded")

    def predict(self, data):
        import numpy as np
        import seaborn as sns
        cmap = ['red', 'green', 'blue','black', 'yellow', 'cyan', 'orange', 'purple']
        self.predicted = self.cls.predict(data)
        samples = data.shape[0]
        for i in np.unique(self.predicted):
            dt = data[self.predicted == i]
            sns.regplot(dt[:,0], dt[:,1], fit_reg=False, color = cmap[i%len(cmap)], marker ='.')

def cluster(request):
    if request.method == 'POST':
        user_form = Plot2dForm(request.POST)
        if user_form.is_valid():

            n_clusters = int(user_form.cleaned_data['clusters'])

        else:
            n_clusters = 3

        import matplotlib.pyplot as plt
        from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
        from matplotlib.figure import Figure
        import numpy as np
        import io
        import pandas as pd

        data = np.array(pd.read_excel('1.xlsx'))
        f = Figure()

        a = data#= np.random.rand(300, 2) * 100

        c = clusterer()
        c.create(n_clusters=n_clusters)
        c.train(a)

        x = np.linspace(np.min(a[:,0]), np.max(a[:,0]), 1000)
        y = np.linspace(np.min(a[:,1]), np.max(a[:,1]), 1000)

        xx, yy = np.meshgrid(x, y)
        xx = xx.reshape(1000000,1)
        yy = yy.reshape(1000000,1)
        ad = np.concatenate((xx, yy), axis=1)
        c.predict(ad)

        # Code that sets up figure goes here; in the question, that's ...
        FigureCanvas(f)

        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        plt.close(f)
        response = HttpResponse(buf.getvalue(), content_type='image/png')
        #response = HttpResponse('HI')
        return response
    else:
        form = Plot2dForm()
        return render(request, 'plot2d_form.html', {'form': form})

        #return HttpResponse('4qwasdasde')  #response
@login_required
def project_view(request):
    project_name = request.GET.get('project_name', '')
    dictiornary = {}
    files_list = []
    if project_name is not None:
        flag = Project.objects.filter(name=project_name).exists()
        if flag:
            proj = Project.objects.get(name=project_name)
            dictiornary['name'] = proj.name
            dictiornary['desc'] = proj.description
            dictiornary['type'] = proj.dtype
            files = Folder.objects.filter(project=proj).all()
            files_list = [f.title for f in files]
            print(files_list)

    return render(request, 'project.html', {'project':dictiornary, 'files': files_list} )

def upload_file(request):
    if request.method == 'POST':
        upload_form = forms.ModelFormWithFileField(request.POST, request.FILES)
        if upload_form.is_valid():
            # file is saved
            upload_form.save()
            return HttpResponseRedirect('wall')
    else:
        upload_form = forms.ModelFormWithFileField()
    return render(request, 'upload.html', {'upload_form': upload_form})

def get_projects(request):
    projects = Project.objects.all()
    json = serializers.serialize('json', projects)
    return HttpResponse(json)

def projects_view(request):
    return render(request, 'projects.html')

def regression(request):
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    import numpy as np
    import io
    from sklearn.linear_model import LinearRegression
    f = Figure()

    sample = np.random.chisquare(1, 200)
    points = np.linspace(-np.pi, 0, 200)
    res = np.sin(points) + sample
    model = LinearRegression()
    model.fit(points.reshape(200,1), res.reshape(200,1))
    space = np.linspace(np.min(points) , np.max(points), 1000).reshape(-1, 1)
    pred = model.predict(space)
    plt.scatter(points, res)
    plt.plot(space,pred, c='red')

    FigureCanvas(f)

    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(f)
    response = HttpResponse(buf.getvalue(), content_type='image/png')
    return response

def plot2d(request):
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    import numpy as np
    import io
    f = Figure()

    samples = np.random.randint(200, size=(500,2))
    plt.scatter(samples[:,0], samples[:,1])

    FigureCanvas(f)

    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(f)
    response = HttpResponse(buf.getvalue(), content_type='image/png')
    return response

def plot3d(request):
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    import numpy as np
    import io
    from mpl_toolkits.mplot3d import Axes3D
    f = Figure()

    def Bumps(x,y):
        return np.sin(5 * x) * np.cos(5 * y)/5

    x = np.linspace(-np.pi/2, np.pi/2, 1000)
    y = np.linspace(-np.pi/2, np.pi/2, 1000)
    xx, yy = np.meshgrid(x, y)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    z = Bumps(xx,yy).reshape((1000,1000))
    ax.plot_surface(xx, yy, z)

    FigureCanvas(f)

    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(f)
    response = HttpResponse(buf.getvalue(), content_type='image/png')
    return response

def hist(request):
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    import numpy as np
    import io
    f = Figure()

    sample = np.random.chisquare(100, 200000)
    fig, ax = plt.subplots()
    ax.hist(sample, 50, density=1)
    ax.set_title('chi_square')
    ax.set_xlabel('value')
    ax.set_ylabel('Probability density')

    FigureCanvas(f)

    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(f)
    response = HttpResponse(buf.getvalue(), content_type='image/png')
    return response


# -*- coding: utf-8 -*-
"""
Created on Mon Jan  6 23:25:57 2020

@author: Tanya
"""

#import numpy as np
import cv2
import os
import numpy as np
from matplotlib import pyplot as plt
#import matplotlib.image as mpimg
#import matplotlib.pyplot as plt
import numpy
from PIL import Image
import glob
import IPython.display as display

path = r'C:\\Users\\Tanya\\Desktop\\IASR\\rottenoranges'  # path to the original dataset
outpath = 'C:\\Users\\Tanya\\Downloads\\AI3\\ISR\\rottenoranges'  # path to the resized images
outpath2 = 'C:\\Users\\Tanya\\Downloads\\AI3\\ISR\\withoutCorners' # path to the mages without the black corners

filenames = glob.glob(path + "/*.png") #read all files in the path mentioned
f = glob.glob(outpath + "/*.png")
fpath = glob.glob(outpath2 + "/*.png")

def resizeImages(filenames):
    for x in filenames:
        basewidth = 340
        img = Image.open(x)
        #wpercent = (basewidth/float(img.size[0]))
        #hsize = int((float(img.size[1])*float(wpercent)))
        hsize = 277
        img = img.resize((basewidth,hsize), Image.ANTIALIAS)
        #plt.imshow(img)
        src_fname, ext = os.path.splitext(x)  # split filename and extension
        # construct output filename, basename to remove input directory
        save_fname = os.path.join(outpath, os.path.basename(src_fname)+'.png')
        img.save(save_fname)

def changeColorOfEdges(img):
    img = Image.open(img)
    np_im = numpy.array(img)
    #img = mpimg.imread(img)
    #img = Image.open(img)
    # height, width, number of channels in image
    height = img.size[1]
    width = img.size[0]
    for row in range(height): #each pixel has coordinates
        for col in range(width):
            if  (np_im[row, col] <= (0, 0, 0)).all():
                if row < 70 and col < 250:
                    np_im[row, col] = [255]
                elif row < 190 and col > 300:
                    np_im[row, col] = [255]
                elif row > 150 and col < 60:
                    np_im[row, col] = [255]
                elif row > 220 and col > 190:
                    np_im[row, col] = [255]
    new_im = Image.fromarray(np_im)
    return new_im

#image_out = Image.new(img.mode,img.size)
#image_out.putdata(img)
#img.save('C:\\Users\\Tanya\\Downloads\\AI3\\ISR\\banana.png')
#size, resize, if black turn to white
#img = mpimg.imread('C:\\Users\\Tanya\\Desktop\\IASR\\rottenoranges\\rotated_by_15_Screen Shot 2018-06-12 at 11.18.34 PM.png')

def removeBlackCorners(f):
    for i in f:
        #img = Image.open(i)
        #img = mpimg.imread(i)
        img = changeColorOfEdges(i)
        src_fname, ext = os.path.splitext(i)  # split filename and extension
        # construct output filename, basename to remove input directory
        save_fname = os.path.join(outpath2, os.path.basename(src_fname)+'.png')
        img.save(save_fname)
        #plt.imshow(img)
        #display.display(img)

def removeBackgrounds(fpath):
    for m in fpath:
        image_bgr = cv2.imread(m)
        image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)

        # Rectange values: start x, start y, width, height
        rectangle = (3, 10, 320, 235)

        # Create initial mask
        mask = np.zeros(image_rgb.shape[:2], np.uint8)

        # Create temporary arrays used by grabCut
        bgdModel = np.zeros((1, 65), np.float64)
        fgdModel = np.zeros((1, 65), np.float64)

        # Run grabCut
        cv2.grabCut(image_rgb, # Our image
                mask, # The Mask
                rectangle, # Our rectangle
                bgdModel, # Temporary array for background
                fgdModel, # Temporary array for background
                5, # Number of iterations
                cv2.GC_INIT_WITH_RECT) # Initiative using our rectangle

        # Create mask where sure and likely backgrounds set to 0, otherwise 1
        mask_2 = np.where((mask==2) | (mask==0), 0, 1).astype('uint8')

        # Multiply image with new mask to subtract background
        image_rgb_nobg = image_rgb * mask_2[:, :, np.newaxis]

        # Show image
        plt.imshow(image_rgb_nobg), plt.axis("off")
        plt.show()

"""
#img = changeColorOfEdges('C:\\Users\\Tanya\\Downloads\\AI3\\ISR\\banana.png')
img2 = changeColorOfEdges(outpath + "\\" + "rotated_by_15_Screen Shot 2018-06-12 at 11.18.34 PM.png")
# Output Images
# Output Images

plt.imshow(img2)
"""
# rotated_by_15_Screen Shot 2018-06-12 at 8.49.20 PM C:\Users\Tanya\Desktop
# myarray = np.loadtxt(x, skiprows=9)
   # im = Image.fromarray(myarray)
   # im.save(outpath + '/*.tif')
#image_list = []
#for filename in glob.glob('C:\\Users\\Tanya\\Desktop\\IASR\\rottenoranges/*.png'): #assuming gif

    #image_list.append(im)


# Coltin Lappin-Lux (Data Analyst)
# lux.coltin@gmail.com
# Boys and Girls Club of Hawaii
# 1/25/18

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from openpyxl import Workbook
from openpyxl import load_workbook

#===============================================================================
# Attribute List (Both Duplicated and Unduplicated) - List without blank cells
#===============================================================================

def att_list(sheet, col, row):
    #Where to find attribute (Column and Row) Ex. 'B', 2
    duplicate_list = []
    unduplicated_list = []

    index = row
    i = col + str(index)
    while sheet[i].value != None:
        #print(sheet[i].value)
        i = col + str(index)
        if sheet[i].value != None:
            duplicate_list.append(sheet[i].value)
        index += 1

    for i in duplicate_list:
        if unduplicated_list.count(i) == 0:
            unduplicated_list.append(i)

    unduplicated_list.sort()

    return unduplicated_list, duplicate_list

#==================================================================================
# Attribute List 2 (Both Duplicated and Unduplicated) - List with blank cells
#==================================================================================

def att_list_2(sheet, list_length, col, row):
    #Where to find attribute (Column and Row) Ex. 'B', 2
    duplicate_list = []
    unduplicated_list = []

    #attribute counter
    att_index = row
    att_i = col + str(att_index)

    #primary attribute counter
    pri_index = 2
    pri_i = 'B' + str(pri_index)

    for x in range(list_length):
        att_i = col + str(att_index)
        pri_i = 'B' + str(pri_index)
        if sheet[att_i].value == None:
            duplicate_list.append([sheet[pri_i].value,"Unknown"])
        else:
            duplicate_list.append([sheet[pri_i].value,sheet[att_i].value])
        att_index += 1
        pri_index += 1

    #attribute counter
    att_index = row
    att_i = col + str(att_index)

    for z in range(list_length):
        att_i = col + str(att_index)
        if unduplicated_list.count(sheet[att_i].value) == 0:
            if sheet[att_i].value == None:
                if unduplicated_list.count("Unknown") == 0:
                    unduplicated_list.append("Unknown")
            else:
                unduplicated_list.append(sheet[att_i].value)
        att_index += 1

    print(unduplicated_list)

    inttemp = []
    strtemp = []

    for a in unduplicated_list:
    	if type(a) == int:
    		inttemp.append(a)
    		inttemp.sort()
    	if type(a) == str:
    		strtemp.append(a)
    		strtemp.sort()

    unduplicated_list = []

    for b in inttemp:
    	unduplicated_list.append(b)
    for c in strtemp:
    	unduplicated_list.append(c)

    print(unduplicated_list)
    return unduplicated_list, duplicate_list

#===============================================================================
# Count
#===============================================================================

def count(what, where):
    #what = what to count (List)
    #where = where to find it (Location)

    results = []

    for x in what:
        results.append([x,where.count(x)])

    return results

#===============================================================================
# Attribute Count
#===============================================================================

def attribute_count(what, where):
    #what = what to count (List)
    #where = where to find it (Location)

    results = []
    count = 0

    for x in what:
        count = 0
        for y in where:
            if x == y[1]:
                count += 1
        results.append([x,count])

    return results

#===============================================================================
# Attribute Percentage
#===============================================================================

def attribute_percentage(att_count):
    #what = what to count (List)
    #where = where to find it (Location)

    results = []
    total = 0
    temp = 0
    for i in range(len(att_count)):
        total = total + att_count[i][1]
    for i in range(len(att_count)):
        temp = att_count[i][1]/total
        results.append([att_count[i][0],temp])

    return results

#===============================================================================
# Count By Club
#===============================================================================

def countByClub(bgch_list, undup, dup):
    #what = what to count (List)
    #where = where to find it (Location)
    #[clubhouse, attribute, count]

    results = []

    for x in bgch_list:
        for y in undup:
            count = 0
            for z in dup:
                if x == z[0] and y == z[1]:
                    count += 1
            results.append([x,y,count])

    return results

#===============================================================================
# Total Count
#===============================================================================

def total(what):
    #what = what to count (List)

    results = len(what)

    return results

#==================================================================
# Main Function (Initialize Variables and Call Functions)
#==================================================================

def main():
    """
    This function executes when this file is run as a script.
    """

    #==================================================================
    # Open Workbooks (Input and Output Excel Sheets)
    #==================================================================
    #Reading in existing Workbook
    title = input("Input Excel Title: ")
    title = title + '.xlsx'

    wb = load_workbook(filename = title)

    #Creating Revised Workbook
    rwb = Workbook()
    dest_filename = input("Output Excel Title: ")
    dest_filename = dest_filename + '.xlsx'

    #==================================================================
    # While loop in case user wants to summarize multiple excel sheets
    #==================================================================
    #Data Calculation
    continuetill = 'yes'
    while continuetill == 'yes':
        sheetname = input("Input Sheet Name/Number: ")
        sheet = wb[sheetname]
        revisedSheet = rwb.active
        revisedSheet = rwb.create_sheet(title=sheetname)

        #==================================================================
        # Summarize Membership Data
        #==================================================================
        #Primary Attribute - Clubhouse
        bgch_clubhouse_list, duplicated_bgch_clubhouse_list = att_list(sheet, 'B', 2)
        #print(bgch_clubhouse_list)

        #Count how many members per clubhouse
        membership_count = count(bgch_clubhouse_list, duplicated_bgch_clubhouse_list)
        membership_total = total(duplicated_bgch_clubhouse_list)
        list_length = len(duplicated_bgch_clubhouse_list)
        membership_count.append(["Total", membership_total])

        #==================================================================
        # Print Title and other document details to new Excel
        #==================================================================
        #Title
        title_index = 1
        title_loc = 'A' + str(title_index)
        revisedSheet[title_loc] = 'Boys & Girls Club of Hawaii'
        #Report Type
        title_index = 2
        title_loc = 'A' + str(title_index)
        revisedSheet[title_loc] = 'Report Type:'
        #Period
        title_index = 3
        title_loc = 'A' + str(title_index)
        revisedSheet[title_loc] = 'Period:'
        #Description
        title_index = 4
        title_loc = 'A' + str(title_index)
        revisedSheet[title_loc] = 'Preparation Date: '

        #==================================================================
        # Print Membership Summary to new Excel
        #==================================================================
        #Membership Data
        club_index = 6
        club_i = 'A' + str(club_index)
        revisedSheet[club_i] = 'Site'

        count_index = 6
        count_i = 'B' + str(count_index)
        revisedSheet[count_i] = 'Membership Count'

        perc_index = 6
        perc_i = 'C' + str(perc_index)
        revisedSheet[perc_i] = 'Membership Percentage'

        for x in membership_count:
            for i in range(len(x)):
                if i == 0:
                    club_index += 1
                    club_i = 'A' + str(club_index)
                    revisedSheet[club_i] = x[i]
                elif i == 1:
                    count_index += 1
                    count_i = 'B' + str(count_index)
                    revisedSheet[count_i] = x[i]
                    perc_index += 1
                    perc_i = 'C' + str(perc_index)
                    revisedSheet[perc_i] = x[i]/membership_total

        #==================================================================
        # Summarizing Attributes
        #==================================================================
        att_continuetill = input("Is there another attribute to summarize? (yes/no) ")
        while att_continuetill == 'yes':

            att_col = input("Attribute Column (Letter): ")
            att_row = 2

            #==================================================================
            # Summarize 1 Attribute
            #==================================================================
            att, dupAtt = att_list_2(sheet, list_length, str(att_col), int(att_row))
            #totals by primary att
            att_countbyclub = countByClub(bgch_clubhouse_list, att, dupAtt)
            #totals
            att_count = attribute_count(att, dupAtt)
            att_percentage = attribute_percentage(att_count)

            #==================================================================
            # Print Attribute Results to New Excel Sheet
            #==================================================================
            #Attribute Title
            club_index += 2
            att_index = club_index + 1
            club_i = 'A' + str(club_index)
            revisedSheet[club_i] = sheet[att_col + str(1)].value

            #==================================================================
            # Hard coded and Calculated by Primary Attribute (Site)
            #==================================================================
            club_index += 1
            club_i = 'A' + str(club_index)
            revisedSheet[club_i] = 'Site'

            for x in bgch_clubhouse_list:
                club_index += 1
                club_i = 'A' + str(club_index)
                revisedSheet[club_i] = x

            #Print Total(#)
            counter = 1
            att_revised_row = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ']
            att_i = att_revised_row[counter] + str(att_index)

            club_index += 1
            club_i = 'A' + str(club_index)
            revisedSheet[club_i] = "Total (#)"
            for i in range(len(att_count)):
                att_i = att_revised_row[counter] + str(club_index)
                revisedSheet[att_i] = att_count[i][1]
                counter += 1

            #Print Total(%)
            counter = 1
            att_revised_row = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ']
            att_i = att_revised_row[counter] + str(att_index)

            club_index += 1
            club_i = 'A' + str(club_index)
            revisedSheet[club_i] = "Total (%)"
            for i in range(len(att_percentage)):
                att_i = att_revised_row[counter] + str(club_index)
                revisedSheet[att_i] = att_percentage[i][1]
                counter += 1

            #Print Attribute Titles
            counter = 1
            att_revised_row = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ']
            att_i = att_revised_row[counter] + str(att_index)

            for x in att:
                att_i = att_revised_row[counter] + str(att_index)
                revisedSheet[att_i] = x
                counter += 1

            #Print Attribute Summary Data
            att_revised_row = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ']

            att_printer_counter = 0
            for x in range(len(bgch_clubhouse_list)):
                counter = 1
                att_index += 1
                att_i = att_revised_row[counter] + str(att_index)
                for y in range(len(att)):
                    revisedSheet[att_i] = att_countbyclub[att_printer_counter][2]
                    #print(att_countbyclub[att_printer_counter][2])
                    att_printer_counter += 1
                    counter += 1
                    att_i = att_revised_row[counter] + str(att_index)

            att_continuetill = input("Is there another attribute to summarize? (yes/no) ")

        continuetill = input("Is there another sheet? (yes/no) ")

    #Done, Save Revised Workbook
    rwb.save(filename = dest_filename)

if __name__ == "__main__":
    main()


# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from profile_chrome import agents_unittest
from profile_chrome import ddms_tracing_agent

class DdmsAgentTest(agents_unittest.BaseAgentTest):
  def testTracing(self):
    agent = ddms_tracing_agent.DdmsAgent(self.device, self.package_info)

    try:
      agent.StartAgentTracing(None, None)
    finally:
      agent.StopAgentTracing()

    result = agent.GetResults()
    self.assertTrue(result.raw_data.startswith('*version'))


import xml.etree.ElementTree as ET

class xmlOperator:
    def __init__(self,xmlPath):
        self.xmlPath=xmlPath
        self.tree = ET.parse(self.xmlPath)
        self.root = self.tree.getroot()

    # 获得指定xml文件的制定内容
    def getDataByXml(self,targetAddress):
        targetData = {}

        for fatherNode in self.root.findall('agent'):
            if fatherNode.get('address') == targetAddress:
                for i in fatherNode:
                    for sonNode in i:
                        # 获得指定的信息
                        targetData.update({i.attrib.get('name'): sonNode.text})

        return targetData

    # 更改指定xml文件的制定内容
    def editDataByXml(self,targetAddress,targetPlugin):

        for fatherNode in self.root.findall('agent'):
            if fatherNode.get('address') == targetAddress:
                for i in fatherNode:
                    for sonNode in i:
                        if i.attrib.get('name') in targetPlugin:
                            # 获得指定的信息
                            sonNode.text='NO'

        self.tree.write(self.xmlPath)

    # 查找一下是否需要新加地址节点
    def addNewAgent(self, AgentAddress,plugins):
        isFind = 1
        for fatherNode in self.root.findall("agent"):
            # 查看是否能找到这个节点
            if fatherNode.get('address') == AgentAddress:
                isFind = 2

        if isFind == 1:
            # 创建新节点并添加为root的子节点
            newEle = ET.Element("agent")
            newEle.attrib = {"address": str(AgentAddress)}

            for i in plugins:
                newElesSonPlugin = ET.Element("plugin")
                newElesSonPlugin.set('name', i)

                newElesSonUpdate = ET.Element("update")
                newElesSonUpdate.text='NO'
                newElesSonPlugin.append(newElesSonUpdate)
                newEle.append(newElesSonPlugin)

            self.root.append(newEle)
            # 写回原文件
            self.tree.write(self.xmlPath,"UTF-8")

    # 查找一下是否需要新加地址节点
    def addNewPlugin(self,newPluginName):

        # 遍历每个地址
        for fatherNode in self.root.findall("agent"):
            tFlag=False

            # 遍历每个插件
            for pluginNode in fatherNode.findall("plugin"):
                # 查找该地址中是否有该插件
                if pluginNode.get('name') == newPluginName:
                    tFlag = True
                    break

            # 没有找到该新的插件
            if tFlag==False:
                # 就往这个节点加这个新的插件
                newElesSonPlugin = ET.Element("plugin")
                newElesSonPlugin.set('name', newPluginName)
                newElesSonUpdate = ET.Element("update")
                newElesSonUpdate.text = 'NO'
                newElesSonPlugin.append(newElesSonUpdate)
                # 加到该agent端的所有插件之中
                fatherNode.append(newElesSonPlugin)

        # 写回原文件
        self.tree.write(self.xmlPath, "UTF-8")

    # 查找一下是否需要新加地址节点
    def deletePlugin(self, deletePluginName):

        # 遍历每个地址
        for fatherNode in self.root.findall("agent"):

            # 遍历每个插件
            for pluginNode in fatherNode.findall("plugin"):
                # 查找该地址中是否有该插件
                if pluginNode.get('name') == deletePluginName:
                    fatherNode.remove(pluginNode)

        # 写回原文件
        self.tree.write(self.xmlPath, "UTF-8")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/30 11:45
# @Author : virus
# @File : 1-5.py
# @Desp : python

# 打折

price = 95

n = int(input("请输入购买衣服件数"))
pay_cash = n * 95

if n * 95 >= 300:
    print("需要支付的金额%.2f"%float(pay_cash*0.85))
else:
    print("需要支付的金额%.2f"%pay_cash)


"""
0-1ナップザック
wi...i個目の重さ
vi...i個目の価値

2次元

dp[i][j]...i個目までの宝で重さjの時の価値の最大
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - wi] + vi)  (wi <= j)
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])                          (wi >  j)

1次元

dp[j]...重さjの時の価値の最大
dp[j] = max(dp[j], dp[j - wi] + vi)  (wi <= j <= w)

wi <= j <= wについて更新(j < wiについては変化が無いため更新不要)
前から更新すると更新した結果を使って更新してしまうため後ろから更新
"""

INF = 10 ** 20

def main():
  case = 0

  while True:
    w = int(input())
    if not w:
      break

    case += 1

    n = int(input())

    dp = [0 for _ in range(w + 1)]

    for i in range(1, n + 1):
      vi, wi = map(int, input().split(","))
      for j in range(w, wi - 1, -1):
        dp[j] = max(dp[j], dp[j - wi] + vi)

    print("Case " + str(case) + ":")
    print(dp[w])
    print(dp.index(dp[w]))
main()


import os
import sys
import argparse
import numpy as np
import pandas as pd
from sklearn import metrics
import matplotlib.pyplot as plt

###########################################
# Command line interface
this_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
default_out = os.path.join(this_dir, "results_test")
default_res = os.path.join(this_dir, "test_results_sigmoid.csv")

parser = argparse.ArgumentParser(description=r"This script will analyse a model's performance returning multiple metrics for binary classification")
parser.add_argument('--output',
        type = str,
        help = f'Folder where the analysis files will be saved. Default: Same folder as the results file.'
        'The output folder is where all the figures and analysis files will be saved on disk',
        default = default_out
        )
parser.add_argument('--results',
        type = str,
        help = f'Path for results file. Default: {default_res}. '
        'The results file is a csv created by one of the test scripts',
        default = default_res
        )
parser.add_argument('--threshold',
        type=float,
        help='Threshold for the percentage to be classified as promoter. Default: 0.5',
        default=0.5)
args = parser.parse_args()
if(args.output == ''):
    args.output = os.path.dirname(args.results)
###########################################
if not os.path.exists(args.output):
    os.makedirs(args.output)

def plot_confusion_matrix(y_true, y_pred, classes,
                          normalize=False,
                          title=None,
                          cmap=plt.cm.Blues):
    if not title:
        if normalize:
            title = 'Normalized confusion matrix'
        else:
            title = 'Confusion matrix, without normalization'

    cm = metrics.confusion_matrix(y_true, y_pred)
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')
    print(cm)

    fig, ax = plt.subplots()
    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.figure.colorbar(im, ax=ax)
    ax.set(xticks=np.arange(cm.shape[1]),
           yticks=np.arange(cm.shape[0]),
           xticklabels=classes, yticklabels=classes,
           title=title,
           ylabel='True label',
           xlabel='Predicted label')

    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            ax.text(j, i, format(cm[i, j], fmt),
                    ha="center", va="center",
                    color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()
    plt.savefig(os.path.join(args.output, '%s.png' % title))
    fig.clf()
    ax.cla()
    plt.close()

def softmax(x, r=1):
    temp = np.exp(x)
    return (temp / np.sum(temp))[r]

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def threshold(x):
    if x < args.threshold:
        return 0
    else:
        return 1

def threshold_flipped(x):
    if x < args.threshold:
        return 1
    else:
        return 0

def sensitivity(fn, tp):
    return tp/(tp + fn)

def specificity(tn, fp):
    return tn/(tn + fp)

def ppv(fp, tp):
    return tp/(tp + fp)

#TODO: Add the distribution curve analysis for optimal threshold
# For sigmoid now
def create_histogram(data, colors, n_bins, title, zoom=slice(None), log=False):
    plt.figure()
    n, bins, patches = plt.hist(x=data,bins=n_bins, color=colors,
                                alpha=0.7, rwidth=0.85, log=log)
    plt.grid(axis='y', alpha=0.75)
    plt.xlabel('Value')
    plt.ylabel('Frequency')
    plt.title(title)
    if(isinstance(zoom, int)):
        extra = '-zoomed_%d' % zoom
    else:
        extra = '-zoomed'
    plt.ylim(top=np.max(n[zoom]))
    plt.savefig(os.path.join(args.output, "%s%s.png" % (title, extra)))
    plt.cla()
    plt.clf()
    plt.close()

print("Reading results")
df = pd.read_csv(args.results)
is_softmax = len(df.columns) == 5
if(is_softmax):
    truths_pos = df[df.label == 1][['prediction_0', 'prediction_1']].to_numpy()
    scores_pos = np.apply_along_axis(softmax, 1, truths_pos, slice(None))
    truths_neg = df[df.label == 0][['prediction_0', 'prediction_1']].to_numpy()
    scores_neg = np.apply_along_axis(softmax, 1, truths_neg, slice(None))
    predictions = df[['prediction_0', 'prediction_1']].to_numpy()
    scores = np.argmax(np.apply_along_axis(softmax, 1, predictions, slice(None)), axis=1)
else:
    truths_pos = df[df.label == 1][['prediction']].to_numpy()
    scores_pos = np.apply_along_axis(sigmoid, 1, truths_pos)
    truths_neg = df[df.label == 0][['prediction']].to_numpy()
    scores_neg = np.apply_along_axis(sigmoid, 1, truths_neg)
    predictions = df['prediction'].to_numpy()
    scores = np.vectorize(sigmoid)(predictions)
    truths_pos = truths_pos.squeeze()
    scores_pos = scores_pos.squeeze()
    truths_neg = truths_neg.squeeze()
    scores_neg = scores_neg.squeeze()
labels = df['label'].to_numpy()
print("Finished reading results")

print("Creating histograms")
n_bins=50
if(is_softmax):
    for i in range(2):
        create_histogram(predictions, ['#0504aa','#7cfc00'], n_bins, 'Prediction logits', zoom=i)
        for j in range(2):
            create_histogram(truths_pos, ['#0504aa','#7cfc00'], n_bins, 'Promoters %sscores' % ('log ' if j else ''), zoom=i, log=j)
            create_histogram(truths_neg, ['#0504aa','#7cfc00'], n_bins, 'Non-promoters %sscores' % ('log ' if j else ''), zoom=i, log=j)
            create_histogram((truths_pos[:,0], truths_pos[:,1], truths_neg[:,0], truths_neg[:,1]), ['darkblue','blue','green','lightgreen'], n_bins, 'Scores%s' % (' log scale' if j else ''), zoom=i*2, log=j)
            create_histogram((truths_pos[:,0], truths_pos[:,1], truths_neg[:,0], truths_neg[:,1]), ['darkblue','blue','green','lightgreen'], n_bins, 'Scores%s' % (' log scale' if j else ''), zoom=i*2+1, log=j)
            create_histogram((scores_pos[:,1], scores_neg[:,0]), ['#0504aa','#7cfc00'], n_bins, 'Truth %sscores promoters' % ('log ' if j else ''), zoom=i, log=j)
            create_histogram((truths_pos[:,1], truths_neg[:,0]), ['#0504aa','#7cfc00'], n_bins, 'Truth %slogits promoters' % ('log ' if j else ''), zoom=i, log=j)
            create_histogram((scores_pos[:,0], scores_neg[:,1]), ['#0504aa','#7cfc00'], n_bins, 'Truth %sscores non-promoters' % ('log ' if j else ''), zoom=i, log=j)
            create_histogram((truths_pos[:,0], truths_neg[:,1]), ['#0504aa','#7cfc00'], n_bins, 'Truth %slogits non-promoters' % ('log ' if j else ''), zoom=i, log=j)
else:
    create_histogram(predictions, ['#0504aa'], n_bins, 'Prediction logits', zoom=slice(None))
    for i in range(2):
        create_histogram(truths_pos, ['#0504aa'], n_bins, 'Promoters %sscores' % ('log ' if i else ''), zoom=slice(None), log=i)
        create_histogram(truths_neg, ['#7cfc00'], n_bins, 'Non-promoters %sscores' % ('log ' if i else ''), zoom=slice(None), log=i)
        for j in range(2):
            create_histogram((scores_pos, scores_neg), ['#0504aa','#7cfc00'], n_bins, 'Truth %sscores promoters' % ('log ' if i else ''), zoom=j, log=i)
            create_histogram((truths_pos, truths_neg), ['#0504aa','#7cfc00'], n_bins, 'Truth %slogits promoters' % ('log ' if i else ''), zoom=j, log=i)
print("Histograms done")

print("Calculating metrics")
fpr, tpr, roc_thresholds = metrics.roc_curve(labels, scores)
roc_auc = metrics.auc(fpr, tpr)
precision, recall, pr_thresholds = metrics.precision_recall_curve(labels, scores)
avg_precision = metrics.average_precision_score(labels, scores)
print("Metrics calculated")

print("Creating report")
def make_report(scores, threshold_func, title):
    thresholded_scores = np.vectorize(threshold_func)(scores)
    report = metrics.classification_report(labels, thresholded_scores, labels=[0, 1], target_names=['non-promoter', 'promoter'], digits=3)
    acc_score = metrics.accuracy_score(labels, thresholded_scores)
    balanced_acc_score = metrics.balanced_accuracy_score(labels, thresholded_scores)
    f1_score = metrics.f1_score(labels, thresholded_scores)
    mcc_score = metrics.matthews_corrcoef(labels, thresholded_scores)
    precision_score = metrics.precision_score(labels, thresholded_scores)
    recall_score = metrics.recall_score(labels, thresholded_scores)
    fbeta_score = metrics.fbeta_score(labels, thresholded_scores, beta=1.0)
    jaccard_score = metrics.jaccard_score(labels, thresholded_scores)
    tn, fp, fn, tp = metrics.confusion_matrix(labels, thresholded_scores).ravel()
    sn_score = sensitivity(fn, tp)
    sp_score = specificity(tn, fp)
    ppv_score = ppv(fp, tp)

    txt_string = 'Metrics report for trained model (%s) .\nThreshold set to %.2f\n' % (args.results, args.threshold)+\
                report + '\nAccuracy score: %0.3f' % acc_score +\
                '\nBalanced Accuracy score: %0.3f' % balanced_acc_score +\
                '\nF1 score: %0.3f' % f1_score +\
                '\nMatthews Coefficient Correlation: %0.3f' % mcc_score +\
                '\nPrecision score: %0.3f' % precision_score +\
                '\nRecall score: %0.3f' % recall_score +\
                '\nF-beta score: %0.3f' % fbeta_score +\
                '\nJaccard Similarity score: %0.3f' % jaccard_score +\
                '\nSensitivity score: %0.3f' % sn_score +\
                '\nSpecificity score: %0.3f' % sp_score +\
                '\nPPV score: %0.3f' % ppv_score

    with open(os.path.join(args.output, '%s-report.txt' % title), 'w') as text_file:
        text_file.write(txt_string)

    np.set_printoptions(precision=3)
    # Plot normalized confusion matrix
    plot_confusion_matrix(labels, thresholded_scores, classes=['non-promoter', 'promoter'],
                          normalize=True, title='Confusion Matrix-%s' % title)

if(is_softmax):
    make_report(scores, threshold, 'softmax')
else:
    make_report(scores, threshold, 'sigmoid')

#args.threshold = -2.9 #Change to desired threshold
#make_report(predictions[:, 0], threshold_flipped, 'logits')
print("Report created")

print("Creating additional plots")
def f_beta_by_threshold(y_true, y_pred_pos, thres_nr=100):
    thresholds = [i / thres_nr for i in range(1, thres_nr, 1)]

    f_scores = []
    for thres in thresholds:
        y_pred_class = y_pred_pos > thres
        score = metrics.matthews_corrcoef(y_true, y_pred_class)
        f_scores.append(score)

    return thresholds, f_scores

betas = [0.1, 0.25, 0.5, 1.0, 1.25, 1.5, 2, 5, 10]

plt.figure()
fig, ax = plt.subplots()
thresholds, betascores = f_beta_by_threshold(labels, scores)
ax.plot(thresholds, betascores, label='β=1')
ax.set_title('mcc by threshold')
ax.set_xlabel('threshold')
ax.set_ylabel('mcc')
ax.legend(loc='right', bbox_to_anchor=(1.3,0.7))
plt.savefig(os.path.join(args.output, 'mcc_by_thresholds.png'))
fig.clf()
ax.cla()
plt.close()

# PLOT AUC
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
         lw=lw, label='ROC curve (area = %0.3f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Area under the ROC curve')
plt.legend(loc="lower right")
plt.savefig(os.path.join(args.output, 'area_under_curve.png'))
plt.cla()
plt.clf()
plt.close()

# PLOT PRCURVE
plt.figure()
lw = 2
plt.plot(recall[:-1], precision[:-1], color='darkorange',
         lw=lw, label='PR curve (AP = %0.3f)' % avg_precision)
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall curve')
plt.legend(loc="upper right")
plt.savefig(os.path.join(args.output, 'precision_recall_curve.png'))
plt.cla()
plt.clf()
plt.close()

# PLOT PR VS THRESHOLDS
plt.figure()
plt.plot(pr_thresholds, precision[:-1], 'b--', label='Precision')
plt.plot(pr_thresholds, recall[:-1], 'g--', label='Recall')
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('Threshold')
plt.legend(loc='upper right')
plt.savefig(os.path.join(args.output, 'precision_recall_vs_thresholds.png'))
plt.cla()
plt.clf()
plt.close()
print("Additional plots created")
print("Analysis done")


from vpython import *
import time
import random

label(pos=vector(0,8,0),text='Density Flow of Vehicles',color=color.white,height=20,box=False)
label(pos=vector(12,-5,0),text="Green : Free way",depth=0.3,color=color.white)

def road_simulation():
	i = -17
	while i <= 17:
		rate(10)
		curve(pos=[(-17,1.5,0),(0,1.5,0),(i,1.5,0)],radius=0.05)
		curve(pos=[(-17,-1.5,0),(0,-1.5,0),(i,-1.5,0)],radius=0.05)
		i += 1
		time.sleep(0.01)

road_simulation()

red = box(pos=vector(0,0,0),color=color.green,width=0.2,length=30,height=1.2)
vehicle = sphere(pos=vector(-16,0,0),radius=0.3,color=color.magenta,visible=True)

def vehicle_movement():
	i = -16
	while i <= 16:
		rate(10)
		vehicle.pos.x = i
		i += 1
		time.sleep(0.05)

for i in range(80): # repeat for _ times
	vehicle_movement()


import dtree_build

def average_prediction(leaf_labels):
#    total = 0
#   sum = 0
#    for value in leaf_labels:
#        total += 1
#        sum += float(value)
#    return round(float(sum/total),2)
    total = 0
    result = 0
    for label, count in leaf_labels.items():
        total += count
        result += count*float(label)
    return round(float(result/total), 2)

def average(rows):
#    results = []
#    for row in rows:
#        # The result is the last column
#        r = row[len(row) - 1]
#        results += [r]
#    return results
    results = {}
    for row in rows:
        # The result is the last column
        r = row[len(row) - 1]
        if r not in results:
            results[r] = 0
        results[r] += 1
    return results

def buildtree(rows, scoref=dtree_build.variance,
              min_gain=0, min_samples=0):
    if len(rows) == 0:
        return dtree_build.decisionnode()
    current_score = scoref(rows)

    # Set up accumulator variables to track the best criteria
    best_gain = 0.0
    best_criteria = None
    best_sets = None

    column_count = len(rows[0]) - 1
    for col in range(0, column_count):
        # Generate the list of different values in
        # this column
        column_values = {}
        for row in rows:
            column_values[row[col]] = 1
        # Now try dividing the rows up for each value
        # in this column
        for value in column_values.keys():
            (set1, set2) = dtree_build.divideset(rows, col, value)

            # Information gain
            p = float(len(set1)) / len(rows)
            gain = current_score - p * scoref(set1) - (1 - p) * scoref(set2)
            if gain > best_gain and len(set1) > min_samples and len(set2) > min_samples and gain > min_gain:
                best_gain = gain
                best_criteria = (col, value)
                best_sets = (set1, set2)

    # Create the sub branches
    if best_gain > 0:
        trueBranch = buildtree(best_sets[0], scoref, min_gain, min_samples)
        falseBranch = buildtree(best_sets[1], scoref, min_gain, min_samples)
        return dtree_build.decisionnode(col=best_criteria[0], value=best_criteria[1],
                            tb=trueBranch, fb=falseBranch)
    else:
        return dtree_build.decisionnode(results=average(rows))

def printtree(tree, current_branch, attributes=None,  indent='', leaff=average_prediction):
    # Is this a leaf node?
    if tree.results != None:
        print(indent + current_branch + str(leaff(tree.results)))
    else:
        # Print the split question
        split_col = str(tree.col)
        if attributes is not None:
            split_col = attributes[tree.col]
        split_val = str(tree.value)
        if type(tree.value) == int or type(tree.value) == float:
            split_val = ">=" + str(tree.value)
        print(indent + current_branch + split_col + ': ' + split_val + '? ')

        # Print the branches
        indent = indent + '  '
        printtree(tree.tb, 'T->', attributes, indent)
        printtree(tree.fb, 'F->', attributes, indent)


# -*- coding: utf-8 -*-
#
# Api.py
#
# (PHASE 1)
#
# This file contains all the code needed for the REST API that wraps the project.
# It instantiates the Mission Creator (top level file for the program) and can be
# communicated with via the command line. See the final report Appendix for full
# running instructions.
#
# Initial Creation Date: 11/03/2018
#
# Written by Jordan Jones and Nolan Heim
#

from flask import Flask, url_for, request, Response
import json
import uuid
import os
from Mission_Creator_REST import *

api = Flask(__name__)

#Base
@api.route('/')
def api_root():
    return "Welcome to the Imaging Opportunity Generator"

#Post
@api.route('/visibility/search', methods = ['POST'])
def api_search():

    request_uuid = uuid.uuid4()
    status = 500

    opportunities = MC.generate_imaging_opportunities(request.json, request_uuid)

    if opportunities == "ERR":
        response = "ERROR - Wrong/missing input object attribute(s)"
        resp = Response(response, status=400, mimetype='application/json')
        return resp

    output_json = {
        "id":str(request_uuid),
        "Opportunities":opportunities
    }

    #saves output for use by GET function
    with open(results_path + str(request_uuid) + ".json", "w") as save_output:
        save_output.write(json.dumps(output_json))
        status = 200

    response = json.dumps(output_json)

    #creates the Response object
    resp = Response(response, status=status, mimetype='application/json')

    return resp

#Get
@api.route('/visibility/<articleid>', methods = ['GET'])
def api_get_results(articleid):

    #no such results id exists, return code 400
    if not (os.path.isfile(results_path+str(articleid)+".json")):
        response = "ERROR - No results for specified ID"
        #Create the response object
        resp = Response(response, status=400)
        return resp

    else: #Results for the given ID do exist
        with open(results_path+str(articleid)+".json", "r") as read_file:
            response = read_file.readlines()

        #Creates the Response object
        resp = Response(response, status=200, mimetype='application/json')
        return resp

    response = "ERROR - Backend error"

    #Creates the Response object
    resp = Response(response, status=500)
    return resp

# Runs the API. Need a separate command window to communicate with it.
if __name__ == '__main__':
    datapath = "../../Data/"
    results_path = "../../Saved Results/"
    parsed_datapath = "../../Parsed Data/"
    MC = Mission_Creator_REST(parsed_datapath, results_path)
    api.run()


from openravepy import *
import time
import numpy

if __name__ == "__main__":

    try:

        env = Environment()
        env.SetViewer('qtcoin')
        env.Load('jaemiHubo.robot.xml')
        time.sleep(1)

        physics = RaveCreatePhysicsEngine(env,'ode')
        physics.SetGravity([0,0,0])
        env.SetPhysicsEngine(physics)

        robot = env.GetRobots()[0]

        with env:
            robot = env.GetRobots()[0]
            robot.GetLinks()[0].SetStatic(True)
            robot.SetController(RaveCreateController(env,'odevelocity'),range(robot.GetDOF()),0)
            env.StopSimulation()
            env.StartSimulation(timestep=0.001 )

        w=0.5*2.0*numpy.pi
        T=1.0/w
        steps=25
        A=.1
        runtime=10

        for i in range(runtime*steps):
            t=float(i)/steps
            #print t
            velocities = numpy.zeros(robot.GetDOF())+numpy.sin(w*t)*A
            #print velocities
            robot.GetController().SendCommand('setvelocity '+' '.join(str(f) for f in velocities))
            time.sleep(1.0/float(steps))

        velocities = numpy.zeros(robot.GetDOF())
        robot.GetController().SendCommand('setvelocity '+' '.join(str(f) for f in velocities))
        raw_input('')

    finally:
        env.Destroy()


# coding: utf8

import jinja2
import flask

blueprint = flask.Blueprint('filters', __name__)

# using the decorator
@jinja2.contextfilter
@blueprint.app_template_filter()
def cut_host(context, value):
    value = value.strip()
    if value.startswith("http://"):
        return value[7:]
    return value

#@jinja2.contextfilter
#def filter2(context, value):
    #print context, value
    #return value
#blueprint.add_app_template_filter(filter2)


import FWCore.ParameterSet.Config as cms

corrJetsProducer = cms.EDProducer ( "CorrJetsProducer",
                                    jets    = cms.InputTag( "cleanJets"                ),
                                    vertex  = cms.InputTag( "goodOfflinePrimaryVertex" ),
                                    rho     = cms.InputTag( "fixedGridRhoFastjetAll"   ),
                                    payload = cms.string  ( "AK8PFchs"                 ),
                                    isData  = cms.bool    (  False                     ))

hadronicV = cms.EDFilter( "CandViewSelector",
                          src = cms.InputTag("corrJetsProducer:corrJets"),
                          cut = cms.string('pt > 200. & userFloat("ak8PFJetsCHSCorrPrunedMass") > 5.'),
                          filter = cms.bool(True) )

hadronicVSequence = cms.Sequence( corrJetsProducer + hadronicV )


from direct.directbase.DirectStart import *
from direct.actor.Actor import Actor
from pandac.PandaModules import *
from direct.task import Task
import math
from math import pi, sin, cos
from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import Point3
from pandac.PandaModules import *
from panda3d.core import CollisionTraverser,CollisionNode
from panda3d.core import CollisionHandlerQueue,CollisionRay
from panda3d.core import Filename,AmbientLight,DirectionalLight
from panda3d.core import PandaNode,NodePath,Camera,TextNode
from panda3d.core import Vec3,Vec4,BitMask32
from direct.showbase.Transitions import *
from direct.gui.DirectGui import *
from direct.actor.Actor import Actor
from direct.showbase.DirectObject import DirectObject
from direct.filter.CommonFilters import *
from panda3d.ai import *
import sys

terrain = loader.loadModel('phase_4/models/neighborhoods/toontown_central_full.bam')
terrain.reparentTo(render)

Noah = Actor({'Torso':'phase_3/models/char/tt_a_chr_dgm_shorts_torso_1000.bam', \
             'Legs':'phase_3/models/char/tt_a_chr_dgm_shorts_legs_1000.bam'}, \
             {'Torso':{'Idle': 'phase_3/models/char/tt_a_chr_dgm_shorts_torso_1000.bam', \
             'TorsoAnim':'phase_3/models/char/tt_a_chr_dgm_shorts_torso_neutral.bam'}, \
             'Legs':{'Idle':'phase_3/models/char/tt_a_chr_dgm_shorts_legs_1000.bam',
             'LegsAnim':'phase_3/models/char/tt_a_chr_dgm_shorts_legs_neutral.bam'}})

Noah.attach('Torso', 'Legs', 'joint_hips')

#Animations
Noah.loop('TorsoAnim')
Noah.loop('LegsAnim')

#Pos, Hpr, Scale, ReparentTo
Noah.setPos(0, 0, 0)
Noah.setHpr(0, 0, 0)
Noah.setScale(1.1)
Noah.reparentTo(render)

#Head
Head = Actor('phase_3/models/char/tt_a_chr_dgm_skirt_head_1000.bam',
            {'anim':'phase_3/models/char/tt_a_chr_dgm_skirt_head_neutral.bam'})

Head.setColor(1, 1, 1)
Head.loop('anim')
Head.find('**/ears').setColor(0)
Head.find('**/muzzle').setColor(0.87, 0.65, 0.47)
Top_Head = Head.find('**/head')
Bot_Head = Head.find('**/head-front')

Neck = Noah.find('**/def_head')
Head.reparentTo(Neck)

#******************************Clothes******************************

#Gloves
Gloves = Noah.find('**/hands')
Gloves.setColor(0.99, 0.99, 0.99)

#Sleeves
Sleeves = loader.loadTexture('phase_4/maps/4thJulySleeve2.jpg')
Noah.find('**/sleeves').setTexture(Sleeves, 1)

#Shirts
Shirt = loader.loadTexture('phase_4/maps/4thJulyShirt2.jpg')
Noah.find('**/torso-top').setTexture(Shirt, 1)

#Shorts
Shorts = loader.loadTexture('phase_4/maps/tt_t_chr_avt_shorts_vampire.jpg')
Noah.find('**/torso-bot').setTexture(Shorts, 1)

#Shoes/Boots
Shoes = loader.loadTexture('phase_4/maps/tt_t_chr_avt_acc_sho_converseStyleBlack.jpg')
Noah.find('**/shoes').hide()
Noah.find('**/boots_long').hide()
Noah.find('**/boots_short').setTexture(Shoes, 1)
Noah.find('**/feet').hide()

#backpack
backpack = loader.loadModel('phase_4/models/accessories/tt_m_chr_avt_acc_pac_woodenSword.bam')
backpack.reparentTo(Noah.find('**/def_joint_attachFlower'))
backpack.setHpr(175.00, 20.56, 0)
backpack.setPos(0.22, -1.14, -0.23)
backpack.setScale(0.35)

#Hats
Hat = loader.loadModel('phase_4/models/accessories/tt_m_chr_avt_acc_hat_topHat.bam')
Hat.reparentTo(Head.find('**/head'))
Hat.setZ(0.30)
Hat.setHpr(0.00, -330.00, 0.00)
Hat.setPos(0.00, 0.00, 0.55)
Hat.setScale(0.3)

#Colors
Top_Head.setColor(0.75, 0.23, 0.23, 1.0)
Bot_Head.setColor(0.75, 0.23, 0.23, 1.0)
Noah.find('**/neck').setColor(0.75, 0.23, 0.23, 1.0)
Noah.find('**/arms').setColor(0.75, 0.23, 0.23, 1.0)
Noah.find('**/legs').setColor(0.75, 0.23, 0.23, 1.0)
Noah.find('**/feet').setColor(0.75, 0.23, 0.23, 1.0)
Hat.setColor(0.99, 0.99, 0.99)
backpack.setColor(0.99, 0.99, 0.99)
Noah.setPos(-.50, 54.18, 0)
Noah.setH(56.31)

Mewtastic = Actor({'Torso':'phase_3/models/char/tt_a_chr_dgm_shorts_torso_1000.bam', \
             'Legs':'phase_3/models/char/tt_a_chr_dgm_shorts_legs_1000.bam'}, \
             {'Torso':{'Idle': 'phase_3/models/char/tt_a_chr_dgm_shorts_torso_1000.bam', \
             'TorsoAnim':'phase_3/models/char/tt_a_chr_dgm_shorts_torso_neutral.bam'}, \
             'Legs':{'Idle':'phase_3/models/char/tt_a_chr_dgm_shorts_legs_1000.bam',
             'LegsAnim':'phase_3/models/char/tt_a_chr_dgm_shorts_legs_neutral.bam'}})

Mewtastic.attach('Torso', 'Legs', 'joint_hips')

#Animations
Mewtastic.loop('TorsoAnim')
Mewtastic.loop('LegsAnim')

#Pos, Hpr, Scale, ReparentTo
Mewtastic.setPos(0, 0, 0)
Mewtastic.setHpr(0, 0, 0)
Mewtastic.setScale(0.90)
Mewtastic.reparentTo(render)

#Head
Head = loader.loadModel('phase_3/models/char/cat-heads-1000.bam')
Head.find('**/muzzle-short-surprise').hide()
Head.find('**/muzzle-short-sad').hide()
Head.find('**/muzzle-short-smile').hide()
Head.find('**/muzzle-short-angry').hide()
Head.find('**/muzzle-short-laugh').hide()
Head.find('**/muzzle-long-surprise').hide()
Head.find('**/muzzle-long-sad').hide()
Head.find('**/muzzle-long-smile').hide()
Head.find('**/muzzle-long-angry').hide()
Head.find('**/muzzle-long-laugh').hide()
Head.find('**/muzzle-long-neutral').hide()
Head.find('**/head-long').hide()
Head.find('**/head-front-long').hide()
Head.find('**/eyes-long').hide()
Head.find('**/joint_pupilL_long').hide()
Head.find('**/joint_pupilR_long').hide()
Head.find('**/ears-long').hide()

Neck = Mewtastic.find('**/def_head')
Head.reparentTo(Neck)

#******************************Clothes******************************

#Gloves
Gloves = Mewtastic.find('**/hands')
Gloves.setColor(0.99, 0.99, 0.99)

#Sleeves
Sleeves = loader.loadTexture('phase_4/maps/PJSleeveRed.jpg')
Mewtastic.find('**/sleeves').setTexture(Sleeves, 1)

#Shirts
Shirt = loader.loadTexture('phase_4/maps/PJRedHorn2.jpg')
Mewtastic.find('**/torso-top').setTexture(Shirt, 1)

#Shorts
Shorts = loader.loadTexture('phase_4/maps/Red_shorts_1.jpg')
Mewtastic.find('**/torso-bot').setTexture(Shorts, 1)

#Shoes/Boots
Shoes = loader.loadTexture('phase_4/maps/tt_t_chr_avt_acc_sho_converseStyleRed.jpg')
Mewtastic.find('**/shoes').hide()
Mewtastic.find('**/shoes').hide()
Mewtastic.find('**/boots_long').hide()
Mewtastic.find('**/boots_short').setTexture(Shoes, 1)
Mewtastic.find('**/feet').hide()

#Hats
Hat = loader.loadModel('phase_4/models/accessories/tt_m_chr_avt_acc_hat_firefighterHelmet.bam')
Hat.reparentTo(Head.find('**/head-short'))
Hat.setPos(0, 0.11, 0.15)
Hat.setHpr(180.00, 333.43, 0)
Hat.setScale(0.42)

#Colors
Head.find('**/head-short').setColor(0.80, 0.48, 0.29, 1.0)
Head.find('**/head-front-short').setColor(0.80, 0.48, 0.29, 1.0)
Head.find('**/ears-short').setColor(0.80, 0.48, 0.29, 1.0)
Mewtastic.find('**/neck').setColor(0.80, 0.48, 0.29, 1.0)
Mewtastic.find('**/arms').setColor(0.80, 0.48, 0.29, 1.0)
Mewtastic.find('**/legs').setColor(0.80, 0.48, 0.29, 1.0)
Mewtastic.find('**/feet').setColor(0.80, 0.48, 0.29, 1.0)
Hat.setColor(0.99, 0.99, 0.99)
Mewtastic.place()

DropplessDog = Actor({'Torso':'phase_3/models/char/tt_a_chr_dgm_shorts_torso_1000.bam', \
             'Legs':'phase_3/models/char/tt_a_chr_dgs_shorts_legs_1000.bam'}, \
             {'Torso':{'Idle': 'phase_3/models/char/tt_a_chr_dgm_shorts_torso_1000.bam', \
             'TorsoAnim':'phase_3/models/char/tt_a_chr_dgm_shorts_torso_neutral.bam'}, \
             'Legs':{'Idle':'phase_3/models/char/tt_a_chr_dgs_shorts_legs_1000.bam',
             'LegsAnim':'phase_3/models/char/tt_a_chr_dgs_shorts_legs_neutral.bam'}})

DropplessDog.attach('Torso', 'Legs', 'joint_hips')

#Animations
DropplessDog.loop('TorsoAnim')
DropplessDog.loop('LegsAnim')

#Pos, Hpr, Scale, ReparentTo
DropplessDog.setPos(0, 0, 0)
DropplessDog.setHpr(0, 0, 0)
DropplessDog.reparentTo(render)

#Head
Head = Actor('phase_3/models/char/tt_a_chr_dgs_shorts_head_1000.bam',
            {'anim':'phase_3/models/char/tt_a_chr_dgs_shorts_head_1000.bam'})

Head.setColor(1, 1, 1)
Head.loop('anim')
Head.find('**/ears').setColor(0)
Head.find('**/muzzle').setColor(0.87, 0.65, 0.47)
Top_Head = Head.find('**/head')
Bot_Head = Head.find('**/head-front')

Neck = DropplessDog.find('**/def_head')
Head.reparentTo(Neck)

#******************************Clothes******************************

#Gloves
Gloves = DropplessDog.find('**/hands')
Gloves.setColor(0.99, 0.99, 0.99)

#Sleeves
Sleeves = loader.loadTexture('phase_4/maps/PJSleeveRed.jpg')
DropplessDog.find('**/sleeves').setTexture(Sleeves, 1)

#Shirts
Shirt = loader.loadTexture('phase_4/maps/PJRedHorn2.jpg')
DropplessDog.find('**/torso-top').setTexture(Shirt, 1)

#Shorts
Shorts = loader.loadTexture('phase_4/maps/Red_shorts_1.jpg')
DropplessDog.find('**/torso-bot').setTexture(Shorts, 1)

#Shoes/Boots
Shoes = loader.loadTexture('phase_4/maps/tt_t_chr_avt_acc_sho_athleticBlack.jpg')
DropplessDog.find('**/shoes').setTexture(Shoes, 1)
DropplessDog.find('**/shoes').setScale(1.1)
DropplessDog.find('**/boots_long').hide()
DropplessDog.find('**/boots_short').hide()
DropplessDog.find('**/feet').hide()

#backpack
backpack = loader.loadModel('phase_4/models/accessories/tt_m_chr_avt_acc_pac_flunky.bam')
backpack.reparentTo(DropplessDog.find('**/def_joint_attachFlower'))
backpack.setHpr(175.00, 0, 0)
backpack.setPos(0.22, -1.00, -0.16)
backpack.setScale(0.35)

#Glasses
Glasses = loader.loadModel('phase_4/models/accessories/tt_m_chr_avt_acc_msk_squareRims.bam')
Glasses.reparentTo(Bot_Head)
Glasses.setZ(0.30)
Glasses.setHpr(180, 350.00, 0)
Glasses.setY(0.06)
Glasses.setScale(0.30)

#Hats
Hat = loader.loadModel('phase_4/models/accessories/tt_m_chr_avt_acc_hat_topHat.bam')
Hat.reparentTo(Head.find('**/head'))
Hat.setZ(0.30)
Hat.setHpr(0.00, -330.00, 0.00)
Hat.setPos(0.00, 0.00, 0.63)
Hat.setScale(0.35)

#Colors
Top_Head.setColor(0.992188, 0.480469, 0.167969, 1.0)
Bot_Head.setColor(0.992188, 0.480469, 0.167969, 1.0)
DropplessDog.find('**/neck').setColor(0.992188, 0.480469, 0.167969, 1.0)
DropplessDog.find('**/arms').setColor(0.992188, 0.480469, 0.167969, 1.0)
DropplessDog.find('**/legs').setColor(0.992188, 0.480469, 0.167969, 1.0)
DropplessDog.find('**/feet').setColor(0.992188, 0.480469, 0.167969, 1.0)
backpack.setColor(0.99, 0.99, 0.99)
Hat.setColor(0.99, 0.99, 0.99)
Glasses.setColor(0.99, 0.99, 0.99)
DropplessDog.place()

base.oobe()
run()


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/taurus/core/util/whichexecutable.py
# Compiled at: 2019-08-19 15:09:29
"""Find path of executable specified by filename"""
__all__ = [
 'whichfile']
__docformat__ = 'restructuredtext'
import os

def whichfile(filename, exts=None):
    r"""Find path of executable specified by filename.
    It Takes into consideration
    the PATHEXT variable (found in MS Windows systems) to try also executable
    names extended with executable extensions.

    Example::

      # on a debian machine with taurus installed in the default path:
      whichfile('taurus') --> '/usr/bin/taurus'

      # or, on a winXP machine:
      whichfile('command') --> 'C:\WINDOWS\system32\command.COM'

    :param filename: (str) executable name.
    :param exts: (list<str>) a list of valid executable extensions.
                 If None given, the PATHEXT environmental variable is used
                 if available.

    :return: (str) absolute path to the executable in the file system
    """
    path = os.getenv('PATH', '').split(os.path.pathsep)
    if exts is None:
        exts = os.getenv('PATHEXT', '').split(os.path.pathsep)
    if '' not in exts:
        exts.insert(0, '')
    for p in path:
        p = os.path.join(p, filename)
        for e in exts:
            pext = p + e
            if os.access(pext, os.X_OK):
                return pext

    return


from django.shortcuts import render
from django.http import HttpResponse

from .models import Suggestion_Model
from .forms import Suggestion_Form

# Create your views here.
def index(request):
    #return HttpResponse("Hello World")
    return render(request, 'index.html')

def suggestion_view(request):
    if request.method == 'POST':
        form = Suggestion_Form(request.POST)
        if form.is_valid():
            suggest = Suggestion_Model(
                suggestion=form.cleaned_data['suggestion']
            )
            suggest.save()
            form = Suggestion_Form()
    else:
        form = Suggestion_Form()
    suggestion_list = Suggestion_Model.objects.all()
    context={
        "suggestion_list":suggestion_list,
        "form":form
        }
    return render(request, 'suggestion.html',context)

def page(request, page_num):
    if page_num>=1:
        example_list=[]
        for i in range(page_num):
            example_list+=[i+1]

    else:
        example_list=None
    #return HttpResponse("Hello World")
    context={
        "page_template":page_num,
        "example_list":example_list
        }
    return render(request, 'page.html',context)


#!/usr/bin/env python

#interfaces with ROS and Python
import rospy
#Getting topics from ROS
from std_msgs.msg import Header, String
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import PoseStamped, PoseWithCovarianceStamped, PoseArray, Pose, Point, Quaternion, Vector3
from nav_msgs.msg import OccupancyGrid
#Broadcaster/reciever information
import tf
from tf import TransformListener
from tf import TransformBroadcaster
from tf.transformations import euler_from_quaternion, rotation_matrix, quaternion_from_matrix
#Helper imports
import math
import time
import cv2 #openCV used to make window for publishing data
import numpy as np
from numpy.random import random_sample
from matplotlib.pyplot import imshow

class TransformHelpers:
	""" Helper functions for making transformations of data from the RunMapping
	world to the script and back.  Will only be useful for us if we add an autonomy
	function to the robot. Credits to Paul Ruvulo """

	@staticmethod
	def convert_pose_to_xy_and_theta(pose):
		""" Convert pose (geometry_msgs.Pose) to a (x,y,yaw) tuple """
		orientation_tuple = (pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w)
		angles = euler_from_quaternion(orientation_tuple)
		return (pose.position.x, pose.position.y, angles[2])

class RunMapping:
	""" Creates a display for an Occupancy Field map
		Tracks the robot's position, can be expanded to track cluster positions
	"""

	def __init__(self):
		cv2.namedWindow("map")
		cv2.namedWindow("past_map")
		rospy.init_node("run_mapping")
		#create map properties, helps to make ratio calcs
		self.origin = [-10,-10]
		self.seq = 0
		self.resolution = 0.1
		self.n = 200

		self.pose = []
		self.cluster_pose = []

		self.dyn_obs=[]
		self.rapid_appear = set()
		self.counter=0

		#Giving initial hypotheses to the system
		self.p_occ = 0.5*np.ones((self.n, self.n)) #50-50 chance of being occupied
		self.odds_ratio_hit = 3.0 #this is arbitrary, can re-assign
		self.odds_ratio_miss = 0.3 #this is arbitrary, can reassign

		#calculates odds based upon hit to miss, equal odds to all grid squares
		self.odds_ratios = (self.p_occ)/(1-self.p_occ)*np.ones((self.n, self.n))
		#calculate initial past odds_ratio
		self.past_odds_ratios = (self.p_occ)/(1-self.p_occ)*np.ones((self.n, self.n))

		#write laser pubs and subs
		rospy.Subscriber("scan", LaserScan, self.scan_received, queue_size=1)
		self.pub = rospy.Publisher("map", OccupancyGrid)

		#note - in case robot autonomy is added back in
		self.tf_listener = TransformListener()

	def is_in_map(self, x, y):
		"Returns boolean of whether or not a point is within map boundaries"
		#return if x is less than the origin, or larger than the map, ditto for y
		return (x < self.origin[0] or x > self.origin[0] + self.n*self.resolution or y<self.origin[1] or y>self.origin[1] + self.n*self.resolution)

	def scan_received(self, msg):
		""" Returns an occupancy grid to publish data to map"""
		if len(msg.ranges) != 360:
			return

		#make a pose stamp that relates to the odom of the robot
		p = PoseStamped(header=Header(stamp=msg.header.stamp,frame_id="base_link"), pose=Pose())
		self.odom_pose = self.tf_listener.transformPose("odom", p)
		# convert the odom pose to the tuple (x,y,theta)
		self.odom_pose = TransformHelpers.convert_pose_to_xy_and_theta(self.odom_pose.pose)

		#local variable used to take odds samples for future comparisons
		time_past = 0

		for degree in range(360):
			if msg.ranges[degree] > 0.0 and msg.ranges[degree] < 5.0:
				#gets the position of the laser data points
				data_x = self.odom_pose[0] + msg.ranges[degree]*math.cos(degree*math.pi/180.0 + self.odom_pose[2])
				data_y = self.odom_pose[1] + msg.ranges[degree]*math.sin(degree*math.pi/180+self.odom_pose[2])

				#maps laser data to a pixel in the map
				datax_pixel = int((data_x - self.origin[0])/self.resolution)
				datay_pixel = int((data_y - self.origin[1])/self.resolution)

				#maps the robot to a position
				robot = (data_x - self.odom_pose[0], data_y - self.odom_pose[1])

				#finds how far away the point is from the robot
				magnitude = math.sqrt(robot[0]**2 + robot[1]**2)

				#converts magnitude and robot position to pixels in the map
				n_steps = max([1, int(math.ceil(magnitude/self.resolution))])
				robot_step = (robot[0]/(n_steps-1), robot[1]/(n_steps-1))
				marked = set()

				for pixel in range(n_steps):
					curr_x = self.odom_pose[0] + pixel*robot_step[0]
					curr_y = self.odom_pose[1] + pixel*robot_step[1]
					if (self.is_in_map(curr_x, curr_y)):
						#make sure its in the map
						break

					x_ind = int((curr_x - self.origin[0])/self.resolution)
					y_ind = int((curr_y - self.origin[1])/self.resolution)
					if x_ind == datax_pixel and y_ind==datay_pixel and self.odds_ratios[datax_pixel, datay_pixel] >= 1/60.0:
						#set odds ratio equal to past odds ratio
						if time_past % 5 == 0:
							self.past_odds_ratios[datax_pixel, datay_pixel]=self.odds_ratios[datax_pixel, datay_pixel]
							time_past += 1
						self.odds_ratios[datax_pixel, datay_pixel] *= self.p_occ[datax_pixel, datay_pixel]/(1-self.p_occ[datax_pixel, datay_pixel]) * self.odds_ratio_hit
					if not((x_ind, y_ind) in marked) and self.odds_ratios[x_ind, y_ind] >= 1/60.0:
						#If point isn't marked, update the odds of missing and add to the map
						if time_past % 5 == 0:
							self.past_odds_ratios[x_ind, y_ind]=self.odds_ratios[x_ind, y_ind]
							time_past += 1
						self.odds_ratios[x_ind, y_ind] *= self.p_occ[x_ind, y_ind] / (1-self.p_occ[x_ind, y_ind]) * self.odds_ratio_miss
						marked.add((x_ind, y_ind))
				if not(self.is_in_map(data_x, data_y)) and self.odds_ratios[data_x, datay_pixel] >= 1/60.0:
					#if it is not in the map, update the odds of hitting it
					if time_past % 5 == 0:
						self.past_odds_ratios[datax_pixel, datay_pixel]=self.odds_ratios[datax_pixel, datay_pixel]
						time_past += 1
					self.odds_ratios[datax_pixel, datay_pixel] *= self.p_occ[datax_pixel, datay_pixel]/(1-self.p_occ[datax_pixel, datay_pixel]) * self.odds_ratio_hit

		self.seq += 1
		if self.seq % 10 == 0:
			map = OccupancyGrid() #this is a nav msg class
			map.header.seq = self.seq
			map.header.stamp = msg.header.stamp
			map.header.frame_id = "map"
			map.header.frame_id = "past_map"
			map.info.origin.position.x = self.origin[0]
			map.info.origin.position.y = self.origin[1]
			map.info.width = self.n
			map.info.height = self.n
			map.info.resolution = self.resolution
			map.data = [0]*self.n**2 #the zero is a formatter, not a multiple of 0
			for i in range(self.n):
				#this is giving us the i,j grid square, occupancy grid
				for j in range(self.n):
					idx = i+self.n*j #makes horizontal rows (i is x, j is y)
					if self.odds_ratios[i,j] < 1/50.0:
						map.data[idx] = 0 #makes the gray
					elif self.odds_ratios[i,j] >= 1/50.0 < 4.0/5.0:
						map.data[idx] = 25
					elif self.odds_ratios[i,j] > 50.0:
						map.data[idx] = 100 #makes the black walls
					else:
						map.data[idx] = -1 #makes unknown
			self.pub.publish(map)

		image = np.zeros((self.odds_ratios.shape[0], self.odds_ratios.shape[1],3))
		image2 = np.zeros((self.odds_ratios.shape[0], self.odds_ratios.shape[1],3))

		self.counter+=1

		#get robots position
		x_odom_index = int((self.odom_pose[0] - self.origin[0])/self.resolution)
		y_odom_index = int((self.odom_pose[1] - self.origin[1])/self.resolution)

		#remember robots position over time
		self.pose.append((x_odom_index, y_odom_index))

		#.shape() comes from being related to the np class
		for i in range(image.shape[0]):
			for j in range(image.shape[1]):
				#the thing that just rapidly appeared, disappeared!
				delta = (self.odds_ratios[i,j]-self.past_odds_ratios[i,j])
				if (delta < 0.0) and (i,j) in self.rapid_appear:
					self.dyn_obs.append((i,j,self.counter))
				#whoa buddy, a thing just appeared!
				if delta > 1000.0 and (i,j) not in self.rapid_appear:
					self.rapid_appear.add((i,j))
				#Map the world with particular colors
				if self.odds_ratios[i,j] < 1/50.0:
					image[i,j,:] = 1.0 #makes open space
				elif self.odds_ratios[i,j] >= 1/50.0 and self.odds_ratios[i,j] <4/5.0:
					image[i,j,:] = (0, 255, 0) #uncertainty points
				elif self.odds_ratios[i,j] > 50.0:
					image[i,j,:] = (0, 0, 255) #makes walls
				else:
					image[i,j,:] = 0.5 #not read

		#if a dynamic obstacle is recorded, let's see it!
		if len(self.dyn_obs)>0:
			for point in self.dyn_obs:
				if (self.counter-point[2])<=10:
					image2[point[0],point[1]] = (255,0,255) #makes old/dynamic shapes on other map
		#also, we want to map the robot's trail
		for point in self.pose:
			image[point[0], point[1]] = (255, 0, 0)

		#draw it!
		cv2.circle(image,(y_odom_index, x_odom_index), 2,(255,0,0))
		cv2.imshow("map", cv2.resize(image,(500,500)))
		cv2.imshow("past_map", cv2.resize(image2,(500,500)))
		cv2.waitKey(20) #effectively a delay

	def run(self):
		r = rospy.Rate(10)
		while not(rospy.is_shutdown()):
			r.sleep()

if __name__ == '__main__':
	try:
		n = RunMapping()
		n.run()
	except rospy.ROSInterruptException: pass


import collections

barve = [("A3", "zelena"), ("B5", "modra"), ("A3", "rumena")]

def barvanje(barve):
    sahovnica = collections.defaultdict()
    for polje, barva in barve:
        if polje in sahovnica:
            continue
        sahovnica[polje] = barva
    return sahovnica

print(barvanje(barve))

######################################################################

sahovnica = {
    "A3": "rumena", "A6": "rumena", "H2": "rumena", "G7": "rumena",
    "C2": "zelena", "C3": "zelena",
    "H6": "modra"
}

def prestej_barvo(sahovnica, barva):
    ponovitev = 0
    for barva1 in sahovnica.values():
        if barva1 == barva:
            ponovitev += 1
    return ponovitev

print(prestej_barvo(sahovnica, 'rumena'))


'''
第2题：
改进下列程序，使得列表中任意位置出现非数字元素，均能实现获取列表的最大值
list1 = ['b', 'c', 23, -59, 32, 'a', 76, 20]

max = list1[0]
for each in list1:
    #print(each)
    if type(each) in [int, float]:
        if each > max:
            max =  each

print(max)
'''

list1 = ['b', 'c', 23, -59, 32, 'a', 76, 20]
list2 = []
for each in list1:
    if type(each) in [int, float]:
        list2.append(each)
max = max(list2)
print(max)


# basic library for class Led
# octopusLAB 2019
"""
led = Led(2)
led.value(1)
"""

__version__ = "1.0.0"

from time import sleep_ms
from machine import Pin

def blink(pin, length_on=1000, length_off=1000):
    print("WARGNING: DEPRECATED: Do not USE, Use Led class instead!!")

    if pin is None:
        print("DUMMY_LED DEPRECATED: Blink")
        return

    if length_off == 1000 and length_on != 1000:
        length_off = length_on

    pin.value(1)
    sleep_ms(length_on)
    pin.value(0)
    sleep_ms(length_off)

class Led:
    def __init__(self, pin, value=False):
        self.pin = None
        self.state = value

        if pin is None:
            print("WARN: Pin is None, this led will be dummy")
            return

        self.pin = Pin(pin, Pin.OUT)
        self.pin.value(self.state)

    def blink(self, length_on=1000, length_off=1000):
        if length_off == 1000 and length_on != 1000:
            length_off = length_on

        self.toggle()
        sleep_ms(length_on)
        self.toggle()
        sleep_ms(length_off)

    def value(self, value=None):
        if value is None:
            if self.pin is not None:
                self.state = self.pin.value() # Update internal value in case someone changed it from outside

            return self.state

        self.state = value

        if self.pin is None:
            print("DUMMY_LED Value {0}".format(self.state))
            return

        self.pin.value(self.state)

    def toggle(self):
        self.value(not self.value())


import csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D

obs=np.array([[0,0,0]])
path=np.array([[0,0,0]])
path1=np.zeros((1,500))
i=0

flag=1

with open('board.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in spamreader:
        a=np.fromstring(",".join(row).replace(' ', ''), dtype=np.float, sep=',')
        if(a[0]==-1):
            flag=0

        if(flag):
            obs = np.append(obs,np.array([a]), axis=0)
        else:
            path = np.append(path,np.array([a]), axis=0)

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

xline = obs[1:,0]
yline = obs[1:,1]
zline = obs[1:,2]

ax.scatter(xline, yline, zline ,marker='s',s=30)

xline = path[2:,0]
yline = path[2:,1]
zline = path[2:,2]

ax.scatter(xline, yline, zline,marker='s',s=30)

plt.show()