# -*- mode: python ; coding: utf-8 -*-

block_cipher = None
from os.path import *
import sys
import win32com.client
import zipfile
import PyInstaller.config
os.path.expanduser

# https://stackoverflow.com/a/42056050
def zipdir(path, ziph):
    length = len(path)

    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        folder = root[length:] # path without "parent"
        for file in files:
            ziph.write(os.path.join(root, file), os.path.join(folder, file))

# pyinstaller build
PyInstaller.config.CONF['distpath'] = "./dist/potatofy_win"
a = Analysis(['potatofy.py'],
             pathex=['C:\\Users\\chanc\\Documents\\Projects\\potatofy'],
             binaries=[],
             datas=[('icons/Questrade.png', 'icons')],
             hiddenimports=['pkg_resources.py2_warn'],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='potatofy',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=False )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               upx_exclude=[],
               name='potatofy')

# post-build script
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("./dist/potatofy_win/potatofy.lnk")
shortcut.Targetpath = abspath(abspath(".\dist\potatofy_win\potatofy\potatofy.exe"))
shortcut.save()

print("Creating zip")
os.chdir("./dist/")
zipf = zipfile.ZipFile('./potatofy.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('./potatofy_win/', zipf)
zipf.close()
print("Finished zip")


# coding=utf-8
'''
Selenium 3 版本需要下载第3方webdriver 'geckodriver'，并放到firefox资料夹中
之后再将该路径添加到环境变数path中
参考网址:https://www.zhihu.com/question/49568096
'''
from selenium import webdriver
from time import sleep

driver = webdriver.Firefox()
driver.get("https://www.google.com")

driver.find_element_by_id("lst-ib").send_keys("Selenium2")
driver.find_element_by_xpath(".//*[@id='tsf']/div[2]/div[3]/center/input[1]").click()
sleep(2)

driver.quit()


"""
In charge of indexing and preprocessing road parts.
"""

from dataclasses import dataclass, field
from hashlib import sha384

from panda3d import core
from direct.stdpy.file import *
from direct.stdpy import pickle

from .common import PR_DEFAULT_DENSITY
from . import preprocess as pp
from . import util

def chk_timestamp(key, base_type):
    h = sha384(f'{key}-{base_type}'.encode()).hexdigest()
    lvl_fname = core.Filename(base.main_dir, f'assets/cache/{h}')
    bam_fname = core.Filename(base.main_dir, f'assets/models/{key}.bam')
    timestamp = 0
    need_reload = True
    if lvl_fname.exists():
        with open(lvl_fname.to_os_specific(), 'r') as f:
            try:
                timestamp = int(f.read())
            except ValueError:
                pass
    else:
        lvl_fname.make_dir()
        need_reload = True
    bts = bam_fname.get_timestamp()
    if bts == timestamp:
        need_reload = False
    with open(lvl_fname.to_os_specific(), 'w') as f:
        f.write(str(bts))
    return need_reload, lvl_fname

def get_bounds(need_reload, key, np):
    h = sha384(f'{key}-road-{np.name}'.encode()).hexdigest()
    fname = core.Filename(base.main_dir, f'assets/cache/{h}')
    if need_reload:
        bounds = pp.get_model_bounds(np)
        with open(fname.to_os_specific(), 'wb') as f:
            pickle.dump(bounds, f)
    else:
        with open(fname.to_os_specific(), 'rb') as f:
            bounds = pickle.load(f)
    return bounds

@dataclass
class Part:
    level_type:str
    part_type:str
    model:core.NodePath
    bounds:pp.Bounds
    density:float = -1.0

class PartMgr:
    def __init__(self, models, keys=('test', )):
        self._parts = {}
        self._build_lib(models, keys)

    def _build_lib(self, models, keys):
        for k in keys:
            if k == 'parts':
                self._scan_road_parts(models)
            elif k == 'props':
                self._scan_props(models)
            else:
                print(f'Unknown key "{k}"')

    def _compute_ground(self, key):
        ground = float('inf')
        for part in self._parts[key]['road']:
            ground = min(ground, part.bounds.depth)
        self._parts[key]['ground'] = ground

    def _scan_road_parts(self, models):
        for key, model in models.items():
            need_reload, lvl_fname = chk_timestamp(key, 'road')
            if key not in self._parts:
                self._parts[key] = {}
            if 'road' not in self._parts[key]:
                self._parts[key]['road'] = []
            for np in model.find_all_matches('**/road_part*'):
                np.detach_node()
                util.set_faux_lights(np)
                np.clear_transform()
                bounds = get_bounds(need_reload, key, np)
                part = Part(key, np.name, np, bounds)
                if 'transition' in np.name:
                    self._parts[key]['transition'] = part
                else:
                    self._parts[key]['road'].append(part)
                np.flatten_strong()
            self._compute_ground(key)

    def _scan_props(self, models):
        for key, model in models.items():
            need_reload, lvl_fname = chk_timestamp(key, 'props')
            if key not in self._parts:
                self._parts[key] = {}
            if 'props' not in self._parts[key]:
                self._parts[key]['props'] = []
            for np in model.find_all_matches('**/props*'):
                np.detach_node()
                np.clear_transform()
                for child in np.get_children():
                    child.detach_node()
                    child.clear_transform()
                    d = child.get_net_tag('density')
                    d = float(d) if d else PR_DEFAULT_DENSITY
                    bounds = get_bounds(need_reload, key, child)
                    part = Part(key, child.name, child, bounds, d)

                    lights = []
                    for n in child.find_all_matches('**/*light*'):
                        n.detach_node()
                        lights.append(n)
                    child.flatten_strong()
                    for n in lights:
                        n.reparent_to(child)
                    util.set_faux_lights(child)
                    if part.bounds.width > 0:
                        self._parts[key]['props'].append(part)
                    else:
                        print(f'Could not scan Prop, apparently width is 0: {part}')

    def get_road_part(self, part_type, variant):
        return self._parts[part_type]['road'][variant]

    def get_road_transition(self, part_type):
        return self._parts[part_type]['transition']

    def get_prop(self, part_type, variant):
        return self._parts[part_type]['props'][variant]

    def get_prop_by_density(self, part_type, density_min):
        return [i for i in self._parts[part_type]['props'] if i.density >= density_min]

    def get_prop_by_prefix(self, part_type, prefix):
        return [i for i in self._parts[part_type]['props'] if i.part_type.startswith(f'{prefix}')]

    def get_part_types(self):
        return list(self._parts.keys())

    def num_roads(self, part_type):
        return len(self._parts[part_type]['road'])

    def num_props(self, part_type):
        return len(self._parts[part_type]['props'])

    def ground(self, part_type):
        return self._parts[part_type]['ground']

    def store(self, fpath):
        pass

    def load(self, fpath):
        pass

    def __getitem__(self, item):
        return self._parts[item[0]][item[1]]


# https://www.acmicpc.net/problem/7576
# 토마토

import sys
from collections import deque

queue = deque()
visit = list()

dxs = [1, -1, 0, 0]
dys = [0, 0, 1, -1]

ripping = False
ripe_day = 0

size_M, size_N = list(map(int, sys.stdin.readline().strip().split()))
tomato_box = list()
for _ in range(size_N):
    tomato_box.append(list(map(int, sys.stdin.readline().strip().split())))

for i in range(size_N):
    for j in range(size_M):
        if tomato_box[i][j] == 1: queue.append([i, j])

while queue:
    node = queue.popleft()
    tomato_x, tomato_y = node

    for dx, dy in zip(dxs, dys):
        new_tomato_x, new_tomato_y = tomato_x+dx, tomato_y+dy
        if new_tomato_x>=0 and new_tomato_x<size_N \
            and new_tomato_y>=0 and new_tomato_y<size_M \
            and tomato_box[new_tomato_x][new_tomato_y] == 0:
            tomato_box[new_tomato_x][new_tomato_y] = tomato_box[tomato_x][tomato_y]+1
            queue.append([new_tomato_x, new_tomato_y])
            ripping = True

        if ripping:
            ripe_day = tomato_box[tomato_x][tomato_y]
            ripping = False

full_tomato = True
for i in range(size_N):
    for j in range(size_M):
        if tomato_box[i][j] == 0 :
            full_tomato = False
            break

if not full_tomato : print(-1)
else : print(ripe_day)


from urllib import request
from django.shortcuts import get_object_or_404, render, reverse, redirect
from django.contrib.auth.decorators import login_required
from .models import Suggestion
from .forms import SuggestionForm
from django.contrib import messages

def view_suggestions(request):
    """
    View all submitted suggestions
    """
    suggestions = Suggestion.objects.all().order_by('-number_of_upvotes')

    context = {
        'suggestions': suggestions,
    }

    return render(request, 'suggestions/view_suggestions.html', context)

@login_required
def add_suggestion(request):
    """
    Add a suggestion form if request = GET
    Submits the form if request = POST
    """
    if request.method == "POST":
        suggestion_form = SuggestionForm(request.POST)
        if suggestion_form.is_valid():
            suggestion = suggestion_form.save(commit=False)
            suggestion.creator = request.user
            suggestion.save()
            messages.success(request, 'Successfully added suggestion!')
            return redirect(reverse('view_suggestions'))
    else:
        suggestion_form = SuggestionForm()

        context = {
            'suggestion_form': suggestion_form,
        }

        return render(request, 'suggestions/add_suggestion.html', context)

@login_required
def edit_suggestion(request, suggestion_id):
    """
    Load the suggestion in the editor to allow the creator to make changes
    """
    if request.method == "POST":
        suggestion = get_object_or_404(Suggestion, pk=suggestion_id)
        suggestion_form = SuggestionForm(request.POST, instance=suggestion)
        if suggestion_form.is_valid():
            suggestion = suggestion_form.save()
            messages.success(request, 'Suggestion succesfully updated!')
        else:
            messages.warning(request, 'Error while saving, please try again')

        return redirect(reverse('view_suggestions'))
    else:
        suggestion = get_object_or_404(Suggestion, pk=suggestion_id)
        suggestion_form = SuggestionForm(instance=suggestion)
        context = {
            'suggestion_form': suggestion_form,
            'suggestion': suggestion,
        }

        return render(request, 'suggestions/edit_suggestion.html', context)

@login_required
def delete_suggestion(request, suggestion_id):
    """
    Allows the creator to delete the suggestion
    """
    suggestion = get_object_or_404(Suggestion, pk=suggestion_id)
    suggestion.delete()
    messages.warning(request, 'Suggestion succesfully deleted')

    return redirect(reverse('view_suggestions'))

@login_required
def upvote_suggestion(request, suggestion_id):
    """
    Upvotes a suggestion if a user is logged in
    and hasn't voted for this suggestion before
    """
    suggestion = get_object_or_404(Suggestion, pk=suggestion_id)
    user = request.user
    # check if user is in list of upvoters
    upvoters = suggestion.upvoters_as_list()
    if str(user) not in upvoters:
        suggestion.upvoters = str(suggestion.upvoters) + f';{user}'
        suggestion.number_of_upvotes += 1
        messages.success(request, f'Upvoted: {suggestion.common_name}')
        suggestion.save()
    else:
        messages.warning(request, 'You have already voted for this plant')

    return redirect(reverse('view_suggestions'))


import json
import random
import requests
from mtranslate import translate
import streamlit as st

MODEL_URL = "https://api-inference.huggingface.co/models/flax-community/papuGaPT2"
PROMPT_LIST = {
    "Najsmaczniejszy owoc to...": ["Najsmaczniejszy owoc to "],
    "Cześć, mam na imię...": ["Cześć, mam na imię "],
    "Największym polskim poetą był...": ["Największym polskim poetą był "],
}
API_TOKEN = st.secrets["api_token"]
headers = {"Authorization": f"Bearer {API_TOKEN}"}

def query(payload, model_url):
    data = json.dumps(payload)
    print("model url:", model_url)
    response = requests.request("POST", model_url, headers=headers, data=data)
    return json.loads(response.content.decode("utf-8"))

def process(
    text: str, model_name: str, max_len: int, temp: float, top_k: int, top_p: float
):
    payload = {
        "inputs": text,
        "parameters": {
            "max_new_tokens": max_len,
            "top_k": top_k,
            "top_p": top_p,
            "temperature": temp,
            "repetition_penalty": 2.0,
        },
        "options": {
            "use_cache": False,
        },
    }
    return query(payload, model_name)

# Page
st.set_page_config(page_title="papuGaPT2 aka Polish GPT-2 model demo")
st.title("papuGaPT2 aka Polish GPT-2")
# Sidebar
st.sidebar.subheader("Configurable parameters")
max_len = st.sidebar.number_input(
    "Maximum length",
    value=100,
    max_value=250,
    help="The maximum length of the sequence to be generated.",
)
temp = st.sidebar.slider(
    "Temperature",
    value=1.0,
    min_value=0.1,
    max_value=2.0,
    help="The value used to module the next token probabilities.",
)
top_k = st.sidebar.number_input(
    "Top k",
    value=10,
    help="The number of highest probability vocabulary tokens to keep for top-k-filtering.",
)
top_p = st.sidebar.number_input(
    "Top p",
    value=0.95,
    help=" If set to float < 1, only the most probable tokens with probabilities that add up to top_p or higher are kept for generation.",
)
do_sample = st.sidebar.selectbox(
    "Sampling?",
    (True, False),
    help="Whether or not to use sampling; use greedy decoding otherwise.",
)
# Body
st.markdown(
    """
    This demo showcases the text generation capabilities of the papuGaPT2, a GPT2 model pre-trained from scratch using Polish subset of the multilingual Oscar corpus.

    To use it, add your text to 'Enter Text' box, or click one of the examples in 'Prompt' drop-down list to load them and click 'Run' button. The model will generate text based on the entered text (prompt).

    For more information including dataset, training and evaluation procedure, intended use, limitations and bias analysis see the [model card](https://huggingface.co/flax-community/papuGaPT2).

    In this demo, we used the template from the wonderful demo of [Spanish GPT2 team](https://huggingface.co/spaces/flax-community/spanish-gpt2) especially María Grandury and Manuel Romero.
    """
)
model_name = MODEL_URL
ALL_PROMPTS = list(PROMPT_LIST.keys()) + ["Custom"]
prompt = st.selectbox("Prompt", ALL_PROMPTS, index=len(ALL_PROMPTS) - 1)
if prompt == "Custom":
    prompt_box = "Enter your text here"
else:
    prompt_box = random.choice(PROMPT_LIST[prompt])
text = st.text_area("Enter text", prompt_box)
if st.button("Run"):
    with st.spinner(text="Getting results..."):
        st.subheader("Result")
        print(f"maxlen:{max_len}, temp:{temp}, top_k:{top_k}, top_p:{top_p}")
        result = process(
            text=text,
            model_name=model_name,
            max_len=int(max_len),
            temp=temp,
            top_k=int(top_k),
            top_p=float(top_p),
        )
        print("result:", result)
        if "error" in result:
            if type(result["error"]) is str:
                st.write(f'{result["error"]}.', end=" ")
                if "estimated_time" in result:
                    st.write(
                        f'Please try again in about {result["estimated_time"]:.0f} seconds.'
                    )
            elif type(result["error"]) is list:
                for error in result["error"]:
                    st.write(f"{error}")
        else:
            result = result[0]["generated_text"]
            st.write(result.replace("\n", "  \n"))
            st.text("English translation")
            st.write(translate(result, "en", "pl").replace("\n", "  \n"))


import base
import utils
import os
import sys
import info

class subinfo(info.infoclass):
    def setTargets( self ):
        self.svnTargets['gitHEAD'] = '[git]kde:pykde4'
        self.defaultTarget = 'gitHEAD'
        self.patchToApply['gitHEAD'] = ('pykde-20110318.patch', 1)

    def setDependencies( self ):
        self.hardDependencies['kde/kdelibs'] = 'default'
        self.hardDependencies['testing/sip'] = 'default'
        self.hardDependencies['testing/pyqt'] = 'default'

from Package.CMakePackageBase import *

class Package(CMakePackageBase):
    def __init__( self ):
        self.subinfo = subinfo()
        CMakePackageBase.__init__( self )
        localPythonPath = os.path.join(self.rootdir, 'emerge', 'python')
        haveLocalPython = os.path.exists(localPythonPath)
        if haveLocalPython:
            self.subinfo.options.merge.destinationPath = "emerge/python"
        else:
            # PyQt4 does not install itself in C:\Python27\Lib\site-packages
            # so how is python supposed to be able to import it?
            pyqtDir = os.path.join(self.rootdir,'lib','site-packages')
            if pyqtDir not in os.getenv("PYTHONPATH").split(';'):
                newPath = ";".join([os.getenv("PYTHONPATH"), pyqtDir])
                os.environ["PYTHONPATH"] = newPath
                utils.debug('added %s to PYTHONPATH' % pyqtDir, 2)

if __name__ == '__main__':
    Package().execute()


import numpy as np
import osmnx as ox

place = "Aveiro, Aveiro, Portugal"
G = ox.graph_from_place(place, network_type="drive")
Gp = ox.project_graph(G)
print(Gp)

points = ox.utils_geo.sample_points(ox.get_undirected(Gp), n=100)
X = points.x.values
Y = points.y.values
X0 = X.mean()
Y0 = Y.mean()

nodes, dists = ox.nearest_nodes(Gp, X, Y, return_dist=True)

node = ox.nearest_nodes(Gp, X0, Y0)

orig = list(G)[0]
dest = list(G)[120]
route = ox.shortest_path(G, orig, dest, weight="length")

list=[]
for x in route:
    print("coordenadas no 1", G.nodes[x]['x'], G.nodes[x]['y'])
    list.append([G.nodes[x]['x'], G.nodes[x]['y']])

print(route)

print(list)


from collections import deque

while True:
    w, h = map(int,input().split())
    if w == 0 and h == 0:
        break
    cnt = 0
    arr = [list(map(int,input().split())) for _ in range(h)]
    # print(arr)
    dr = [1, 1, 0, -1, -1, -1, 0, 1]
    dc = [0, 1, 1, 1, 0, -1, -1, -1]

    queue = deque()
    for i in range(h):
        for j in range(w):
            if arr[i][j] == 1:
                queue.append([i,j])
                arr[i][j] = -1

                while queue:
                    r, c = queue.popleft()
                    for k in range(8):
                        nr = r + dr[k]
                        nc = c + dc[k]

                        if 0<= nr < h and 0<= nc < w and arr[nr][nc] == 1:
                            queue.append([nr, nc])
                            arr[nr][nc] = -1

                cnt += 1
    print(cnt)


# -*- coding: utf-8 -*-
"""
Created on Sun Oct 21 20:24:36 2018

@author: Benjamin Ihme
"""

#TODO: LU DECOMPOSITIN AND INVERSE

#NOTE: I dont use __getitem__ and __setitem__ because that would increase runtime and typing "entries"
# a few times is not so bad
class Matrix:
    def __init__(self, entries=[[0]]):

        # check for mistakes and if necessary set the matrix to predefined value
        if type(entries)!= list:
            if type(entries)==int or type(entries)==float or type(entries)==complex:
                self.entries=[[entries]]
            else:
                raise TypeError("incompatible type of entry for matrix")
        elif len(entries)==1 and len(entries[0])==0: #if given matrix is empty
            self.entries=[[0]] #set it to zero
        elif len(entries)==0: #if given matrix is empty
            self.entries=[[0]] #set it to zero
        elif type(entries[0])!=list: #check for
            if type(entries[0])==int or type(entries[0])==float or type(entries[0])==complex:
                self.entries=[[x] for x in entries]
            else:
                raise TypeError("incompatible type of entry for matrix")
        else:
            k=len(entries[0]) #check if all rows have the same length
            for i in range(len(entries)):
                if len(entries[i])!= k:
                    raise Exception("all rows of matrix have to have same length")
                for j in range(len(entries[i])):
                    if type(entries[i][j])!=int and type(entries[i][j])!=float and type(entries[i][j])!=complex:
                        raise TypeError("only int, float and complex are accepted types  for entries of matrix")

            self.entries=entries

    def height(self):
        return len(self.entries)
    def width(self):
        return len(self.entries[0])

    #method to print matrix
    def __str__(self):
        s=''
        for i in range(self.height()):
            for j in range(self.width()):
                s= s+str(self.entries[i][j])+', '
            s=s+'\n'
        return s

    # method to multiply two matrices
    def __mul__(self,other):
        #check for compatible type
        if type(other)!= Matrix:
            raise TypeError("matrix can only be multiplied with other matrix")

        #check for compatible dimensions
        if self.width()!=other.height():
            raise Exception("Incompatible Dimensions for matrix multiplication")

        #multiply matrices
        new_entries=[[0 for x in range(other.width())] for n in range(self.height())] #0-entries of right dimension
        for i in range(self.height()):
            for k in range(other.width()):
                for j in range(self.width()):
                    new_entries[i][k]=new_entries[i][k]+self.entries[i][j]*other.entries[j][k]
        return Matrix(new_entries)

    # method to compare two matrices for equality
    def __eq__(self,other):

        #first check for equality despite other data type
        if type(other)!= Matrix:
            if type(other)==int or type(other)==float or type(other)==complex:
                if self.height()==1 and self.width()==1:
                    return self.entries[0][0]==other

            elif type(other)==list:
                if len(other)==0: return false
                elif len(other)==1:
                    return self.entries[0][0]==other[0]

                #check wether other is a "vector" equal to our matrix
                elif self.width()==1 and self.height()==len(other):
                    for i in range(self.height()):
                        if self.entries[i][0]!=other[i]:
                            return False
                    return True

            else: return False
        else: return self.entries==other.entries

        # method to add row multiplier*r2 to row r1
    def add_row_to_row(self, r1, r2, multiplier):
        #check for false rows
        if r2<1 or r1<1 or r2>self.height() or r1>self.height():
            raise Exception("trying to add nonexistent row")

        #add mlutiplier*r2 to r1
        self.entries[r1-1]=[self.entries[r1-1][i]+multiplier*self.entries[r2-1][i] for i in range(self.width())]

    # method to multiply row r ba multiplier
    def mult_row(self,r, multiplier):
        #check for false row
        if r<1 or r>self.height():
            raise Exception("trying to multiply nonexistent row")

        #multiply row with multiplier
        self.entries[r-1]=[multiplier*self.entries[r-1][i] for i in range(self.width())]

    # method to swap row r1 with row r2
    def swap_rows(self,r1,r2):
        #check for false rows
        if r2<1 or r1<1 or r2>self.height() or r1>self.height():
            raise Exception("trying to swap nonexistent row")

        #swap rows r1 and r2
        if r1!=r2: # prevents useles computation
            self.entries[r1-1],self.entries[r2-1]=self.entries[r2-1],self.entries[r1-1]

    # method to compute inverse of square matrix
    def inverse(self):
        #check for correct dimensions
        if self.height()!=self.width():
            raise Exception("trying to find inverse of non square matrix")

        d=self.height() #to be used multiple times

        #build 1-Matrix of same dimension
        one_coef=[[1 if i==j else 0 for i in range(d)] for j in range(d)]
        E=Matrix(one_coef)

        #make copy of self
        copy=Matrix(self.entries)

        #apply steps used to form copy to the 1-Matrix to the 1 matrix
        for i in range(d):
            if copy.entries[i][i]!=0:

                E.mult_row(i+1, 1/copy.entries[i][i])
                copy.mult_row(i+1, 1/copy.entries[i][i])

                for j in list(range(i))+list(range(i+1, d)): #go through all rows except for i
                    E.add_row_to_row(j+1, i+1, (-1.0)*copy.entries[j][i]) #do same action on E
                    copy.add_row_to_row(j+1, i+1, (-1.0)*copy.entries[j][i]) #multiply so entry in i'th column is 0

            else:
                nonzero_found=False
                nonzero_line_index=0
                for j in range(i+1, d): #go through all rows except for i
                    if copy.entries[j][i]!=0: #if non-zero entry is found below
                        nonzero_found=True
                        nonzero_line_index=j+1
                        break
                if nonzero_found==False: #if nonzero entry wasnt fount matrix isnt invertible
                    raise Exception("trying to invert non-invertable matrix")
                else: #if nonzero entry was found

                    E.swap_rows(nonzero_line_index, i+1) #also swap in E
                    copy.swap_rows(nonzero_line_index, i+1) #swap the rows so nonzero is on diagonal

                    E.mult_row(i+1, 1/copy.entries[i][i])
                    copy.mult_row(i+1, 1/copy.entries[i][i])

                    for j in list(range(i))+list(range(i+1, d)): #go through all rows except for i
                        E.add_row_to_row(j+1, i+1, (-1.0)*copy.entries[j][i]) #do same action on E
                        copy.add_row_to_row(j+1, i+1, (-1.0)*copy.entries[j][i]) #multiply so entry in i'th column is 0

        return E

    #method to find LU Decomposition of square matrix
    def LU_Decomposition(self):

        #first check for if matrix is square
        if self.height()!=self.width():
            raise Exception("LU Decomposition only for square matrix")

        # create copy of matrix to perform actions on. it will be transformed
        #to the Upper Matrix and store the entries of lower Matrix in Lower
        #part, as that part of upper Matrix becomes 0
        U=Matrix(self.entries)

        d=self.height() #to be used multiple times

        #variables to help by searching
        row_max_entry=0
        max_entry=0

        # perform Decomposition
        for i in range(d):

            row_max_entry=i+1 #set var back to 0 so you can look for next biggest abs
            max_entry=abs(U.entries[i][i]) #set variable to current diagonal

            #go through all rows beneath row i+1 and search for maximal absolute entry
            for j in range(i+1,d):
                if abs(U.entries[j][i])>max_entry:
                    max_entry=abs(U.entries[j][i])
                    row_max_entry=j+1

            #check if max_entry is 0
            if max_entry==0:
                raise ValueError("trying to find LU Decomposition of non-regular matrix")

            #swap row with maximal absolute entry onto diagonal
            if row_max_entry!=i+1:
                U.swap_rows(i+1, row_max_entry)

            #go through rows below and do special row to row addition,
            #so that lower Matrix is not effected
            for j in range(i+1, d):

                #save entry of row j+1 in column i+1 because it will be changed,
                #end we need it later to add to Lower matrix
                b=U.entries[j][i]

                #go through all columns from i+1 on and subtract i+1'th row
                #so that entry in i+1'th column becomes 0
                for k in range(i,d):
                    U.entries[j][k]=U.entries[j][k]+((-1.0)*b/U.entries[i][i])*U.entries[i][k]

                U.entries[j][i]=1.0*b/U.entries[i][i]

        return U

#Bsp LU Decomposition (be aware that the permutations of original matrix
#are not represented in the output, so there is some permutation of rows P
#such that P*A=L*U)

# =============================================================================
# M2=Matrix([[3,2,1],
#            [6,6,3],
#            [9,10,6]])
#
# print(M2.LU_Decomposition())
#
# M=Matrix([[0,1],
#           [1,0]])
# print(M.LU_Decomposition())
# =============================================================================

#Example for inverse Matrix
#m=Matrix([[3 ,-1,2 ],
#          [-3,4 ,-1],
#          [-6,5,-2]])
#print(m.inverse())

#Example for assotiative matrix multiplication

#m1=Matrix([[1,2,3,4]])

#m2=Matrix([[1,2  ],
#           [2,3  ],
#           [4,6  ],
#           [7,1.3]])
#
#m3=Matrix([[3,5,7,3,1],
#           [6,2,9,0,0]])

#print((m1*m2)*m3)
#print(m1*(m2*m3))


import sys

n = int(sys.stdin.readline().rstrip())
top = list(map(int, sys.stdin.readline().split()))
temp = []
answer = [-1 for _ in range(n)]

for i in range(n - 1, -1, -1):
    if not temp or top[i] < top[temp[-1]]:
        temp.append(i)
    else:
        while temp and top[temp[-1]] < top[i]:
            answer[temp.pop()] = i + 1
        temp.append(i)

while temp:
    answer[temp.pop()] = 0

print(' '.join(map(str, answer)))


import json

from django.conf.urls import url

from tastypie.authentication import MultiAuthentication, SessionAuthentication
from tastypie.resources import Resource

from repos.models import Repository
from visualizations.models import Visualization, VisualizationSerializer

from .authentication import ApiTokenAuthentication
from .authorization import VizAuthorization

class VizResource( Resource ):

    class Meta:
        resource_name = 'viz'

        detail_allowed_methods = [ 'delete', 'get', 'post' ]

        # Ensure we have an API token before returning any data.
        # TODO: Make sure this API token concept works with public/private
        # data.
        authentication = MultiAuthentication( ApiTokenAuthentication(),
                                              SessionAuthentication() )

        authorization = VizAuthorization()

    def prepend_urls( self ):
        base_url = '^(?P<resource_name>%s)/(?P<pk>\w+)' % ( self._meta.resource_name )

        return [
            url( r'%s/(?P<viz_id>\d+)/' % ( base_url ), self.wrap_view( 'delete_detail' ), name='api_delete_detail' )
        ]

    def dehydrate( self, bundle ):
        serializer = VisualizationSerializer()
        bundle.data = serializer.serialize( [bundle.obj] )
        return bundle

    def delete_detail( self, request, **kwargs ):

        # Grab the repo we're creating a visualization for
        repo_id = kwargs.get( 'pk' )
        viz_id  = kwargs.get( 'viz_id' )

        try:
            basic_bundle = self.build_bundle( request=request )
            basic_bundle.obj = Visualization.objects.get( id=viz_id, repo__mongo_id=repo_id )

            if not self.authorized_delete_detail( basic_bundle.obj, basic_bundle ):
                return HttpUnauthorized()

            basic_bundle.obj.delete()
            response_data = { 'success': True }
            return self.create_response( request, response_data )

        except ValueError as e:
            return HttpBadRequest( str( e ) )

        return HttpUnauthorized()

    def get_detail( self, request, **kwargs ):

        # Grab the repo we're creating a visualization for
        repo_id = kwargs[ 'pk' ]

        try:
            basic_bundle = self.build_bundle( request=request )
            basic_bundle.obj = Visualization.objects.get(repo__mongo_id=repo_id)

            if not self.authorized_read_detail( basic_bundle.obj, basic_bundle ):
                return HttpUnauthorized()

            basic_bundle = self.dehydrate( basic_bundle )

            data = {
                'objects': basic_bundle.data }

            return self.create_response( request, data )
        except ValueError as e:
            return HttpBadRequest( str( e ) )

    def post_detail( self, request, **kwargs ):

        # Grab the repo we're creating a visualization for
        repo_id = kwargs[ 'pk' ]

        try:
            basic_bundle = self.build_bundle( request=request )

            repo = Repository.objects.get( mongo_id=repo_id )
            if not self.authorized_create_detail( repo, basic_bundle ):
                return HttpUnauthorized()

            params = json.loads( request.body )

            new_viz = Visualization( name=params.get( 'name' ),
                                     repo=repo,
                                     x_axis=params.get( 'x_axis' ),
                                     y_axis=params.get( 'y_axis' ) )
            new_viz.save()
            response_data = { 'success': True, 'id': str( new_viz.id ) }
            return self.create_response( request, response_data )

        except ValueError as e:
            return HttpBadRequest( str( e ) )


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: a2htray
# create date: 2023/4/18

"""
PAT 乙级 1082
"""

from functools import cmp_to_key

def cmp(a, b):
    if a[1] > b[1]:
        return 1
    else:
        return -1

if __name__ == '__main__':
    n = int(input())

    players = []
    for _ in range(n):
        idstr, x, y = input().split()

        players.append([idstr, int(x) ** 2 + int(y) ** 2])

    players.sort(key=cmp_to_key(cmp))

    print(players[0][0], players[-1][0])


#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#

import json
import dateutil.parser
import babel
from flask import Flask, render_template, request, Response, flash, redirect, url_for, abort
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandler
from flask_wtf import Form
from flask_migrate import Migrate
from datetime import datetime
from forms import *
from helpers import *
#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

app = Flask(__name__)
moment = Moment(app)
app.config.from_object('config')
db = SQLAlchemy(app)

migrate = Migrate(app, db)

#----------------------------------------------------------------------------#
# Models.
#----------------------------------------------------------------------------#

artist_genres = db.Table('artist_genres',
    db.Column('artist_id', db.Integer, db.ForeignKey('artists.id'), primary_key=True),
    db.Column('genre_id', db.Integer, db.ForeignKey('genres.id'), primary_key=True)
    )

venue_genres = db.Table('venue_genres',
    db.Column('venue_id', db.Integer, db.ForeignKey('venues.id'), primary_key=True),
    db.Column('genre_id', db.Integer, db.ForeignKey('genres.id'), primary_key=True)
    )

class Venue(db.Model):
    __tablename__ = 'venues'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    address = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))

    website = db.Column(db.String(120))
    seeking_talent = db.Column(db.Boolean)
    seeking_description = db.Column(db.String())
    genres = db.relationship('Genre', secondary=venue_genres, backref=db.backref('venues', lazy=True))

    shows = db.relationship("Show", back_populates="venue")

    def __repr__(self):
      return self.name

class Artist(db.Model):
    __tablename__ = 'artists'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))
    seeking_venue = db.Column(db.Boolean, default=False)
    shows = db.relationship("Show", back_populates="artist")
    genres = db.relationship('Genre', secondary=artist_genres, backref=db.backref('artists', lazy=True))

class Genre(db.Model):
  __tablename__ = 'genres'
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String, nullable=False)

  def __repr__(self):
    return self.name

class Show(db.Model):
  __tablename__ = 'shows'
  venue_id = db.Column(db.Integer, db.ForeignKey('venues.id'), primary_key=True)
  artist_id = db.Column(db.Integer, db.ForeignKey('artists.id'), primary_key=True)
  venue = db.relationship("Venue", back_populates="shows")
  artist = db.relationship("Artist", back_populates="shows")
  start_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow(), primary_key=True)

  def __repr__(self):
    try:
      return "<({}){} - ({}){}>".format(self.venue.id,self.venue.name[:10], self.artist.id,self.artist.name[:10])
    except:
      return super.__repr__(self)

#----------------------------------------------------------------------------#
# Filters.
#----------------------------------------------------------------------------#

def format_datetime(value, format='medium'):
  if type(value) != datetime:
    date = dateutil.parser.parse(value)
  else:
    date = value
  if format == 'full':
      format="EEEE MMMM, d, y 'at' h:mma"
  elif format == 'medium':
      format="EE MM, dd, y h:mma"
  return babel.dates.format_datetime(date, format)

app.jinja_env.filters['datetime'] = format_datetime

#----------------------------------------------------------------------------#
# Controllers.
#----------------------------------------------------------------------------#

@app.route('/')
def index():
  return render_template('pages/home.html')

#----------------------------------------------------------------------------#
# Helper Functions.
#----------------------------------------------------------------------------#

# given a model with a genres association and a list of string genres,
# set the genres associated with the model to the corresponding instrumented
# list of Genre objects
def set_genre_list(model, genre_list):
  # gets a genre by name, if no corresponding genre is found, the genre is
  # created
  def get_or_create_genre(genre_name):
    genre = Genre.query.filter(Genre.name.ilike('%{}%'.format(genre_name))).first()
    if genre:
      return genre
    else:
      return Genre(name=genre_name)

  model.genres.clear()
  genre_list = [get_or_create_genre(genre) for genre in genre_list]
  model.genres.extend(genre_list)

def retrieve_upcoming_shows(filter_kwargs):
  return Show.query.filter_by(**filter_kwargs).filter(Show.start_time >= datetime.now()).all()

def retrieve_past_shows(filter_kwargs):
  return Show.query.filter_by(**filter_kwargs).filter(Show.start_time < datetime.now()).all()

def transform_artist_detail(artist):
    past_shows = retrieve_past_shows({"artist": artist})
    upcoming_shows = retrieve_upcoming_shows({"artist": artist})
    return {
        "id": artist.id,
        "name": artist.name,
        "genres": artist.genres,
        "city": artist.city,
        "state": artist.state,
        "phone": artist.phone,
        "seeking_venue": artist.seeking_venue,
        "image_link": artist.image_link,
        "facebook_link": artist.facebook_link,
        "past_shows": [transform_show(show, "venue") for show in past_shows],
        "upcoming_shows": [transform_show(show, "venue") for show in upcoming_shows],
        "past_shows_count": len(past_shows),
        "upcoming_shows_count": len(upcoming_shows),
    }

#  Venues
#  ----------------------------------------------------------------

@app.route('/venues')
def venues():

  all_venues = Venue.query.all()

  data = []

  for venue in all_venues:
    was_added = False
    # Add num_upcoming_shows
    parsed_venue = {
      "id": venue.id,
      "name": venue.name,
      "num_upcoming_shows": len(retrieve_upcoming_shows({"venue": venue}))
    }
    for i in range(len(data)):
      location = data[i]
      if location["city"] == venue.city and location["state"] == venue.state:
        data[i]["venues"].append(parsed_venue)
        was_added = True

    if not was_added:
      data.append({
        "city": venue.city,
        "state": venue.state,
        "venues": [
          parsed_venue
        ]
      })

  return render_template('pages/venues.html', areas=data);

@app.route('/venues/search', methods=['POST'])
def search_venues():

  search_term=request.form.get('search_term', '')

  matching_venues= Venue.query.filter(Venue.name.ilike('%{}%'.format(search_term))).all()

  response={
    "count": len(matching_venues),
    "data": [{"id": venue.id, "name": venue.name, "num_upcoming_shows": len(retrieve_upcoming_shows({ "venue":venue }))} for venue in matching_venues]
  }
  return render_template('pages/search_venues.html', results=response, search_term=search_term)

@app.route('/venues/<int:venue_id>')
def show_venue(venue_id):

  venue = Venue.query.get(venue_id)
  if not venue:
    return abort(404)
  past_shows = retrieve_past_shows({"venue": venue })
  upcoming_shows = retrieve_upcoming_shows({ "venue": venue })
  data = {
    "id": venue.id,
    "name": venue.name,
    "genres": venue.genres,
    "address": venue.address,
    "city": venue.city,
    "state": venue.state,
    "phone": venue.phone,
    "website": venue.website,
    "facebook_link": venue.facebook_link,
    "seeking_talent": venue.seeking_talent,
    "image_link": venue.image_link,
    "past_shows": [transform_show(show) for show in past_shows],
    "upcoming_shows": [transform_show(show) for show in upcoming_shows],
    "past_shows_count": len(past_shows),
    "upcoming_shows_count": len(upcoming_shows),
  }
  return render_template('pages/show_venue.html', venue=data)

#  Create Venue
#  ----------------------------------------------------------------

@app.route('/venues/create', methods=['GET'])
def create_venue_form():
  form = VenueForm()
  return render_template('forms/new_venue.html', form=form)

@app.route('/venues/create', methods=['POST'])
def create_venue_submission():

  data = {
   key: request.form.get(key) for key in request.form if key != 'genres'
  }
  venue = Venue(**data)
  set_genre_list(venue, request.form.getlist('genres'))

  error=False
  safe_commit_session(venue, db)

  # on successful db insert, flash success
  if not error:
    flash('Venue ' + request.form['name'] + ' was successfully listed!')
  else:
    flash('An error occurred. Venue ' + data.name + ' could not be listed.')

  return render_template('pages/home.html')

@app.route('/venues/<venue_id>', methods=['DELETE'])
def delete_venue(venue_id):

  venue = Venue.query.get(venue_id)
  error = False
  try:
    db.session.delete(venue)
    db.session.commit()
  except:
    error = True
    db.session.rollback()
  finally:
    db.session.close()

  if error:
    flash('An error occurred. Venue ' + venue.name + ' could not be deleted.')
  else:
    flash('Venue ' + venue.name + ' deleted successfully.')
  # BONUS CHALLENGE: Implement a button to delete a Venue on a Venue Page, have it so that
  # clicking that button delete it from the db then redirect the user to the homepage
  return render_template('pages/home.html')

#  Artists
#  ----------------------------------------------------------------
@app.route('/artists')
def artists():
  data=[{
    "id": artist.id,
    "name": artist.name,
  } for artist in Artist.query.all()]
  return render_template('pages/artists.html', artists=data)

@app.route('/artists/search', methods=['POST'])
def search_artists():

  search_term=request.form.get('search_term', '')

  matching_artists= Artist.query.filter(Artist.name.ilike('%{}%'.format(search_term))).all()

  response={
    "count": len(matching_artists),
    "data": [{
      "id": artist.id,
      "name": artist.name,
      "num_upcoming_shows": len(retrieve_upcoming_shows({ "artist": artist })),
    } for artist in matching_artists]
  }
  return render_template('pages/search_artists.html', results=response, search_term=request.form.get('search_term', ''))

@app.route('/artists/<int:artist_id>')
def show_artist(artist_id):

  artist = Artist.query.get(artist_id)
  if not artist:
    return abort(404)
  data = transform_artist_detail(artist)
  return render_template('pages/show_artist.html', artist=data)

#  Update
#  ----------------------------------------------------------------
@app.route('/artists/<int:artist_id>/edit', methods=['GET'])
def edit_artist(artist_id):
  form = ArtistForm()
  artist = Artist.query.get(artist_id)
  artist_data=transform_artist_detail(artist)
  return render_template('forms/edit_artist.html', form=form, artist=artist_data)

@app.route('/artists/<int:artist_id>/edit', methods=['POST'])
def edit_artist_submission(artist_id):
  form = request.form
  artist = Artist.query.get(artist_id)
  artist.name = form.get('name', artist.name)
  artist.city = form.get('city', artist.city)
  artist.state = form.get('state', artist.state)
  artist.phone = form.get('phone', artist.phone)
  artist.facebook_link = form.get('facebook_link', artist.facebook_link)
  set_genre_list(artist, form.getlist('genres'))
  error = safe_commit_session(artist, db)
  if not error:
    artist = Artist.query.get(artist_id)
    flash('Artist ' + artist.name + ' edited successfully.')
  else:
    flash('Unable to edit artist ' + artist.name)

  return redirect(url_for('show_artist', artist_id=artist_id))

@app.route('/venues/<int:venue_id>/edit', methods=['GET'])
def edit_venue(venue_id):
  form = VenueForm()

  venue = Venue.query.get(venue_id)

  return render_template('forms/edit_venue.html', form=form, venue=venue)

@app.route('/venues/<int:venue_id>/edit', methods=['POST'])
def edit_venue_submission(venue_id):
  venue = Venue.query.get(venue_id)
  if not venue:
    return abort(404)
  form = request.form
  venue.name = form.get('name', venue.name)
  venue.phone = form.get('phone', venue.phone)
  venue.address = form.get('address', venue.address)
  venue.city = form.get('city', venue.city)
  venue.state = form.get('state', venue.state)
  venue.facebook_link = form.get('facebook_link', venue.facebook_link)
  set_genre_list(venue, form.getlist('genres'))

  error=False
  safe_commit_session(venue, db)

  # on successful db insert, flash success
  if not error:
    flash('Venue ' + form.get('name') + ' was successfully listed!')
  else:
    flash('An error occurred. Venue ' + form.get('name') + ' could not be listed.')
  return redirect(url_for('show_venue', venue_id=venue_id))

#  Create Artist
#  ----------------------------------------------------------------

@app.route('/artists/create', methods=['GET'])
def create_artist_form():
  form = ArtistForm()
  return render_template('forms/new_artist.html', form=form)

@app.route('/artists/create', methods=['POST'])
def create_artist_submission():
  # called upon submitting the new artist listing form
  form = request.form
  artist_data = {
    key: form.get(key) for key in form if key != 'genres'
  }
  artist = Artist(**artist_data)
  import pdb; pdb.set_trace()
  set_genre_list(artist, form.getlist('genres'))

  error = safe_commit_session(artist, db)
  if error:
    flash('Unable to add artist ' + artist_data.get("name"))
  else:
    flash('Artist ' + request.form['name'] + ' was successfully listed!')
  return render_template('pages/home.html')

#  Shows
#  ----------------------------------------------------------------

@app.route('/shows')
def shows():
  # displays list of shows at /shows
  data=[transform_show(show, "show") for show in Show.query.all()]
  return render_template('pages/shows.html', shows=data)

@app.route('/shows/create')
def create_shows():
  # renders form. do not touch.
  form = ShowForm()
  return render_template('forms/new_show.html', form=form)

@app.route('/shows/create', methods=['POST'])
def create_show_submission():
  # called to create new shows in the db, upon submitting new show listing form
  form = request.form
  show = Show(artist_id=form.get('artist_id'), venue_id=form.get('venue_id'), start_time=form.get('start_time'))

  error = safe_commit_session(show,db)
  if error:
    flash('Unable to add show')
  else:
    # on successful db insert, flash success
    flash('Show was successfully listed!')
  return render_template('pages/home.html')

@app.errorhandler(404)
def not_found_error(error):
    return render_template('errors/404.html'), 404

@app.errorhandler(500)
def server_error(error):
    return render_template('errors/500.html'), 500

if not app.debug:
    file_handler = FileHandler('error.log')
    file_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    )
    app.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('errors')

#----------------------------------------------------------------------------#
# Launch.
#----------------------------------------------------------------------------#

# Default port:
if __name__ == '__main__':
    app.run()

# Or specify port manually:
'''
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
'''


import tkinter
from shapely.geometry import Point, LineString
from shapely.geometry.polygon import Polygon
import math
from queue import PriorityQueue
import time

left_point = None
right_point = None

is_rightclicked = False
is_leftclicked = False

graph = {}

drawarray = []
draw_graph_array = []
draw_graph_bool = False

vertex = None
maparray = []

n = 0
m = 0

def map1():
    global maparray
    for i in range(len(maparray)):
        canvas.delete(maparray[i])
    global coordinates

    global is_leftclicked
    global is_rightclicked
    global leftclicked_id
    global rightclicked_id

    global left_point
    global right_point

    global drawarray

    if (is_leftclicked==True):
        canvas.delete(leftclicked_id)
    if (is_rightclicked==True):
        canvas.delete(rightclicked_id)
    is_leftclicked = False
    is_rightclicked = False
    left_point = None
    right_point = None

    for i in range(len(drawarray)):
        canvas.delete(drawarray[i])
    drawarray = []

    coordinates = []
    maparray = []
    global line

    with open("points.txt") as file:
        line = file.read().splitlines()

    for i in range(len(line)-1):
        a = line[i].split(" ")
        b = line[i+1].split(" ")
        coordinates.append((int(a[0]), int(a[1])))
        tmp = canvas.create_line(int(a[0]), int(a[1]), int(b[0]), int(b[1]), fill="black", width=5)
        maparray.append(tmp)
    coordinates.append((int(line[0].split(" ")[0]), int(line[0].split(" ")[1])))

def map2():
    global maparray
    for i in range(len(maparray)):
        canvas.delete(maparray[i])
    global coordinates

    global is_leftclicked
    global is_rightclicked
    global leftclicked_id
    global rightclicked_id

    global left_point
    global right_point

    global drawarray

    if (is_leftclicked==True):
        canvas.delete(leftclicked_id)
    if (is_rightclicked==True):
        canvas.delete(rightclicked_id)
    is_leftclicked = False
    is_rightclicked = False
    left_point = None
    right_point = None

    for i in range(len(drawarray)):
        canvas.delete(drawarray[i])
    drawarray = []

    coordinates = []
    maparray = []

    global line

    with open("points2.txt") as file:
        line = file.read().splitlines()

    for i in range(len(line)-1):
        a = line[i].split(" ")
        b = line[i+1].split(" ")
        coordinates.append((int(a[0]), int(a[1])))
        tmp = canvas.create_line(int(a[0]), int(a[1]), int(b[0]), int(b[1]), fill="black", width=5)
        maparray.append(tmp)
    coordinates.append((int(line[0].split(" ")[0]), int(line[0].split(" ")[1])))

def create_graph():
    global coordinates
    global graph
    global n
    global m
    n = 0
    m = 0
    graph = {}
    main_polygon = Polygon(coordinates)

    for i in range(len(coordinates)):
        graph[i]=[]
        n = n+1

    for i in range(len(coordinates)):
        for j in range(len(coordinates)):
            if (i!=j):
                m = m+1

                path = LineString([coordinates[i], coordinates[j]])
                point = path.interpolate(0.5)

                if not path.crosses(main_polygon):
                    if (main_polygon.contains(point) or abs(j-i)==1):
                        tmp1 = [j, math.sqrt((coordinates[i][0]-coordinates[j][0])**2 + (coordinates[i][1]-coordinates[j][1])**2)]
                        graph[i].append(tmp1)

def draw_graph():
    global vertex
    global graph
    global coordinates
    global n
    global m
    global draw_graph_array
    global draw_graph_bool

    if not draw_graph_bool:
        vertex['text'] = "Turn off graph drawing"
        draw_graph_bool = True
        main_polygon = Polygon(coordinates)
        for i in range(len(coordinates)):
            for j in range(len(coordinates)):
                if (i!=j):

                    path = LineString([coordinates[i], coordinates[j]])
                    point = path.interpolate(0.5)

                    if not path.crosses(main_polygon):
                        if (main_polygon.contains(point) or abs(j-i)==1):
                            tmp =canvas.create_line(coordinates[i][0], coordinates[i][1], coordinates[j][0], coordinates[j][1], fill="green", width=1)
                            draw_graph_array.append(tmp)
    else:
        vertex['text'] = "Turn on graph drawing"
        for i in range(len(draw_graph_array)):
            canvas.delete(draw_graph_array[i])
        draw_graph_array = []
        draw_graph_bool = False

def draw_line_right(event):
    global is_rightclicked
    global rightclicked_id

    global right_point
    global n
    global m

    global drawarray

    for i in range(len(drawarray)):
        canvas.delete(drawarray[i])
    drawarray = []

    x1=event.x-5
    y1=event.y-5
    x2=event.x+5
    y2=event.y+5
    x = event.x
    y = event.y
    tmppoint = Point(x, y)

    polygon = Polygon(coordinates)
    if polygon.contains(tmppoint):
        right_point = tmppoint
        if not is_rightclicked:
            rightclicked_id = canvas.create_oval(x1,y1,x2,y2,fill="green", outline="")
            is_rightclicked = True
        else:
            canvas.delete(rightclicked_id)
            rightclicked_id = canvas.create_oval(x1,y1,x2,y2,fill="green", outline="")

def draw_line_left(event):
    global is_leftclicked
    global leftclicked_id

    global left_point
    global n
    global m

    global drawarray

    for i in range(len(drawarray)):
        canvas.delete(drawarray[i])
    drawarray = []

    x1=event.x-5
    y1=event.y-5
    x2=event.x+5
    y2=event.y+5
    x = event.x
    y = event.y
    tmppoint = Point(x, y)

    polygon = Polygon(coordinates)

    if polygon.contains(tmppoint):
        left_point = tmppoint
        if not is_leftclicked:

            leftclicked_id = canvas.create_oval(x1,y1,x2,y2,fill="red", outline="")
            is_leftclicked = True

        else:
            canvas.delete(leftclicked_id)
            leftclicked_id = canvas.create_oval(x1,y1,x2,y2,fill="red", outline="")

def dijkstra():
    global n
    global m
    global drawarray

    start_time = time.time()
    if (is_leftclicked == True and is_rightclicked == True):
        print(right_point)
        print(left_point)
        print("Dijkstra")
        create_graph()

        graph[n] = []
        n=n+1
        graph[n] = []
        n=n+1

        polygon = Polygon(coordinates)
        for i in range(len(coordinates)-1):
            path = LineString([coordinates[i], right_point])
            if not path.crosses(polygon):
                tmp1 = [i, math.sqrt((coordinates[i][0]-right_point.x)**2 + (coordinates[i][1]-right_point.y)**2)]
                graph[n-2].append(tmp1)

                tmp2 = [n-2, math.sqrt((coordinates[i][0]-right_point.x)**2 + (coordinates[i][1]-right_point.y)**2)]
                graph[i].append(tmp2)
                #canvas.create_line(coordinates[i][0], coordinates[i][1], right_point.x, right_point.y, fill="blue", width=1)

        for i in range(len(coordinates)-1):
            path = LineString([coordinates[i], left_point])
            if not path.crosses(polygon):
                tmp1 = [i, math.sqrt((coordinates[i][0]-left_point.x)**2 + (coordinates[i][1]-left_point.y)**2)]
                graph[n-1].append(tmp1)

                tmp2 = [n-1, math.sqrt((coordinates[i][0]-left_point.x)**2 + (coordinates[i][1]-left_point.y)**2)]
                graph[i].append(tmp2)
                #canvas.create_line(coordinates[i][0], coordinates[i][1], left_point.x, left_point.y, fill="red", width=1)

        path = LineString([right_point, left_point])
        if not path.crosses(polygon):
            tmp1 = [n-1, math.sqrt((right_point.x-left_point.x)**2 + (right_point.y-left_point.y)**2)]
            graph[n-2].append(tmp1)

            tmp2 = [n-2, math.sqrt((right_point.x-left_point.x)**2 + (right_point.y-left_point.y)**2)]
            graph[n-1].append(tmp2)
            #canvas.create_line(right_point.x, right_point.y, left_point.x, left_point.y, fill="purple", width=1)

        start = n-2
        end = n-1
        visited = []
        distance = []
        par = []
        for i in range(n):
            visited.append(False)
            distance.append(float('inf'))
            par.append(None)
        distance[start] = 0
        pq = PriorityQueue()
        pq.put((0, start))
        while not pq.empty():
            (d, v) = pq.get()
            visited[v] = True
            for i in range(len(graph[v])):
                if not visited[graph[v][i][0]] and distance[v] + graph[v][i][1] < distance[graph[v][i][0]]:
                    distance[graph[v][i][0]] = distance[v] + graph[v][i][1]
                    par[graph[v][i][0]] = v
                    pq.put((distance[graph[v][i][0]], graph[v][i][0]))
        print(distance[end])
        distancetoend = distance[end]
        coordinates.append((right_point.x, right_point.y))
        coordinates.append((left_point.x, left_point.y))
        while par[end] != None:

            tmp = canvas.create_line(coordinates[par[end]][0], coordinates[par[end]][1], coordinates[end][0], coordinates[end][1], fill="purple", width=5)
            print(end, " ", par[end], " ", coordinates[end], " ", coordinates[par[end]])
            drawarray.append(tmp)
            end = par[end]
        coordinates.pop()
        coordinates.pop()
    elapsed_time = time.time() - start_time
    timetext['text'] = "Time Executed: " + "{:.2f}".format(elapsed_time) + " seconds"
    print(distance[end])
    distancetext['text'] = "Distance: " + "{:.2f}".format(distancetoend)

if __name__ == '__main__':

    window = tkinter.Tk()
    window.title("Shortest path GUI")
    window.geometry("1500x800")
    window['bg'] = 'white'
    btn_dijkstra = tkinter.Button(window, text="Find the shortest path", command=dijkstra, fg = 'black', bg = 'yellow')
    btn_dijkstra.place(rely=0.05, relx=0.3, anchor="center")

    vertex = tkinter.Button(window, text="Turn on graph drawing", command=draw_graph, fg = 'black', bg = 'yellow')
    vertex.place(rely=0.05, relx=0.4, anchor="center")

    map1 = tkinter.Button(window, text="Map 1", command=map1, fg = 'black', bg = 'yellow')
    map1.place(rely=0.05, relx=0.5, anchor="center")

    map2 = tkinter.Button(window, text="Map 2", command=map2, fg = 'black', bg = 'yellow')
    map2.place(rely=0.05, relx=0.6, anchor="center")

    canvas = tkinter.Canvas(window, width=1500, height=700, bg="white")
    canvas.place(relx=0.5, rely=0.6, anchor=tkinter.CENTER)

    timetext = tkinter.Label(window, text="Time Executed: ")
    timetext.place(relx=0.4, rely=0.1, anchor=tkinter.CENTER)

    distancetext = tkinter.Label(window, text="Distance: ")
    distancetext.place(relx = 0.6, rely=0.1, anchor=tkinter.CENTER)

    coordinates = []

    global line
    with open("points.txt") as file:
        line = file.read().splitlines()

    for i in range(len(line)-1):
        a = line[i].split(" ")
        b = line[i+1].split(" ")
        coordinates.append((int(a[0]), int(a[1])))
        tmp = canvas.create_line(int(a[0]), int(a[1]), int(b[0]), int(b[1]), fill="black", width=5)
        maparray.append(tmp)
    coordinates.append((int(line[0].split(" ")[0]), int(line[0].split(" ")[1])))

    #new thing here

    create_graph()

    canvas.bind('<Button-1>', draw_line_left)
    canvas.bind('<Button-3>', draw_line_right)

    #display timer dijkstra in the window

    window.mainloop()


from datetime import datetime, timedelta
import os
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import (StageToRedshiftOperator, LoadFactOperator,
                                LoadDimensionOperator, DataQualityOperator, CleanCsvOperator, PostgresOperator)
from helpers import SqlQueries

# AWS_KEY= os.environ.get('AWS_KEY')
# AWS_S ECRET = os.environ.get('AWS_SECRET')

default_args = {
    'owner': 'udacity',
    'start_date': datetime(2020, 3, 28),
    'depends_on_past': False,
    'retries': 0,
    'retry_delay': timedelta(minutes=5),
    'catchup': False,
    'email_on_retry': False
}

dag = DAG('udac_capstone_project',
          default_args=default_args,
          description='Load and transform data in Redshift with Airflow',
          start_date=datetime.now(),
          schedule_interval='0 * * * *'
        )

start_operator = DummyOperator(task_id='Begin_execution',  dag=dag)

clean_data_csv = CleanCsvOperator(
    task_id="clean_data_csv",
    dag=dag,
    aws_credentials_id='aws_credentials',
    s3_bucket='audacity-capstone-luke',
    s3_key='covid_19_data.csv',
    region='ap-southeast-2',
    datecols=[]
)

clean_case_csv = CleanCsvOperator(
    task_id="clean_case_csv",
    dag=dag,
    aws_credentials_id='aws_credentials',
    s3_bucket='audacity-capstone-luke',
    s3_key='COVID19_line_list_data.csv',
    region='ap-southeast-2',
    datecols=['reporting date', 'symptom_onset', 'hosp_visit_date', 'exposure_start', 'exposure_end']
)

create_tables = PostgresOperator(
    task_id="create_tables",
    dag=dag,
    postgres_conn_id="redshift",
    sql="create_tables.sql"
)

stage_cases_to_redshift = StageToRedshiftOperator(
    task_id='Stage_cases',
    dag=dag,
    redshift_conn_id='redshift',
    aws_credentials_id='aws_credentials',
    table='staging_cases',
    s3_bucket='audacity-capstone-luke',
    s3_key='COVID19_line_list_data.csv',
    region='ap-southeast-2'
)

stage_data_to_redshift = StageToRedshiftOperator(
    task_id='Stage_data',
    dag=dag,
    redshift_conn_id='redshift',
    aws_credentials_id='aws_credentials',
    table='staging_data',
    s3_bucket='audacity-capstone-luke',
    s3_key='covid_19_data.csv',
    region='ap-southeast-2'
)

load_cases_table = LoadFactOperator(
    task_id='Load_cases_fact_table',
    dag=dag,
    redshift_conn_id='redshift',
    table='fact_cases',
    select_sql=SqlQueries.fact_cases_table_insert
)

load_patients_table = LoadFactOperator(
    task_id='Load_patients_fact_table',
    dag=dag,
    redshift_conn_id='redshift',
    table='patientinfo',
    select_sql=SqlQueries.patient_info_table_insert
)

load_data_table = LoadFactOperator(
    task_id='Load_data_fact_table',
    dag=dag,
    redshift_conn_id='redshift',
    table='fact_data',
    select_sql=SqlQueries.fact_data_table_insert
)

load_location_dimension_table = LoadDimensionOperator(
    task_id='Load_location_dim_table',
    dag=dag,
    redshift_conn_id='redshift',
    table='dim_locations',
    cols='(location, country)',
    select_sql=SqlQueries.dim_location_table_insert
)

load_source_dimension_table = LoadDimensionOperator(
    task_id='Load_source_dim_table',
    dag=dag,
    redshift_conn_id='redshift',
    table='dim_sources',
    cols='(sourcename, link)',
    select_sql=SqlQueries.dim_sources_table_insert
)

load_time_dimension_table = LoadDimensionOperator(
    task_id='Load_time_dim_table',
    dag=dag,
    redshift_conn_id='redshift',
    table='dim_times',
    cols='',
    select_sql=SqlQueries.time_table_insert
)

run_quality_checks = DataQualityOperator(
    task_id='Run_data_quality_checks',
    dag=dag,
    redshift_conn_id='redshift',
    tables=["fact_cases", "fact_data", "patientinfo", "dim_locations", "dim_times", "dim_sources"]
)

end_operator = DummyOperator(task_id='Stop_execution',  dag=dag)

start_operator >> create_tables
create_tables >> clean_case_csv >> stage_cases_to_redshift
create_tables >> clean_data_csv >> stage_data_to_redshift
stage_cases_to_redshift >> load_location_dimension_table
stage_data_to_redshift >> load_location_dimension_table
stage_cases_to_redshift >> load_source_dimension_table
load_location_dimension_table >> load_patients_table
load_source_dimension_table >> load_cases_table
load_location_dimension_table >> load_data_table
load_data_table >> load_time_dimension_table
load_cases_table >> load_time_dimension_table
load_patients_table >> load_time_dimension_table
load_time_dimension_table >> run_quality_checks
run_quality_checks >> end_operator


from .conv_bc01 import *
import cudarray as ca

class ConvBC01(object):
    def __init__(self, padding, strides):
        self.padding = padding
        self.strides = strides

    def fprop(self, imgs, filters, convout=None):
        b, c, img_h, img_w = imgs.shape
        f, c_filters, filter_h, filter_w = filters.shape
        if c != c_filters:
            raise ValueError('channel mismatch')
        if imgs.dtype != filters.dtype:
            raise ValueError('dtype mismatch')

        convout_shape = self.output_shape(imgs.shape, f, (filter_h, filter_w))
        if convout is None:
            convout = ca.empty(convout_shape, dtype=imgs.dtype)
        else:
            if convout.shape != convout_shape:
                raise ValueError('convout.shape does not match result')
            if convout.dtype != imgs.dtype:
                raise ValueError('dtype mismatch')

        conv_bc01(imgs=imgs,
                  filters=filters,
                  padding=self.padding,
                  strides=self.strides,
                  convout=convout)

        self.last_imgs = imgs

        return convout

    def bprop(self, imgs, filters, convout_d, to_filters=True, to_imgs=True,
              filters_d=None, imgs_d=None):
        if imgs is None:
            imgs = self.last_imgs
        b, c, _, _ = imgs.shape
        f, c_filters, _, _ = filters.shape
        b_convout, f_convout, _, _ = convout_d.shape

        if b != b_convout:
            raise ValueError('batch mismatch')
        if f != f_convout:
            raise ValueError('filter mismatch')
        if c != c_filters:
            raise ValueError('channel mismatch')

        if imgs.dtype != filters.dtype != convout_d.dtype:
            raise ValueError('dtype mismatch')

        if filters_d is None:
            filters_d = ca.empty(filters.shape, dtype=filters.dtype)

        if imgs_d is None:
            imgs_d = ca.empty(imgs.shape, dtype=imgs.dtype)

        conv_bc01_bprop(imgs=imgs,
                        convout_d=convout_d,
                        filters=filters,
                        padding=self.padding,
                        strides=self.strides,
                        imgs_grad=imgs_d,
                        filters_grad=filters_d)

        return filters_d, imgs_d

    def output_shape(self, imgs_shape, n_filters, filter_shape):
        b, _, img_h, img_w = imgs_shape
        out_shape = ((img_h + 2*self.padding[0] - filter_shape[0])
                     / self.strides[0] + 1,
                     (img_w + 2*self.padding[1] - filter_shape[1])
                     / self.strides[1] + 1)
        return (b, n_filters) + out_shape


from typing import Any, List, Optional

from wire.core.container import Container
from wire.core.settings import BaseAppSettings

def prometheus_metrics_provider(
    container: Container[BaseAppSettings],
) -> Optional[List[Any]]:
    """Add prometheus metrics to your application."""
    if not container.settings.telemetry.metrics_enabled:
        return None

    from prometheus_fastapi_instrumentator import Instrumentator

    instrumentor = Instrumentator(
        excluded_handlers=[
            path.strip() for path in container.settings.telemetry.ignore_path.split(",")
        ]
    )
    instrumentor.instrument(container.app).expose(
        container.app,
        endpoint=container.settings.telemetry.metrics_path,
        include_in_schema=True,
        tags=["Telemetry"],
    )

    return [instrumentor]


from flask import Flask
from flask_restful import Resource, Api, reqparse, abort

app = Flask(__name__)
api = Api(app)

info = {}

parser = reqparse.RequestParser()
parser.add_argument("phone", type=int, help="Number is required", required=True)
parser.add_argument("age", type=int, help="Age must be an integer")

class HelloWorld(Resource):
    def get(self):
        return {"Hello": "World"}

def not_found(name):
    if name not in info:
        abort(404, message='Cannot find friend')

def dupe_entry(name):
    if name in info:
        abort(409, message='friend already exists')

class Basics(Resource):
    # def get(self, name):
    #     return {"Hello": name}
    def get(self, name):
        not_found(name)
        return info[name], 200

    def post(self, name):
        dupe_entry(name)
        args = parser.parse_args()
        info[name] = args
        return info[name], 201

    def put(self, name):
        args = parser.parse_args()
        info[name] = args
        return info[name], 201

    def delete(self,name):
        del info[name]
        return '', 204

api.add_resource(HelloWorld, '/hi')
api.add_resource(Basics, '/basic/<string:name>')

if __name__ == '__main__':
    app.run(debug=True)


import sys
import string
import tokenize
import re
from utils import *

def simpleLinePreprocessing(line):
    replacePunctuation = str.maketrans(string.punctuation, ' '*len(string.punctuation))
    newLine = line.translate(replacePunctuation).lower()
    newLine = ' '.join(newLine.split())
    return newLine

def advancedLinePreprocessing(line):
    replacePunctuation = str.maketrans(string.punctuation, ' '*len(string.punctuation))
    newLine = line.translate(replacePunctuation).lower()
    # remove emails
    newLine = re.sub( r'([e{0,1}[-]{0,1}mail]){0,1}[a-z0-9:.]+@[a-z0-9:.]+', '', newLine)
    # replace punctuation with spaces
    replacePunctuation = str.maketrans(string.punctuation, ' '*len(string.punctuation))
    # reduce multiple spaces
    newLine = ' '.join(newLine.split())
    # split numbers and words with a space
    newLine = re.sub( r'([a-zA-Z])([0-9])', r'\1 \2', newLine)
    newLine = re.sub( r'([0-9])([a-zA-Z])', r'\1 \2', newLine)
    # apply pseudo dictionary
    for key, listOfValues in preprocessingDict.items():
        for value in listOfValues:
            newLine = newLine.replace(value, key)

    # remove telephone numbers
    newLine = re.sub( r'(tel|fax)([ 0-9]*)', '', newLine)
    # sort alphabetically
    items = sorted(newLine.split())
    newLine = ''.join(items)

    return newLine

def simplifyLines(lines):
    simplifiedLines = []

    for line in lines:
        # newLine = simpleLinePreprocessing(line)
        newLine = advancedLinePreprocessing(line)
        simplifiedLines.append(newLine)

    print('Lines simplified')
    return simplifiedLines

def generateStopWords(lines):
    numberOfLines = len(lines)
    print('Number of lines:',str(numberOfLines))

    simplifiedLines = simplifyLines(lines)

    stopWordsSet = set()
    wordsSet = set()

    for line in simplifiedLines:
        for word in line.split():
            wordsSet.add(word)

    print('Propositions of stop words:')

    for word in wordsSet:
        linesCounter = 0
        for line in simplifiedLines:
            if re.search(r"\b{0}\b".format(word), line):
                linesCounter +=1
        if linesCounter > numberOfLines/10:
            stopWordsSet.add(word)
            print(word, str(linesCounter))

    return stopWordsSet

def removeStopWordsFromLines(stopWords, lines):
    linesWithoutStopWords = []
    for line in lines:
        newLine = line
        for word in stopWords:
            newLine = re.sub(r'\b{0}\b'.format(word), '', newLine)
            newLine = ' '.join(newLine.split())
        linesWithoutStopWords.append(newLine)

    return linesWithoutStopWords

def readLinesFromFile(filename):
    lines = []
    with open(filename, 'r', newline='', encoding='latin2') as sourcefile:
        lines = sourcefile.readlines()
    return lines

def performPreprocessing(sourcefile):
    lines = readLinesFromFile(sourcefile)
    simplifiedLines = simplifyLines(lines)
    # stopWords = generateStopWords(simplifiedLines)
    stopWords = ['no','o','ltd','road','co','sp','a','fax','ul','tel','z','of']
    additionalStopWords = ['email', 'e mail', 'mail' 'st', 'str', 'street', 'zip code', 'zip']
    stopWords.extend(additionalStopWords)
    linesWithoutStopWords = removeStopWordsFromLines(stopWords, simplifiedLines)
    return linesWithoutStopWords


#!/usr/bin/env python
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
import keras
import matplotlib.pyplot as plt
import pandas as pd
import time

from tkinter import ttk
from tkinter import filedialog
from tkinter import *
from PIL import Image, ImageTk
import os

# global parameters1
global timestep
timestep = 5
global batch_size
batch_size = 1
global train_length
train_length = 1300
global epochs
epochs = 5

# global parameters2
global unit1
unit1 = 4
global unit2
unit2 = 4
global unit3
unit3 = 168

# global parameters
global adam_lr
adam_lr = 0.003
global loss_func
loss_func = 'mean_squared_error'
global file_path
file_path = "./dt1.txt"

global data_from
data_from = 0

global data_to
data_to = 2000

global data_from_column
data_from_column = 1

global data_to_column
data_to_column = 1

global dataset
dataset = []

# Windows
root = Tk()
root.title('Deep Learning Platform')
root.resizable(False, False)
windowWidth = 1400
windowHeight = 1400
screenWidth, screenHeight = root.maxsize()

# load data set
def load_dataset():
    global file_path
    file_path = filedialog.askopenfilename()
    if (os.path.splitext(file_path)[-1] == ".txt"):
        for line in open(file_path):
            line = line.strip()
            dataset.append(float(line))
    if (os.path.splitext(file_path)[-1] == ".csv"):
        cvs_reader = pd.read_csv(file_path)
        # label = ttk.Text(monty3, width=80, text=cvs_reader.head(22))
        label = Text(monty5, width=80, height=30)
        label.insert(INSERT, cvs_reader)
        label.grid(row=0, column=0)
        train_set = cvs_reader.values
        for line in train_set:
            # line = line.strip()
            dataset.append(float(line))
    if (os.path.splitext(file_path)[-1] == ".xlsx"):
        xls_reader = pd.read_excel(file_path)
        #  label = ttk.Text(monty3, width=80, text=xls_reader.head(220))
        label = Text(monty5, width=80, height=30)
        label.insert(INSERT, xls_reader)
        label.grid(row=0, column=0)
        train_set = xls_reader.values
        for line in train_set:
            #  line = line.strip()
            dataset.append(float(line))

# Pages
tabControl = ttk.Notebook(root)
tab2 = ttk.Frame(tabControl)
tabControl.add(tab2, text='DATA LOAD')
tabControl.pack(expand=1, fill='both')
tab1 = ttk.Frame(tabControl)
tabControl.add(tab1, text='PARAMETER CONTROL')
tabControl.pack(expand=1, fill='both')

# tags
monty1 = ttk.LabelFrame(tab1, text='BASIC_PARA', width=500, height=100)
monty1.grid(column=0, row=0, padx=5, pady=20)
monty2 = ttk.LabelFrame(tab1, text='OPERATION', width=500, height=100)
monty2.grid(column=0, row=2, columnspan=2, padx=5, pady=20)
monty3 = ttk.LabelFrame(tab1, text='RESULT_SHOW', width=500, height=100)
monty3.grid(column=1, row=0, rowspan=2, padx=5, pady=20)

monty5 = ttk.LabelFrame(tab2, text='DATA_SHOW', width=650, height=550)
monty5.grid(column=1, row=0, rowspan=3, padx=5, pady=20)
monty4 = ttk.LabelFrame(tab2, text='DATA_CHOSEN_ROW', width=200, height=50)
monty4.grid(column=0, row=0, padx=5)
monty6 = ttk.LabelFrame(tab2, text='DATA_CHOSEN_COLUMN', width=200, height=50)
monty6.grid(column=0, row=1, padx=5)
monty7 = ttk.LabelFrame(tab2, text='DATA_LOAD', width=200, height=50)
monty7.grid(column=0, row=2, padx=5)

# Parameters1
var_steptime = StringVar()
var_steptime.set(timestep)
text_timestep_lable = StringVar()

var_batch_size = StringVar()
var_batch_size.set(batch_size)
text_batchsize_lable = StringVar()

var_train_length = StringVar()
var_train_length.set(train_length)
text_train_length_label = StringVar()

var_epochs = StringVar()
var_epochs.set(epochs)
text_epochs_label = StringVar()

# Parameters2
var_unit1 = StringVar()
var_unit1.set(unit1)
text_unit1_lable = StringVar()

var_unit2 = StringVar()
var_unit2.set(unit2)
text_unit2_lable = StringVar()

var_unit3 = StringVar()
var_unit3.set(unit3)
text_unit3_label = StringVar()

# Parameters3
var_adam_lr = StringVar()
var_adam_lr.set(adam_lr)
text_adam_lr_label = StringVar()

var_loss_func = StringVar()

# Parameters4
var_data_from = StringVar()
var_data_from.set(data_from)
text_data_from = StringVar()

var_data_to = StringVar()
var_data_to.set(data_to)
text_data_to = StringVar()

var_data_from_column = StringVar()
var_data_from_column.set(data_from_column)
text_data_from_column = StringVar()

var_data_to_column = StringVar()
var_data_to_column.set(data_to_column)
text_data_to_column = StringVar()

var_adam_lr = StringVar()
var_adam_lr.set(adam_lr)
text_adam_lr_label = StringVar()

def show(content):
    if content.isdigit():
        return True
    else:
        return False

show_com = root.register(show)

# Entry1
entry_steptime = Entry(monty1, textvariable=var_steptime, width=10, validate='key',
                       validatecommand=(show_com, '%P')).grid(row=0, column=2, pady=5)
lb1 = Label(monty1, text='timestep', width=13).grid(row=0, column=1, pady=5)
entry_batch_size = Entry(monty1, textvariable=var_batch_size, width=10, validate='key',
                         validatecommand=(show_com, '%P')).grid(row=1, column=2, pady=5)
lb2 = Label(monty1, width=13, text='batch_size').grid(row=1, column=1, pady=10)
entry_train_length = Entry(monty1, textvariable=var_train_length, width=10, validate='key',
                           validatecommand=(show_com, '%P')).grid(row=2, column=2, pady=5)
lb3 = Label(monty1, width=13, text='train_length').grid(row=2, column=1, pady=5)

entry_epochs = Entry(monty1, textvariable=var_epochs, width=10, validate='key',
                     validatecommand=(show_com, '%P')).grid(row=3, column=2, pady=5)
lb4 = Label(monty1, width=13, text='epochs').grid(row=3, column=1, pady=5)

entry_adam_lr = Entry(monty1, textvariable=var_adam_lr, width=10, validate='key').grid(row=4, column=2, pady=5)
lb3 = Label(monty1, width=13, text='adam_lr').grid(row=4, column=1, pady=5)

loss_funcChosen = ttk.Combobox(monty1, width=20, textvariable=var_loss_func)
loss_funcChosen['values'] = (
    'mean_squared_error', 'mean_absolute_error', 'squared_hinge', 'binary_crossentropy', 'mape', 'msle', 'hinge',
    'categorical_crossentropy')
loss_funcChosen.grid(row=5, column=1, columnspan=2, pady=5)
loss_funcChosen.current(0)
loss_funcChosen.config(state='readonly')
# Entry2
entry_unit1 = Entry(monty1, textvariable=var_unit1, width=10, validate='key',
                    validatecommand=(show_com, '%P')).grid(row=6, column=2, pady=5)
lb1 = Label(monty1, text='Embedding', width=13).grid(row=6, column=1, pady=5)
entry_unit2 = Entry(monty1, textvariable=var_unit2, width=10, validate='key',
                    validatecommand=(show_com, '%P')).grid(row=7, column=2, pady=5)
lb2 = Label(monty1, width=13, text='Hidden').grid(row=7, column=1, pady=5)
entry_unit3 = Entry(monty1, textvariable=var_unit3, width=10, validate='key',
                    validatecommand=(show_com, '%P')).grid(row=8, column=2, pady=5)
lb3 = Label(monty1, width=13, text='Dense').grid(row=8, column=1, pady=5)

# Entry 3
entry_data_from = Entry(monty4, textvariable=var_data_from, width=10, validate='key',
                        validatecommand=(show_com, '%P')).grid(row=0, column=2, pady=5)
lb1 = Label(monty4, text='From', width=13).grid(row=0, column=1, pady=5)

entry_data_to = Entry(monty4, textvariable=var_data_to, width=10, validate='key',
                      validatecommand=(show_com, '%P')).grid(row=1, column=2, pady=5)
lb1 = Label(monty4, text='To', width=13).grid(row=1, column=1, pady=5)

# Entry 4
entry_data_from_column = Entry(monty6, textvariable=var_data_from_column, width=10, validate='key',
                               validatecommand=(show_com, '%P')).grid(row=0, column=2, pady=5)
lb1 = Label(monty6, text='From', width=13).grid(row=0, column=1, pady=5)

entry_data_to_column = Entry(monty6, textvariable=var_data_to_column, width=10, validate='key',
                             validatecommand=(show_com, '%P')).grid(row=1, column=2, pady=5)
lb1 = Label(monty6, text='To', width=13).grid(row=1, column=1, pady=5)

# var_modify
def var_modify():
    global timestep
    timestep = int(var_steptime.get())
    global batch_size
    batch_size = int(var_batch_size.get())
    global train_length
    train_length = int(var_train_length.get())
    global epochs
    epochs = int(var_epochs.get())
    global unit1
    unit1 = int(var_unit1.get())
    global unit2
    unit2 = int(var_unit2.get())
    global unit3
    unit3 = int(var_unit3.get())

def conf_selected():
    global data_from
    data_from = int(var_data_from.get())
    global data_to
    data_to = int(var_data_to.get())

    # global adam_lr
    # adam_lr = float(var_unit3.get())
    # global loss_func
    # loss_func = var_loss_func.get()

# Figure Show
global IMG
IMG = []
global counter
counter = 0
global label
im = Image.open('ai.jpeg')
img = ImageTk.PhotoImage(im)
label = Label(monty3, image=img)
label.grid(row=0, column=0)

# RNN Training Function
def training():
    im = Image.open('ai.jpeg')
    img = ImageTk.PhotoImage(im)
    label = Label(monty3, image=img)
    label.grid(row=0, column=0)

    RNN_units = [unit1, unit2, unit3]  # 442
    data_length = train_length + timestep + RNN_units[2]
    test_length = timestep + RNN_units[2]

    global dataset
    dataset = dataset[data_from:data_to]
    date = []
    for line in open("./dt2.txt", "r"):
        line = line.strip()
        date.append(line)

    len1 = data_length + RNN_units[2] + timestep - 1
    len2 = len(dataset)
    dataset = dataset[(len2 - len1):len2]
    length = len(dataset)
    dataset = np.array(dataset)
    old_dataset = dataset.copy()
    dataset = (dataset - np.min(dataset)) / (max(dataset) - min(dataset))

    values = []
    labels = []
    for i in range(length - timestep - RNN_units[2] + 1):
        temp1 = dataset[i:i + timestep]
        temp2 = dataset[i + timestep:i + timestep + RNN_units[2]]
        values.append(temp1)
        labels.append(temp2)
    print(len(values))
    x_train = values[0:train_length]
    x_test = values[(train_length):train_length + timestep + RNN_units[2]]
    y_train = labels[0:train_length]
    y_test = labels[(train_length):train_length + timestep + RNN_units[2]]

    x_train = np.reshape(x_train, (train_length, timestep, 1))
    y_train = np.reshape(y_train, (train_length, RNN_units[2]))
    x_test = np.reshape(x_test, (timestep + RNN_units[2], timestep, 1))
    y_test = np.reshape(y_test, (timestep + RNN_units[2], RNN_units[2]))

    print(x_train.shape)
    model = Sequential()
    model.add(LSTM(RNN_units[0], input_shape=(timestep, 1), return_sequences=True))
    model.add(LSTM(RNN_units[1], return_sequences=False))
    model.add(Dense(RNN_units[2]))
    model.summary()
    adam = keras.optimizers.adam(lr=adam_lr)

    model.compile(loss=loss_func, optimizer=adam, metrics=['accuracy'])
    history = model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2, verbose=1)

    trainpredict = model.predict(x_test, verbose=1, batch_size=batch_size)

    trainpredict = trainpredict * (max(old_dataset) - min(old_dataset)) + min(old_dataset)
    y_test = y_test * (max(old_dataset) - min(old_dataset)) + min(old_dataset)

    y = old_dataset[timestep + train_length:timestep + train_length + RNN_units[2]]
    print(trainpredict.shape)
    print(y_test.shape)
    print(len(y_test[0]))

    plt.clf()
    # plot prediction and real result
    fig = plt.figure(0)
    # plt.plot(range(168),y_test[0],'ro-')
    # plt.plot(range(168),trainpredict[0],'g*:')
    #

    plt.plot(range(unit3), y_test[0], 'ro-')
    plt.plot(range(unit3), trainpredict[0], 'g*:')
    plt.legend(('real', 'pred'), loc='upper right')
    plt.savefig('3.png')
    plt.clf()

    fig = plt.figure(1)
    plt.title("Intend Perception Accuracy", fontproperties="Times New Roman")
    plt.ylabel("Intend Encode", fontproperties="Times New Roman")
    plt.xlabel("Epoch", fontproperties="Times New Roman")
    plt.plot(range(timestep + unit3), y_test[:, 0], 'ro-')
    plt.plot(range(timestep + unit3), trainpredict[:, 0], 'g*:')
    plt.legend(('real', 'pred'), loc='upper right')
    plt.savefig('1.png')
    plt.clf()

    # plot train process
    fig = plt.figure(2)
    plt.plot(history.history['acc'], label='training acc')
    plt.plot(history.history['val_acc'], label='val acc')
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(loc='lower right')
    plt.savefig('2.png')

    clearIMG()
    loadFigure()
    dataset = []

def clearIMG():
    global IMG
    IMG = []

def loadFigure():
    for i in range(1, 4):
        im = Image.open(str(i) + '.png')
        img = ImageTk.PhotoImage(im)
        IMG.append(img)
        counter = 0
        label = Label(monty3, image=IMG[counter])
    label.grid(row=0, column=0)

def chimg():
    global label
    global counter
    if counter < 1:
        counter += 1
    else:
        counter = 0
    label.destroy()
    label = Label(monty3, image=IMG[counter])
    label.grid(row=0, column=0)

def figure_config():
    counter = 2
    label = Label(monty3, image=IMG[counter])
    label.grid(row=0, column=0)

# Operation
Button(monty7, text='LOAD DATASET', width=15, command=load_dataset, activeforeground='white',
       activebackground='green').grid(row=0, column=0, padx=20, pady=10)
Button(monty7, text='CONF SELECT', width=15, command=conf_selected, activeforeground='white',
       activebackground='green').grid(row=1, column=0, padx=20, pady=10)

Button(monty2, text='MODIFY PARAMETERS', width=15, command=var_modify, activeforeground='white',
       activebackground='green').grid(row=0, column=1, padx=26, pady=10)
Button(monty2, text='START TRAINING', width=15, command=training, activeforeground='white',
       activebackground='green').grid(row=0, column=2, padx=26, pady=10)
Button(monty2, text='NEXT RESULT', width=15, command=chimg, activeforeground='white', activebackground='green').grid(
    row=0, column=3, padx=26, pady=10)
Button(monty2, text='FIGURE CONFIG', width=15, command=figure_config, activeforeground='white',
       activebackground='green').grid(row=0, column=4, padx=26, pady=10)
mainloop()


"""
# Title : PySpark Script - Create Parquet
# Description : This script is used to read a CSV file, clean it and persist it to Parquet file
# Usage : spark-submit write-parquet.py
"""

# First import the neccesary modules
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, TimestampType, DecimalType
import sys,logging
from datetime import datetime

# Logging configuration
formatter = logging.Formatter('[%(asctime)s] %(levelname)s @ line %(lineno)d: %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(handler)

# Schema Configuration
# Here we define a schema for the CSV File read
# If a record is not compatible with the CSV, a null value is read

schema = StructType([
    StructField("trasaction_timestamp", TimestampType(), True),
    StructField("transaction_amount", DecimalType(4, 4), True),
    StructField("transaction_channel", StringType(), True)])

# current time variable to be used for logging purpose
dt_string = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")

AppName = "Spark-Project"

def main():

    # Start spark code
    spark = SparkSession.builder.appName(AppName+"_"+str(dt_string)).getOrCreate()
    spark.sparkContext.setLogLevel("ERROR")
    logger.info("Starting spark application")

    # Read CSV File into a Spark Dataframe
    logger.info("Reading CSV File")
    df = spark.read.load('hdfs://localhost:9000/files/data.csv', format="csv", sep=",", header="false", schema=schema)

    # Preview Spark Dataframe (for the project's purposes we use df.show(200) to see all records)
    logger.info("Previewing CSV File Data")
    print(df.show(10))

    # Clean and Transform the Spark Dataframe
    # When string (and generally a data type) is transformed to timestamp (to another data type) and doesn't match timestamp (this data type) format null is returned

    # Define the wanted values for the transaction_channel column
    # Assumption: Only Call and Email Values valid
    type_list = ["Call", "Email"]

    # Keep only the rows that have these values
    df = df.filter(df["transaction_channel"].isin(type_list))

    # Drop the rows with null
    df = df.na.drop()

    logger.info("Ending spark application")

    # Persist to parquet file, overwrite if already exists, and save it to HDFS
    df.write.mode("overwrite").parquet("/files/test")

    spark.stop()
    return None

# Starting point for PySpark
if __name__ == '__main__':
    main()
    sys.exit()


import serial
import time

def serialWriteInt(ser, value):
	'''
	Send value to serial device and delays for buffering of target device.
	Parameters:
		ser - Serial. Target device object.
		value - Interger. Number to be sent.
	'''
	ser.write(str(value).encode('utf-8'))
	print('Serial write: ' + str(value))
	time.sleep(0.002 * len(str(value)))

def main():
	ser = serial.Serial('/dev/ttyACM0', 9600)
	x = 0
	while True:
		# Rising edge
		while x<255:
			x+=5
			serialWriteInt(ser, x)

		# Falling edge
		while x>0:
			x-=5
			serialWriteInt(ser, x)

if __name__ == '__main__':
	main()


import os
import time
import logging
from datetime import datetime

from workflow.notify import notify
from workflow.background import is_running

from mstodo.util import wf_wrapper

log = logging.getLogger(__name__)
wf = wf_wrapper()

def sync(background=False):
    log.info('running mstodo/sync')
    from mstodo.models import base, task, user, taskfolder, hashtag
    from peewee import OperationalError

    # If a sync is already running, wait for it to finish. Otherwise, store
    # the current pid in alfred-workflow's pid cache file
    if not background:
        if is_running('sync'):
            wait_count = 0
            while is_running('sync'):
                time.sleep(.25)
                wait_count += 1

                if wait_count >= 2:
                    notify(
                        title='Please wait...',
                        message='The workflow is making sure your tasks are up-to-date'
                    )

            return False

        notify(
            title='Manual sync initiated',
            message='The workflow is making sure your tasks are up-to-date'
        )

        pidfile = wf.cachefile('sync.pid')
        with open(pidfile, 'w', encoding="utf-8") as file_obj:
            #@TODO check if this needs to be byte-written? May be due to pickling the program state?
            # file_obj.write(os.getpid().to_bytes(length=4, byteorder=sys.byteorder))
            file_obj.write(str(os.getpid()))

    base.BaseModel._meta.database.create_tables([
        taskfolder.TaskFolder,
        task.Task,
        user.User,
        hashtag.Hashtag
    ], safe=True)

    # Perform a query that requires the latest schema; if it fails due to a
    # mismatched scheme, delete the old database and re-sync
    try:
        task.Task.select().where(task.Task.recurrence_count > 0).count()
        hashtag.Hashtag.select().where(hashtag.Hashtag.tag == '').count()
    except OperationalError:
        base.BaseModel._meta.database.close()
        wf.clear_data(lambda f: 'mstodo.db' in f)

        # Make sure that this sync does not try to wait until its own process
        # finishes
        sync(background=True)
        return

    first_sync = False

    try:
        # get root item from DB. If it doesn't exist then make this the first sync.
        user.User.get()
    except user.User.DoesNotExist:
        first_sync = True
        wf.cache_data('last_sync',datetime.utcnow())
        notify(
            title='Please wait...',
            message='The workflow is syncing tasks for the first time'
        )

    user.User.sync(background=background)
    taskfolder.TaskFolder.sync(background=background)
    if first_sync:
        task.Task.sync_all_tasks(background=background)
    else:
        task.Task.sync_modified_tasks(background=background)
    hashtag.Hashtag.sync(background=background)
    #@TODO move this into a child sync of the relevant tasks once bugfix is completed

    if first_sync:
        notify(
            title='Initial sync has completed',
            message='All of your tasks are now available for browsing'
        )

    log.debug('First sync: ' + str(first_sync))
    log.debug('Last sync time: ' + str(wf.cached_data('last_sync',max_age=0)))
    wf.cache_data('last_sync',datetime.utcnow())
    log.debug('This sync time: ' + str(wf.cached_data('last_sync')))
    return True

def background_sync():
    from workflow.background import run_in_background
    task_id = 'sync'

    # Only runs if another sync is not already in progress
    run_in_background(task_id, [
        '/usr/bin/env',
        'python3',
        wf.workflowfile('alfred_mstodo_workflow.py'),
        'pref sync background',
        '--commit'
    ])

def background_sync_if_necessary(seconds=30):
    last_sync = wf.cached_data('last_sync', max_age=0)

    # Avoid syncing on every keystroke, background_sync will also prevent
    # multiple concurrent syncs
    if last_sync is None or (datetime.utcnow() - last_sync).total_seconds() > seconds:
        background_sync()