from django.urls import include, path
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'blogposts', views.BlogPostViewSet)
router.register(r'blogquotes', views.BlogQuoteViewSet)
router.register(r'blogcategories', views.BlogCategoryViewSet)
router.register(r'pages', views.PagesViewSet)
router.register(r'socialmedialinks', views.SocialMediaLinkViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls))]


#!/usr/bin/python

from __future__ import division, print_function

import os
import sys
import argparse
import pdb

import numpy as np
import matplotlib.pyplot as plt

path = '/Users/kevinnapier/Mechanics/Lab/Lab04/data'
graphicspath = '/Users/kevinnapier/Mechanics/Lab/Lab04/'

small = {}
medium = {}
large = {}

numtrials = 5
numpulleys = 3

# Import raw data
def import_data(pulley, fileprefix):
    for jj in range(numtrials):
        pulley[jj+1] = np.loadtxt(os.path.join(path,
                                     fileprefix+'_mass_{}.txt'.format(jj+1)),
                                   skiprows = 7,
                                   usecols = (0,1,2,3),
                                   unpack = True)
    return;

# Generate QA plots of the data
def qaplots(pulley, name):
    plt.figure()
    for kk in range(numtrials):
        plt.plot(pulley[kk+1][0], pulley[kk+1][3])
    plt.show()
    return

# Clip times
def clip(edges, pulley):
    keep = []
    for jj in range(5):
        keep.append(np.where((pulley.items()[jj][1][0] > edges[0]) * (pulley.items()[jj][1][0] < edges[1])))
    return keep

def main():

    import_data(small, 'small')
    import_data(medium, 'medium')
    import_data(large, 'large')

    smalledges = [2, 5]
    mediumedges = [1, 2]
    largeedges = [0.4, 0.9]

    smallclip = clip(smalledges, small)
    medclip = clip(mediumedges, medium)
    largeclip = clip(largeedges, large)

    smallkeep = smallclip[0][0]
    medkeep = medclip[0][0]
    largekeep = largeclip[0][0]

    smallN = len(smallclip[0][0])
    medN = len(medclip[0][0])
    largeN = len(largeclip[0][0])

    small1 = [small[1][3][ii] for ii in smallkeep]
    small2 = [small[2][3][ii] for ii in smallkeep]
    small3 = [small[3][3][ii] for ii in smallkeep]
    small4 = [small[4][3][ii] for ii in smallkeep]
    small5 = [small[5][3][ii] for ii in smallkeep]

    med1 = [medium[1][3][ii] for ii in medkeep]
    med2 = [medium[2][3][ii] for ii in medkeep]
    med3 = [medium[3][3][ii] for ii in medkeep]
    med4 = [medium[4][3][ii] for ii in medkeep]
    med5 = [medium[5][3][ii] for ii in medkeep]

    large1 = [large[1][3][ii] for ii in largekeep]
    large2 = [large[2][3][ii] for ii in largekeep]
    large3 = [large[3][3][ii] for ii in largekeep]
    large4 = [large[4][3][ii] for ii in largekeep]
    large5 = [large[5][3][ii] for ii in largekeep]

    means1 = np.mean(small1)
    stds1 = np.std(small1)
    means2 = np.mean(small2)
    stds2 = np.std(small2)
    means3 = np.mean(small3)
    stds3 = np.std(small3)
    means4 = np.mean(small4)
    stds4 = np.std(small4)
    means5 = np.mean(small5)
    stds5 = np.std(small5)

    meanm1 = np.mean(med1)
    stdm1 = np.std(med1)
    meanm2 = np.mean(med2)
    stdm2 = np.std(med2)
    meanm3 = np.mean(med3)
    stdm3 = np.std(med3)
    meanm4 = np.mean(med4)
    stdm4 = np.std(med4)
    meanm5 = np.mean(med5)
    stdm5 = np.std(med5)

    meanl1 = np.mean(large1)
    stdl1 = np.std(large1)
    meanl2 = np.mean(large2)
    stdl2 = np.std(large2)
    meanl3 = np.mean(large3)
    stdl3 = np.std(large3)
    meanl4 = np.mean(large4)
    stdl4 = np.std(large4)
    meanl5 = np.mean(large5)
    stdl5 = np.std(large5)

    masses = np.array([0.05, 0.1, 0.15, 0.2, 0.25])*9.8
    smrad = 0.005
    mdrad = 0.0165
    lgrad = 0.0265

    smtau = masses*smrad
    mdtau = masses*mdrad
    lgtau = masses*lgrad

    tau = np.hstack([smtau, mdtau, lgtau])

    alpha = np.array([means1, means2, means3, means4, means5,
                      meanm1, meanm2, meanm3, meanm4, meanm4,
                      meanl1, meanl2, meanl3, meanl4, meanl5])

    errarray = np.array([stds1/np.sqrt(smallN), stds2/np.sqrt(smallN),
                         stds3/np.sqrt(smallN), stds4/np.sqrt(smallN),
                         stds5/np.sqrt(smallN), stdm1/np.sqrt(medN),
                         stdm2/np.sqrt(medN), stdm3/np.sqrt(medN),
                         stdm4/np.sqrt(medN), stdm5/np.sqrt(medN),
                         stdl1/np.sqrt(largeN), stdl2/np.sqrt(largeN),
                         stdl3/np.sqrt(largeN), stdl4/np.sqrt(largeN),
                         stdl5/np.sqrt(largeN)])

    stdarray = np.array([stds1, stds2, stds3, stds4, stds5,
                         stdm1, stdm2, stdm3, stdm4, stdm5,
                         stdl1, stdl2, stdl3, stdl4, stdl5])

    weights = (errarray)/(np.log(10)*alpha)
    raderr = 0.001
    merr = 0.001
    tauerr = np.sqrt(raderr**2+merr**2)

    cc, cov = np.polyfit(np.log10(tau), np.log10(alpha), 1, w=1/weights, cov=True)#cov=True)
    alphamodel = np.log10(tau)*cc[0]+cc[1]
    alphadata = np.log10(alpha)
    chisq = np.sum(((alphadata-alphamodel)**2/(np.log10(stdarray)**2)))

    coefferr = np.sqrt(np.diag(cov))*np.sqrt(chisq)

    # Add parsing arguments
    parser = argparse.ArgumentParser()

    parser.add_argument('--qaplots',
                        action='store_true',
                        help='Generate Raw Data Plots.')

    parser.add_argument('--theoretical',
                        action='store_true',
                        help='Calculate the theoretical moment of inertia.')

    parser.add_argument('--experimental',
                        action='store_true',
                        help='Calculate the eperimental moment of inertia.')

    parser.add_argument('--plot',
                        action='store_true',
                        help='Make the plot of alpha vs tau.')

    args = parser.parse_args()
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    if args.qaplots == True:
        qaplots(small, 'small')
        qaplots(medium, 'medium')
        qaplots(large, 'large')

    if args.experimental == True:
        print(np.sqrt(np.diag(cov)))
        Iexp = 10**(-cc[1])
        Iexperr = np.log(10)*Iexp*coefferr[1]
        print(Iexp, Iexperr)

    if args.theoretical == True:
        rodmass = 0.041
        rodlength = 0.382
        rodI = (1/12)*0.041*0.382**2

        pmI = 2*0.08*0.07**2

        Itot = pmI + rodI

        Itot = Itot

        errRod = rodI*np.sqrt(((2*0.382**2*0.001)/0.382)**2+(0.001/0.041)**2)
        errPM = pmI*np.sqrt(((2*0.07**2*0.001)/0.07)**2+(0.001/0.08)**2)

        errtot = errRod+2*errPM

        print(Itot, errtot)

    if args.plot == True:
        xx = np.linspace(-2.7,-1,100)
        plt.errorbar(np.log10(tau), np.log10(alpha), yerr=(errarray)/(np.log(10)*alpha), fmt='.', label='Data')
        plt.plot(xx, xx*cc[0]+cc[1], 'r-', label='Line of Best Fit')
        plt.legend(numpoints=1, loc=4)
        plt.xlim([-2.7, -1])
        plt.xlabel(r'$log_{10}\tau\,(Nm)$')
        plt.ylabel(r'$log_{10}\alpha\,(rad/s^2)$')
        plt.show()

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 14:07:27 2020

@author: shamu
"""

import numpy as np
import pandas as pd
import xarray as xr
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt

r_path1 = '/home/shamu/mangrove1/Working_hub/DATA_dep/Kuroshio/ugos_wNpacific_M.nc'
r_path2 = '/home/shamu/mangrove1/Working_hub/DATA_dep/Kuroshio/vgos_wNpacific_M.nc'
r_path3 = '/home/shamu/mangrove1/Working_hub/DATA_dep/Kuroshio/Yan_Sun_Spatial_Mean/Sigs/26_ceemd.npy'
# w_path1 = '/home/shamu/mangrove1/Working_hub/DATA_dep/Kuroshio/Yan_Sun_Spatial_Mean/Sigs/'
# w_path2 = '/home/shamu/mangrove1/Working_hub/DATA_dep/Kuroshio/Yan_Sun_Spatial_Mean/figs/Yan_Sun_mean_area_3.png'

Sig = np.load(r_path3)[:,4]
Data1 = xr.open_dataset(r_path1)
Data2 = xr.open_dataset(r_path2)

ugos,vgos = Data1['ugos'],Data2['vgos']

ugos_a = (ugos - ugos.mean(axis=0))*100
vgos_a = (vgos - vgos.mean(axis=0))*100

EKE = (ugos_a**2 + vgos_a**2)/2
# EKE_a = EKE - EKE.mean()

LAT,LON = Data1['lat'], Data1['lon']

mlat1,Mlat1,mlon1,Mlon1 = 22.7, 23.9, 123, 125

EKE_S = EKE.where( (EKE.lat >= mlat1) & (EKE.lat<=Mlat1) & (EKE.lon >= mlon1) & (EKE.lon <=Mlon1) ,
                   drop=True)#.mean(axis=(1,2),skipna=True)

date = pd.date_range('1993-01-01', periods = 324, freq = 1 * '1m').strftime('%Y-%m') # or freq = 3 * '1D'

df = pd.DataFrame(EKE_S)
df['date']= date
import pandas as pd

pd_sig = pd.DataFrame(EKE_S)

R_m_sig = pd_sig.rolling(window=12*2,center=True).mean()
plt.plot(R_m_sig)

#
plt.figure(figsize=(16,10), dpi= 80)
plt.plot(date, EKE_S, color='k',linewidth=3)

xtick_location = df.index.tolist()[::12]
xtick_labels = df.date.tolist()[::12]
plt.xticks(ticks=xtick_location, labels=xtick_labels, rotation=45, fontsize=15, alpha=.7)
# plt.title('IMF05', fontsize=22)
plt.yticks(fontsize=15, alpha=.7)

# Lighten borders
plt.gca().spines["top"].set_alpha(.0)
plt.gca().spines["bottom"].set_alpha(.3)
plt.gca().spines["right"].set_alpha(.0)
plt.gca().spines["left"].set_alpha(.3)

plt.legend(loc='lower right')
plt.grid(axis='both', alpha=.3)
# plt.savefig(w_path1,dpi=150)
plt.show()

# np.save(w_path1+'bo_qiu_EKE_4.npy',EKE_S)
np.save(w_path1+'Wang_eddy_box_1.npy',EKE_S)

# EKE

# Vorticity


# -*- coding : utf-8 -*-

# We import every useful library

import os, sys, time, re
from PIL import Image
from os.path import isfile, join

def input_(string):
	if sys.version_info[0] < 3 :
		return raw_input(string)
	else :
		return input(string)

def get_clean(string):  # Helps to fight against any code injection attack
	if re.search(r"^[0-9A-Za-z-_]*?$", string) is None :
		return "Warning"
	else :
		return string

def get_options():

	# We initiate our launching options

	FAST = False
	HELP = False
	REPLACE = False
	ZIP = False
	RECURSIVE = False
	PREFIX = False
	SUFFIX = False

	# We analyze and update our launching options

	if len(sys.argv)>= 2 :

		if sys.argv[1][0] == "-" :
			for elt in sys.argv[1] :
				if elt == "f" :
					FAST = True
				elif elt == "h" :
					HELP = True
				elif elt == "r" :
					REPLACE = True
				elif elt == "z" :
					ZIP = True
				elif elt == "R" :
					RECURSIVE = True
				elif elt == "s" :
					SUFFIX = True
				elif elt == "p" :
					PREFIX = True
				elif elt != "-" :
					print("Invalid option\n")
					sys.exit(0)
		else :
			print("Invalid option\n")
			sys.exit(0)

	# We act accordingly

	if HELP == True :
		print("\n\n"+open("READ_ME.txt",'r').read()+"\n")
		sys.exit(0)

	if ZIP == True :
		print("Sorry, the 'zip' option is not available yet")
	if REPLACE == True :
		sure = "Warning"
		while sure == "Warning":
			sure = get_clean(input_("Are you sure you want to replace your files ? (yes/no)\n"))
			if sure == "no" :
				REPLACE = False
			elif sure != "yes" :
				sure = "Warning"
	s = str()
	if SUFFIX == True :
		tmp = "Warning"
		while tmp == "Warning":
			tmp = get_clean(str(input_("Enter a suffix for your files (15 characters max)\n")))
		s = tmp
	p = str()
	if PREFIX == True :
		tmp = "Warning"
		while tmp == "Warning":
			tmp = get_clean(str(input_("Enter a prefix for your files (15 characters max)\n")))
		p = tmp

	options = [FAST, HELP, REPLACE, ZIP, RECURSIVE, PREFIX, SUFFIX, p, s]

	return options

def analyze_data(Dir, List2, List3, k):
	for File in os.listdir(folder+"/"+Dir):

		if isfile(folder+"/"+Dir+"/"+File):
			for f in flist :
				if File.endswith("."+f):
					List2.append(File)
					List3.append(folder+"/"+Dir)
		elif RECURSIVE == True:
			analyze_data(Dir+"/"+File, List2, List3, k)

	return

def get_format():

	F = "NC"
	List2 = list()

	Flist = ", ".join(flist)

	while F == "NC" :
		G = str(input_("Enter the final format of your pictures among "+Flist+"\n"))
		for elt in flist :
			if G == elt :
				F = G
				break
			else :
				F = "NC"

	return F

def progression(current,total):

	percentage = int(100*current/total)
	prog = int(percentage/10 +1)
	progression = "["+"#"*prog+"-"*(10-prog)+"]"

	return [progression, percentage]

def convert(List2, List3):
	current = 0

	l = 0

	for elt in List2 :
		j = 0
		for el in elt :
			if el == "." :
				break
			else :
				j+=1

		Dir1 = List3[l]
		Dir2 = Dir1.split("/")
		n = 0
		for el in Dir2 :
			if el == "original":
				Dir2[n] = "converted"
				break
			n+=1
		Dir2 = "/".join(Dir2)
		l+=1

		name = elt[:j]
		sys.stdout.write('\n'+"Opening "+Dir1+"/"+elt+"...")
		pic = Image.open(Dir1+'/'+elt)

		if FAST == False :
			time.sleep(0.8)

		k=0
		for lett in Dir1 :
			k+=1
		K=0
		for lett in Dir2 :
			K+=1
		sys.stdout.write('\r' + ' '*(k+j+15))
		sys.stdout.write('\r' + "Opened " +Dir1+'/'+ elt + "\n")

		name2 = s + name + p + "." + F

		if os.path.exists(Dir2) == False :
			os.mkdir(Dir2)

		sys.stdout.write('\r'+"Saving "+Dir2+"/"+name2+"...")
		pic.save(Dir2+'/'+name2)

		current+=1
		sys.stdout.write('\r' + ' '*(K+j+14))
		Prog = progression(current, total)
		Progression = Prog[0]
		Percentage = Prog[1]
		sys.stdout.write('\r' + "Saved " + Dir2+"/"+name2)
		sys.stdout.write( " "*(60-K-j-14) + Progression + "  " + str(Percentage) + "%\n")
		if REPLACE == True :
			os.remove(Dir1 + '/' + elt)

	return

# We start our main program
flist = ["jpg","png","bmp","gif","tiff","pdf"]
options = get_options()
FAST = options[0]
HELP = options[1]
REPLACE = options[2]
ZIP = options[3]
RECURSIVE = options[4]
PREFIX = options[5]
SUFFIX = options[6]
p = options[7]
s = options[8]

# We ask the user about his desired final format

F = get_format()

# We analyze the files to convert

sys.stdout.write("\nAnalyzing the files...")

List3 = list()
List2 = list()
k = 0
folder = os.getcwd()
for elt in folder :
	k+=1

analyze_data("original", List2, List3, k)

total = 0
for elt in List2:
	total+=1

if FAST == False :
	time.sleep(1)
sys.stdout.write("\rFiles analyzed         \n")
print(List2)

# Finally, we convert the files

convert(List2, List3)

print("\nDone \n")


import configparser
import json
import re
import threading
import time
from datetime import timedelta, datetime, timezone
from logging import Logger
from queue import Queue
from typing import List, Dict

from dateutil import parser
from requests import request

from app.IncartDateTime import get_wait_time, get_delay_time
from app.WhatsappChanel import post_api_message, get_api_messages
from app.model import DataAccessLayer, IncartJob, JobDoctor, Doctor, ChatMessage
from app.repo import Repo

# найти все url в переданной строке
def find_url_links(txt) -> List:
    """Find all url links in input string"""
    regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|" \
            r"(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
    url = re.findall(regex, txt)
    return [x[0] for x in url]

class Task(threading.Thread):
    wait_confirm_request = 30  # интервал в сек. проверки подтверждения согласия на расшифировку
    request_time_estimate = 30.0  # время ожидания в мин. согласия на обработку задания, после отправки запроса
    wait_job_processing = 30  # интервал в сек. проверки окончания обработки доктором задания
    job_time_estimate = 120.0  # время ожидания в мин. окончания обработки задания доктором
    job_delay = 180.0  # время задержки выполнения задачи в мин. (задача отложена из за невозможности найти исполнителя)

    def __init__(self, job_id: str, queue: Queue, logger: Logger):
        threading.Thread.__init__(self)
        self.daemon = False
        self.stopped = threading.Event()
        self.dal = DataAccessLayer()
        self.dal.connect()
        self.job_id: str = job_id
        self.queue = queue
        self.logger: Logger = logger

    def stop(self):
        self.stopped.set()
        self.join()

    def run(self):
        """
        Run the thread
        """
        self.run_job()

    # Запустить задачу на выполнение
    def run_job(self) -> None:
        repo = Repo(self.dal.session)
        job: IncartJob = repo.get_incartjob(self.job_id)
        jobdoctor: JobDoctor = None

        # искать исполнителя задания
        if job.doctor_id is None:
            jobdoctor = self.find_doctor(job)
        # исполнитель не найден(не нашли кандидата)
        if jobdoctor is None:
            self.set_restart_datetime(job)
            return
        # исполнитель не найден (кандидат отказалася)
        if job.doctor_id is None:
            self.stop_job(jobdoctor)
            return
        # отправить задание на исполнение
        self.send_job(jobdoctor)
        if jobdoctor.job_finish_id is None:
            self.stop_job(jobdoctor)
            return
        # задание не было выполнено в срок
        if jobdoctor.job_finished is None:
            self.stop_job(jobdoctor)
            return
        # доктор подтвердил выполнение задания
        job.closed = datetime.now().astimezone(timezone.utc)
        self.update_job(job)
        if job.file_decrypt:
            self.send_success(jobdoctor)  # послать подтверждение выполнения
        else:
            self.send_error(jobdoctor)  # послать сообщение
        self.send_result(job)

    # перекратить обработку задания, отослать кандитату или исполнителю отказ
    def stop_job(self, jobdoctor: JobDoctor):
        job: JobDoctor = jobdoctor.job
        job.doctor_id = None
        self.update_job(job)
        self.queue.put(job.id)
        self.send_rejection(jobdoctor)  # послать отказ

    # расчитать и записать в задание время следующего рестарта
    def set_restart_datetime(self, job):
        now_utc = datetime.now().astimezone(timezone.utc)
        job.restart = get_delay_time(now_utc, wait=Task.job_delay)
        self.update_job(job)

    # Найти исполнителя на выполнение задания
    def find_doctor(self, job: IncartJob) -> JobDoctor:
        self.log_info("run: find_doctor")
        # get free candidate for processing the result
        candidate: Doctor = self.get_candidate(job)
        if candidate is None:
            return None  # прекращаем дальнейщий поиск если нет кандидата

        jobdoctor = JobDoctor()  # создать объект для отслеживания состояиня обработки задания
        jobdoctor.doctor = candidate
        jobdoctor.job = job
        ok: bool = self.update_jobdoctor(jobdoctor)

        # send a request for processing the result
        msg = "Компания \"Инкарт\" предлагает Вам заказ на обработку результата исследования.\n" \
              "Если Вы готовы выполнить заказ, пришлите ответ со словом: Да."
        result = post_api_message(candidate.id, msg)
        status = result["status"]
        if status != 'success':
            return jobdoctor
        data = result["data"]
        self.log_info(f"data={data}")
        jobdoctor.request_id = data['message_id']
        jobdoctor.request_started = datetime.now().astimezone(timezone.utc)
        jobdoctor.request_time_estimate = jobdoctor.request_started + timedelta(minutes=Task.request_time_estimate)
        ok = self.update_jobdoctor(jobdoctor)
        self.confirm_request(jobdoctor)
        if jobdoctor.answered is not None:
            job.doctor_id = candidate.id
            self.update_job(job)
        return jobdoctor

    # предложить кандидата для выполнения задания
    def get_candidate(self, job: IncartJob) -> Doctor:
        self.log_info("run: get_candidate")
        repo = Repo(self.dal.session)
        candidate: Doctor = repo.get_job_candidate(job)  # Бобылев Е.А. 96881373
        return candidate

    # ожидать подтвеждение от кандидата согласия на выполнения задания
    def confirm_request(self, jobdoctor: JobDoctor) -> None:
        self.log_info("run: confirm_request")
        now = datetime.now().astimezone(timezone.utc)

        while now < jobdoctor.request_time_estimate:
            self.log_info("run: confirm_request while")
            val = get_api_messages(jobdoctor.doctor_id, jobdoctor.request_started)
            status = val['status']
            if status != 'success':
                continue
            data: List[Dict] = val["data"]
            if len(data) > 0:
                last_msg = ChatMessage.from_json(data[-1])
                msg_date: datetime = parser.parse(last_msg.created)
                if jobdoctor.request_started < msg_date < jobdoctor.request_time_estimate:
                    if last_msg.text.upper() == 'ДА':
                        jobdoctor.request_answer_id = last_msg.id
                        jobdoctor.answered = msg_date
                    self.log_info(F"run conffirm_request msg.text={last_msg.text}")
                    break
            time.sleep(Task.wait_confirm_request)
            now = datetime.now().astimezone(timezone.utc)
        self.update_jobdoctor(jobdoctor)

    # отправить задание на обработку
    def send_job(self, jobdoctor: JobDoctor) -> None:
        self.log_info("run: send_job")
        start = datetime.now()
        finish = get_wait_time(start, wait=Task.job_time_estimate)
        link = jobdoctor.job.file_encrypt
        msg = f"Скачайте задание {link}\n" \
              f"Ждем результат  {finish}."
        result = post_api_message(jobdoctor.doctor_id, msg)
        status = result["status"]
        if status != 'success':
            return
        data = result["data"]
        jobdoctor.job_start_id = data['message_id']
        jobdoctor.job_started = start.astimezone(timezone.utc)
        jobdoctor.job_time_estimate = finish.astimezone(timezone.utc)
        self.update_jobdoctor(jobdoctor)
        # ждем результат
        self.wait_processing(jobdoctor)

    # выполнения провеоки окончания обработки задания доктором (Ожидание завершения обработки доктором)
    def wait_processing(self, jobdoctor: JobDoctor) -> None:
        self.log_info("run: wait_processing")
        now_utc = datetime.now().astimezone(timezone.utc)
        while now_utc < jobdoctor.job_time_estimate:
            val = get_api_messages(jobdoctor.doctor_id, jobdoctor.job_started)
            status = val['status']
            if status != 'success':
                continue
            data: List[Dict] = val["data"]
            last_msg = ChatMessage.from_json(data[-1])
            msg_date: datetime = parser.parse(last_msg.created)
            if jobdoctor.job_started < msg_date < jobdoctor.job_time_estimate:
                urls = find_url_links(last_msg.text)
                if len(urls) > 0:
                    jobdoctor.job.file_decrypt = urls[0]
                else:
                    jobdoctor.job.enc_error = last_msg.text
                jobdoctor.job_finish_id = last_msg.id
                jobdoctor.job_finished = parser.parse(last_msg.created)  # Это строка
                self.update_jobdoctor(jobdoctor)
                break
            time.sleep(Task.wait_job_processing)

    # записать изменения состояния задачи в БД
    def update_job(self, job: IncartJob) -> bool:
        self.log_info("run: update_job")
        repo = Repo(self.dal.session)
        ok: bool = repo.update_incartjob(job)
        self.log_info(f"run: update_job, result={ok}")
        return ok

    # записать изменения состояния обработки задачи в БД
    def update_jobdoctor(self, jobdoctor: JobDoctor) -> bool:
        self.log_info("run: update_jobdoctor")
        repo = Repo(self.dal.session)
        ok: bool = repo.update_jobdoctor(jobdoctor)
        self.log_info(f"run: update_jobdoctor, result={ok}")
        return ok

    # записать в лог
    def log_info(self, msg: str):
        if self.logger:
            self.logger.info(msg)

    # послать отказ по wahtsapp
    def send_rejection(self, jobdoctor: JobDoctor) -> None:
        self.log_info("run: send_rejection")
        msg = "К сожалению мы вынуждены отменить выполнение Вами заказа."
        post_api_message(jobdoctor.doctor_id, msg)

    # послать подтверждение по whatsapp
    def send_success(self, jobdoctor: JobDoctor) -> None:
        self.log_info("run: send_success")
        msg = "Подтверждаем выполнение заказа"
        post_api_message(jobdoctor.doctor_id, msg)

    # послать подтверждение по whatsapp
    def send_error(self, jobdoctor):
        self.log_info("run: send_success")
        msg = "Спасибо. Заказ не был выполнен (возможно из за ошибок) и будет направлен администратору для првоерки."
        post_api_message(jobdoctor.doctor_id, msg)
        pass

    # отослать результат обработки задания
    def send_result(self, job: IncartJob):
        """sent processing result"""
        url = "http://holtershop.ru/local/backend/exchange.php"
        body = {"order_id": job.order_id, "file": job.file_decrypt, "report": job.report, "enc_error": job.file_encrypt}
        payload = json.dumps(body)
        headers = {
            'Content-Type': 'application/json',
            'charset': 'UTF-8'
        }
        response = request("POST", url, headers=headers, data=payload.encode('utf-8'))
        self.log_info(f'send_result: {body}')
        self.log_info(f'send_result: ststus_code ={response.status_code}')

    # Выполнить инициализацию глобальных переменных
    @staticmethod
    def init(config: configparser.ConfigParser):
        Task.wait_confirm_request = config["DEFAULT"].getint("wait_confirm_request")
        Task.request_time_estimate = config["DEFAULT"].getfloat("request_time_estimate")
        Task.wait_job_processing = config["DEFAULT"].getint("wait_job_processing")
        Task.job_time_estimate = config["DEFAULT"].getfloat("job_time_estimate")
        Task.job_delay = config["DEFAULT"].getfloat("job_delay")


# -*- coding: utf-8 -*-
"""
Created on Tue Apr  7 13:38:16 2020

@author: tdenizgez
"""

import cv2
import numpy as np

def nothing(x):
    pass

def findMaxContours(contours):
    maxI = 0
    maxA = 0

    for i in range(len(contours)):
        if maxA < cv2.contourArea(contours[i]):
            maxA = cv2.contourArea(contours[i])
            maxI  = i

    return contours[maxI]

cap = cv2.VideoCapture(0)

while True:
    _,frame = cap.read()
    frame = cv2.flip(frame, 1)

    roi = frame[:,320:]

    hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
    lower = np.array([0,70,90],dtype=np.uint8)
    upper = np.array([180,109,132],dtype=np.uint8)
    mask = cv2.inRange(hsv, lower, upper)

    kernel = np.ones((5,5))
    mask = cv2.dilate(mask, kernel,3)

    mask = cv2.GaussianBlur(mask, (3,3), 8)

    contours,_=cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    c = findMaxContours(contours)

    cv2.drawContours(roi, c, -1, (0,0,255))

    cv2.imshow("mask",mask)
    cv2.imshow("roi",roi)

    if cv2.waitKey(3) & 0xFF == ord('q'):
       break

cap.release()
cv2.waitKey()
cv2.destroyAllWindows()


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /Users/dunfield/snappy/build/lib.macosx-10.6-intel-2.7/snappy/snap/polished_reps.py
# Compiled at: 2018-08-17 21:53:27
from __future__ import print_function
import os, sys, re, string, tempfile
from itertools import product, chain
from functools import reduce
from ..sage_helper import _within_sage
from ..pari import pari
from .fundamental_polyhedron import *
if _within_sage:
    import sage
    from sage.all import RealField, ComplexField, gcd, prod, powerset
    from sage.all import MatrixSpace, matrix, vector, ZZ
    Object = sage.structure.sage_object.SageObject
    identity = lambda A: MatrixSpace(A.base_ring(), A.nrows())(1)
    abelian_group_elt = lambda v: vector(ZZ, v)
else:
    Object = object
    from .utilities import Matrix2x2 as matrix, powerset
    from ..number import Number

    def identity(A):
        return matrix(A.base_ring(), 1.0, 0.0, 0.0, 1.0)

    def prod(L, initial=None):
        if initial:
            return reduce(lambda x, y: x * y, L, initial)
        else:
            if L:
                return reduce(lambda x, y: x * y, L)
            return 1

    abelian_group_elt = lambda v: v

class MapToFreeAbelianization(Object):
    """
    >>> import snappy
    >>> M = snappy.Manifold('m125')
    >>> G = M.fundamental_group(False, False, False)
    >>> rho = MapToFreeAbelianization(G)
    >>> from __future__ import print_function
    >>> for g in G.generators(): print( g, rho(g) )
    ...
    a (3, -1)
    b (5, -2)
    c (0, 1)
    d (1, 0)
    """

    def __init__(self, fund_group):
        self.generators = gens = fund_group.generators()
        self.relators = rels = fund_group.relators()
        entries = list(chain(*(self.abelianize_word(r) for r in rels)))
        presentation = pari.matrix(len(rels), len(gens), entries).mattranspose()
        U, V, D = presentation.matsnf(flag=1)
        self.U = U
        elementary_divisors = D.matsnf().list()
        self._rank = elementary_divisors.count(0)

    def abelianize_word(self, word):
        return [ word.count(g) - word.count(g.swapcase()) for g in self.generators ]

    @property
    def rank(self):
        return self._rank

    def __call__(self, word):
        v = self.U * pari(self.abelianize_word(word)).mattranspose()
        return abelian_group_elt(tuple(int(x) for x in list(v[0])[:self._rank]))

def clean_RR(r, error):
    if abs(r) < error:
        return 0
    return r

if _within_sage:

    def clean_CC(z, error, prec):
        CC = ComplexField(prec)
        return CC(clean_RR(z.real(), error), clean_RR(z.imag(), error))

else:

    def clean_CC(z, error, prec):
        re, im = z.real(), z.imag()
        prec = re.prec()
        clean_z = pari.complex(clean_RR(re.gen, error), clean_RR(im.gen, error))
        return Number(clean_z, precision=prec)

def clean_matrix(A, error, prec):
    return matrix([ [ clean_CC(A[x], error, prec) for x in ((i, 0), (i, 1)) ] for i in (0,
                                                                                1)
                  ])

def SL2C_inverse(A):
    return matrix([[A[(1, 1)], -A[(0, 1)]], [-A[(1, 0)], A[(0, 0)]]])

def matrix_norm(A):
    return max([ abs(a) for a in A.list() ])

def matrix_difference_norm(A, B):
    return max([ abs(a - b) for a, b in zip(A.list(), B.list()) ])

def projective_distance(A, B):
    return min(matrix_norm(A - B), matrix_norm(A + B))

def compare_matrices(Mats0, Mats1):
    return max([ projective_distance(A, B) for A, B in zip(Mats0, Mats1) ])

def make_epsilon(A):
    prec = A.base_ring().precision()
    RR = RealField(prec)
    return RR(2) ** (RR(-0.6) * prec)

def make_trace_2(A):
    P = A if A.trace() > 0 else -A
    if abs(P.trace() - 2) < make_epsilon(A):
        return P
    raise ValueError("Matrix of peripheral element doesn't seem to be parabolic")

def parabolic_eigenvector(A):
    P, CC, epsilon = make_trace_2(A), A.base_ring(), make_epsilon(A)
    for v in [vector(CC, (1, 0)), vector(CC, (0, 1))]:
        if (v - P * v).norm() < epsilon:
            return v

    v = vector(CC, pari(P - 1).matker()._sage_().list())
    assert (v - P * v).norm() < epsilon
    return v

def extend_to_basis(v):
    u = 1 / v.norm() * v
    w = vector(v.base_ring(), (-u[1].conjugate(), u[0].conjugate()))
    return matrix([u, w]).transpose()

def is_essentially_Id2(M, error=0.001):
    return max(map(abs, (M - identity(M)).list())) < error

class MatrixRepresentation(Object):

    def __init__(self, gens, relators, matrices):
        self._gens, self._relators, self._matrices = gens, relators, matrices
        self._build_hom_dict()
        A = matrices[0]
        self._id = identity(A)

    def _build_hom_dict(self):
        gens, matrices = self._gens, self._matrices
        inv_gens = [ g.upper() for g in gens ]
        inv_mat = [ SL2C_inverse(m) for m in matrices ]
        self._hom_dict = dict(zip(gens + inv_gens, matrices + inv_mat))

    def generators(self):
        return self._gens

    def num_generators(self):
        return len(self._gens)

    def relators(self):
        return self._relators

    def __call__(self, word):
        return prod([ self._hom_dict[g] for g in word ], self._id)

    def is_nonprojective_representation(self):
        """
        True if this is an SL(2,C)-representation, i.e., if multiplying the generators
        in a word yields the identity matrix.
        """
        return all([ is_essentially_Id2(self(R)) for R in self.relators() ])

    def is_projective_representation(self):
        """
        True if this is an PSL(2,C)-representation, i.e., if multiplying the generators
        in a word yields the identity matrix or its negative.
        """
        rel_images = [ self(R) for R in self.relators() ]
        return all([ is_essentially_Id2(M) or is_essentially_Id2(-M) for M in rel_images ])

    def lift_to_SL2C(self):
        assert self.is_projective_representation()
        base_gen_images = [ self(g) for g in self.generators() ]
        generators, relators, meridian = self.generators(), self.relators(), self.peripheral_curves()[0][0]
        pos_signs = product(*([(1, -1)] * len(base_gen_images)))
        for signs in pos_signs:
            gen_images = [ s * M for s, M in zip(signs, base_gen_images) ]
            rho = MatrixRepresentation(generators, relators, gen_images)
            if rho.is_nonprojective_representation():
                self._matrices = gen_images
                self._build_hom_dict()
                break

        assert self.is_nonprojective_representation()

    def all_lifts_to_SL2C(self):
        ans = []
        self.lift_to_SL2C()
        base_gen_images = map(self, self.generators())
        pos_signs = product(*([(1, -1)] * len(base_gen_images)))
        for signs in pos_signs:
            beta = MatrixRepresentation(self.generators(), self.relators(), [ s * A for s, A in zip(signs, base_gen_images) ])
            if beta.is_nonprojective_representation():
                ans.append(beta)

        return ans

    def trace_field_generators(self):
        gens = self.generators()
        enough_elts = [ ('').join(sorted(s)) for s in powerset(gens) if len(s) > 0 ]
        return [ self(w).trace() for w in enough_elts ]

    def invariant_trace_field_generators(self):
        gens = self.generators()
        if min([ abs(self(g).trace()) for g in gens ]) < 0.001:
            raise ValueError('Algorithm fails when a generator has trace 0, see page 125 of ML')
        gens = [ 2 * g for g in gens ]
        enough_elts = [ ('').join(sorted(s)) for s in powerset(gens) if len(s) > 0 ]
        return [ self(w).trace() for w in enough_elts ]

class ManifoldGroup(MatrixRepresentation):

    def __init__(self, gens, relators, peripheral_curves=None, matrices=None):
        MatrixRepresentation.__init__(self, gens, relators, matrices)
        self._peripheral_curves = peripheral_curves

    def peripheral_curves(self):
        return self._peripheral_curves

    def SL2C(self, word):
        return self(word)

    def check_representation(self):
        relator_matrices = [ self.SL2C(R) for R in self.relators() ]
        return max([ projective_distance(A, identity(A)) for A in relator_matrices ])

    def cusp_shape(self, cusp_num=0):
        M, L = map(self.SL2C, self.peripheral_curves()[cusp_num])
        C = extend_to_basis(parabolic_eigenvector(M))
        M, L = [ make_trace_2(C ** (-1) * A * C) for A in [M, L] ]
        z = L[0][1] / M[0][1]
        return z.conjugate()

    def lift_to_SL2C(self):
        MatrixRepresentation.lift_to_SL2C(self)
        phi = MapToFreeAbelianization(self)
        meridian = self.peripheral_curves()[0][0]
        meridian_trace = self(meridian).trace()
        if phi.rank == 1 and phi(meridian) % 2 != 0 and meridian_trace < 0:

            def twist(g, gen_image):
                if phi(g)[0] % 2 == 0:
                    return gen_image
                return -gen_image

            self._matrices = [ twist(g, M) for g, M in zip(self._gens, self._matrices) ]
            self._build_hom_dict()
            assert self.is_nonprojective_representation()
            assert self(meridian).trace() > 0

    def __repr__(self):
        return 'Generators:\n   %s\nRelators:\n   %s' % (
         (',').join(self.generators()),
         ('\n   ').join(self.relators()))

def polished_holonomy(manifold, bits_prec=100, fundamental_group_args=[], lift_to_SL2=True, ignore_solution_type=False, dec_prec=None):
    """
    Return the fundamental group of M equipt with a high-precision version of the
    holonomy representation::

        sage: M = Manifold('m004')
        sage: G = M.polished_holonomy()
        sage: G('a').trace()
        1.5000000000000000000000000000 - 0.86602540378443864676372317075*I
        sage: G = M.polished_holonomy(bits_prec=1000)
        sage: G('a').trace().parent()
        Complex Field with 1000 bits of precision
    """
    M = manifold
    if dec_prec:
        bits_prec = None
        error = 10 ** (-dec_prec * 0.8)
    else:
        error = 2 ** (-bits_prec * 0.8)
    shapes = M.tetrahedra_shapes('rect', bits_prec=bits_prec, dec_prec=dec_prec)
    G = M.fundamental_group(*fundamental_group_args)
    f = FundamentalPolyhedronEngine.fromManifoldAndShapesMatchingSnapPea(M, shapes, normalize_matrices=True)
    mats = f.matrices_for_presentation(G, match_snappea=True)
    clean_mats = [ clean_matrix(A, error=error, prec=bits_prec) for A in mats ]
    PG = ManifoldGroup(G.generators(), G.relators(), G.peripheral_curves(), clean_mats)
    if lift_to_SL2:
        PG.lift_to_SL2C()
    else:
        assert PG.is_projective_representation()
    return PG


import os
import cv2
import numpy as np
import keras
from keras.models import load_model
import warnings
import time
warnings.filterwarnings("ignore")

face_cascade = cv2.CascadeClassifier( os.getcwd() + '/haarcascade_frontalface_default.xml')

CNN_model = load_model('CNN_model_trained_v4_2.model')
face_size = [100,100]

def predict_output(img):
    faces = face_cascade.detectMultiScale(img, 1.3, 5)
    faces = np.array(faces)
    if faces.size:
        [x,y,w,h] = faces[0]
        cropped_img = img[y-50:y+h+20, x:x+w]
        cropped_img = np.array(cropped_img).astype(np.float32)
        cropped_img = cropped_img/255.0
        display_img = cropped_img
        if cropped_img.shape[0] >= face_size[0] and cropped_img.shape[1] >= face_size[1]:
            cropped_img = cv2.resize(cropped_img,(face_size[0],face_size[1]))
            x = CNN_model.predict(np.expand_dims(cropped_img,axis=0))
            if x < 0.5:
            	display_string = "Female"
            	cv2.putText(display_img,display_string,(x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,100))
            else:
            	display_string = "Male"
            	cv2.putText(display_img,display_string,(x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
            cv2.imshow('gender_detection',display_img)
            #

cap = cv2.VideoCapture(0)
fps = 0
t1 = time.time()
while(True):
    ret, frame = cap.read()
    t2 = time.time()
    if t2 - t1 >= 1:
    	print (fps,'fps')
    	fps = 0
    	t1 = time.time()
    fps = fps + 1
    predict_output(frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


__author__ = 'anna'

from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
import time

class HiddenElements(object):

    def test_letskodeit(self):

        url = 'https://letskodeit.teachable.com/p/practice'
        driver = webdriver.Chrome()
        driver.maximize_window()
        driver.get(url)
        driver.implicitly_wait(3)

        element = driver.find_element(By.ID, "displayed-text")
        print(element.is_displayed())
        time.sleep(3)
        driver.find_element(By.ID, 'hide-textbox').click()
        time.sleep(3)
        print(element.is_displayed())
        driver.find_element(By.ID, 'show-textbox').click()
        time.sleep(3)
        print(element.is_displayed())
        driver.quit()

    def test_expedia(self):
        url = "https://www.expedia.com/"
        driver = webdriver.Chrome()
        driver.maximize_window()
        driver.get(url)
        driver.implicitly_wait(3)

        driver.find_element(By.XPATH, "//span[contains(text(),'Flights')]").click()

        driver.implicitly_wait(3)
        buttons = driver.find_elements(By.XPATH, "//span[text()='Add Adult']//parent::button")
        print("Button state: {}".format(buttons[0].is_displayed()))
        try:
            travelers = driver.find_element(By.XPATH, "//div[@id='traveler-selector-hp-flight']//ul[@class='menu-bar-inner']/li/button[@type='button']")
            travelers.click()
            time.sleep(3)
        except:
            print("Failed")
        print("Button state: {}".format(buttons[0].is_displayed()))
        buttons[0].click()
        time.sleep(4)
        driver.quit()

ff = HiddenElements()
ff.test_letskodeit()
ff.test_expedia()


import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow import keras

IMAGE_SIZE = [350, 350]
FLATTEN_SIZE = [350, 350, 3]  # [IMAGE_SIZE, Channels=3]
MAX_RATING = 5
EPOCHS = 5

def initTensorFlow():
    tf.data.experimental.AUTOTUNE
    tf.enable_eager_execution()
    return initModel()

def initModel():
    model = keras.Sequential([
        keras.layers.Flatten(input_shape=FLATTEN_SIZE),
        keras.layers.Dense(128, activation=tf.nn.relu),
        keras.layers.Dense(MAX_RATING, activation=tf.nn.softmax)
    ])
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    return model

def initConvo2DModel():
    model = Sequential([
        Conv2D(16, 3, padding='same', activation='relu',
               input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)),
        MaxPooling2D(),
        Conv2D(32, 3, padding='same', activation='relu'),
        MaxPooling2D(),
        Conv2D(64, 3, padding='same', activation='relu'),
        MaxPooling2D(),
        Flatten(),
        Dense(512, activation='relu'),
        Dense(1, activation='sigmoid')
    ])

    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    return model

def trainModel(model, data, labels):
    # train_data & train_labels = type numpy.ndarray
    four_fifths = int(len(data) * 0.8)
    train_data = data[0: four_fifths]
    train_labels = labels[0: four_fifths]
    test_data = data[four_fifths: len(data)]
    test_labels = labels[four_fifths: len(data)]

    model.fit(train_data, train_labels, epochs=EPOCHS)
    test_loss, test_acc = model.evaluate(test_data, test_labels)
    print('Test accuracy:', test_acc)
    return model

def modelPredict(model, images):
    return model.predict(images)

def preprocess_image(path):
    image = tf.read_file(path)
    image = tf.image.decode_jpeg(image, channels=0)
    image = tf.image.resize(image, IMAGE_SIZE)
    return image.numpy() / 255.0


#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist

def move():
    # Starts a new node
    rospy.init_node('robot_cleaner', anonymous=True)
    velocity_publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
    vel_msg = Twist()

    #Receiveing the user's input
    print("Enter input:")
    print("1.Radius")

    print("0.Exit")
    radius = input()
    speed = 1
    #input("Input your speed:")
    #Checking if valid circle
    if(radius==1):
        vel_msg.linear.x = abs(speed)
    if(radius==0):
        exit()
    #Since we are moving just in xy plane
    vel_msg.linear.y = 0
    vel_msg.linear.z = 0
    vel_msg.angular.x = 0
    vel_msg.angular.y = 0
    ##NEED V=WR##
    vel_msg.angular.z = speed/radius

    while not rospy.is_shutdown():

        #Setting the current time for distance calculus
        t0 = rospy.Time.now().to_sec()
        current_distance = 0

        #Loop to move the turtle in an specified distance
        while(current_distance < (2*3.14*radius)):
            #Publish the velocity
            velocity_publisher.publish(vel_msg)
            #Takes actual time to velocity calculus
            t1=rospy.Time.now().to_sec()
            #Calculates distancePoseStamped
            current_distance= speed*(t1-t0)
        #After the loop, stops the robot
        vel_msg.linear.x = 0
        vel_msg.angular.z=0
        #Force the robot to stop
        velocity_publisher.publish(vel_msg)
        return radius

if __name__ == '__main__':
    try:
        x=1
        while x:
            x=move()

    except rospy.ROSInterruptException: pass


import re
import sys

import cfg_model
import stmts

_vertex_re = re.compile('^([0-9]+)\\[shape = box, label = "([^"]*)"\\];$')
_edge_re = re.compile('^([0-9]+) -> ([0-9]+)\\[label = "([^"]*)"\\];$')

class dot_graph(object):
	__slots__ = (
		'vertex_labels',
		'vertex_outgoing',
	)

	def __init__(self):
		self.vertex_labels = {}
		self.vertex_outgoing = {}

def _get_enter_vertex(dg):
	for vertex, label in dg.vertex_labels.items():
		if label == 'ENTER': return vertex
	return None

def _get_exit_vertex(dg):
	for vertex, label in dg.vertex_labels.items():
		if label == 'EXIT': return vertex
	return None

def _get_reachable(dg, origin):
	pending = set((origin,))
	reachable = set()
	while pending:
		vertex = pending.pop()
		reachable.add(vertex)
		for succ, label in dg.vertex_outgoing.get(vertex, []):
			if succ not in reachable: pending.add(succ)
	return reachable

def _prune_unreachable(dg, reachable):
	for vertex in dg.vertex_labels.keys():
		if vertex not in reachable:
			del dg.vertex_labels[vertex]
			del dg.vertex_outgoing[vertex]
def _parse_line(line, dg):
	m = _vertex_re.match(line)
	if m:
		vertex = m.group(1)
		label = m.group(2)
		dg.vertex_labels[vertex] = label
		return
	m = _edge_re.match(line)
	if m:
		origin = m.group(1)
		target = m.group(2)
		label = m.group(3)
		dg.vertex_outgoing[origin] = dg.vertex_outgoing.get(origin, []) + [(target, label)]

def _convert_to_cfg(dg):
	cfg = cfg_model.cfg()
	cfg_tgt_map = {}
	cfg_org_map = {}

	entry = cfg.make_node(stmts.null_stmt())
	exit = cfg.make_node(stmts.null_stmt())

	for vertex, label in dg.vertex_labels.items():
		if label == 'ENTER':
			cfg_org_map[vertex] = entry
			continue
		elif label == 'EXIT':
			cfg_tgt_map[vertex] = exit
			continue
		succs = dg.vertex_outgoing.get(vertex, [])
		is_branch = len(succs) > 1

		if is_branch:
			n1 = cfg.make_node('let P, p%s := f%s(P)' % (vertex, vertex))
			n2 = cfg.make_node('branch p%s' % vertex)
			cfg.make_edge(n1, n2)
			cfg_tgt_map[vertex] = n1
			cfg_org_map[vertex] = n2
		else:
			n = cfg.make_node('let P := f%s(P)' % vertex)
			cfg_tgt_map[vertex] = n
			cfg_org_map[vertex] = n

	for origin, tgts in dg.vertex_outgoing.items():
		for target, label in tgts:
			n1 = cfg_org_map[origin]
			n2 = cfg_tgt_map[target]
			if (n1, n2) in cfg.edges:
				dummy = cfg.make_node('let P := dummy(P)')
				cfg.make_edge(dummy, n2, 0)
				n2 = dummy
			cfg.make_edge(n1, n2, int(label))

	return cfg

def parse_dot_to_cfg(lines):
	dg = dot_graph()
	for line in lines:
		_parse_line(line[:-1], dg)

	reachable = _get_reachable(dg, _get_enter_vertex(dg))
	_prune_unreachable(dg, reachable)

	cfg = _convert_to_cfg(dg)

	return cfg


from numpy import load, linspace

D = load('./testing_data/tcv_equil_64523_1100ms.npz')

R_psi = D['R']
z_psi = D['z']
psi_grid = D['psi']

from morbo.grid import GridGenerator
from morbo.equilibrium import Equilibrium
psi = Equilibrium(R_psi, z_psi, psi_grid)
psi.plot_stationary_points()

"""
Specify the flux axes for the 4 separatrix-bounded regions
"""
core_flux_grid = linspace(0.91,1,7)
pfr_flux_grid =  linspace(0.91,1,7)

outer_sol_flux_grid = linspace(1,1.09,7)[1:]
inner_sol_flux_grid = linspace(1,1.09,7)[1:]

outer_leg_distance_axis = linspace(0, 1, 16)
inner_leg_distance_axis = linspace(0, 1, 7)

outer_edge_distance_axis = linspace(0, 1, 40)
inner_edge_distance_axis = linspace(0, 1, 30)

GG = GridGenerator(equilibrium = psi,
                   core_flux_grid = core_flux_grid,
                   pfr_flux_grid = pfr_flux_grid,
                   outer_sol_flux_grid = outer_sol_flux_grid,
                   inner_sol_flux_grid = inner_sol_flux_grid,
                   inner_leg_distance_axis = inner_leg_distance_axis,
                   outer_leg_distance_axis = outer_leg_distance_axis,
                   inner_edge_distance_axis = inner_edge_distance_axis,
                   outer_edge_distance_axis = outer_edge_distance_axis,
                   machine = 'tcv')

GG.plot_grids()

# core_flux_grid = [v for v in linspace(0.9,0.95,4)]
# core_flux_grid.extend([v for v in linspace(0.95,1.,8)[1:-1]])
#
# pfr_flux_grid = [v for v in linspace(0.9,0.95,4)]
# pfr_flux_grid.extend([v for v in linspace(0.95,1.,8)[1:-1]])
#
# outer_sol_flux_grid = [v for v in linspace(1,1.05,8)[1:]]
# outer_sol_flux_grid.extend([v for v in linspace(1.05,1.2,8)[1:]])
#
# inner_sol_flux_grid = [v for v in linspace(1,1.05,8)[1:]]
# inner_sol_flux_grid.extend([v for v in linspace(1.05,1.095,4)[1:]])
#
# outer_leg_distance_axis = concatenate([linspace(0, 0.9, 16), linspace(0.9, 1, 6)[1:]])
# inner_leg_distance_axis = concatenate([linspace(0, 0.65, 5), linspace(0.65, 1, 6)[1:]])
#
# outer_edge_distance_axis = linspace(0, 1, 30)
# inner_edge_distance_axis = linspace(0, 1, 30)


"""This Code takes O*NET data on Tasks, DWA's and IWA's. It ranks IWA's for each occupations
based on their component DWA and Task work intensities. It uses these ranks as weights in a
Bipartite Graph, building the graph and returning it and it's adjacency matrix.
"""
import numpy as np
import pandas as pd
import time
import operator
import networkx as nx
from networkx import bipartite
import pickle
import matplotlib.pyplot as plt

#using pandas to read in the data in csv format as a dataframe: df
df = pd.read_excel(r'C:\Users\Daniel Sharp\Documents\MPhil Thesis\Data and Analysis\Tasks to DWAs.xlsx', header=0)
#print(df.head())

dflen = str(len(df))
print('df length:' + ' ' + dflen)

#DWAs are ranked separately for each occupation in the O*NET database
#For each occupation, the following steps are taken:

#1) Collect all tasks associated with the occupation
#list of uniques occupations
occs = list(df['O*NET-SOC Code'].unique())

#list of unique tasks
tasks = list(df['Task ID'].unique())

#list of unique dwas
dwaids = list(df['DWA ID'].unique())

#length of each list from above
dwalen = str(len(dwaids))
tasklen = str(len(tasks))
occslen = str(len(occs))
print('tasks:' + ' ' + tasklen)
print('jobs:' + ' ' + occslen)
print('dwas:' + ' ' + dwalen)
#print(df.head())

#gives unique task codes list related to occupation
uniqtasks = df.groupby('O*NET-SOC Code')['Task ID'].unique().reset_index()
#print(uniqtasks)

#gives unique DWA code list related to occupation
uniqdwa = df.groupby('O*NET-SOC Code')['DWA ID'].unique().reset_index()

#give number of unique tasks for each occ
numuniqtasks = df.groupby(by='O*NET-SOC Code', as_index=False).agg({'Task ID': pd.Series.nunique})
#print(numuniqtasks)

#2) Collect the list of all tasks associated with DWA's across occupations
dwas = df.groupby('DWA ID')['Task ID'].unique().reset_index()
#print(dwas)

#give number of unique dwas linked to each task
numdwas = df.groupby(by='DWA ID', as_index=False).agg({'Task ID': pd.Series.nunique})
#print(numdwas)

#give the number of tasks for each DWA in each occupation
numtasks=df.groupby(by=['O*NET-SOC Code', 'DWA ID'], as_index=False).agg({'Task ID': pd.Series.nunique})
numtasks.rename(columns={'Task ID':'Task Freq'},inplace=True)
#3) Sort the DWAs from step 2 based on:
#a. The highest importance of any linked task from step 1.

#reading in csv file of dwa rankings
ratedf = pd.read_excel(r'C:\Users\Daniel Sharp\Documents\MPhil Thesis\Data and Analysis\Task Ratings.xlsx', header=0)
ratedf = ratedf.loc[:, ['O*NET-SOC Code', 'Task ID', 'Scale ID', 'Data Value']]

#removing other ranking classifications from dataframe - FT = frequency and RT = relevance - only need IM = importance
ratedf = ratedf[ratedf['Scale ID'] != 'FT']
ratedf = ratedf[ratedf['Scale ID'] != 'RT']
#print(ratedf)

#map the task ratings onto the DWA to task crosswalk

"""A function that generates a multi_index dictionary from a dataframe
"""
def df_multi_dict(df1,m1,m2,c1):
    #df1-dataframe 1
    #m1-column containing the first dictionary key
    #m2-column containing the second dictionary key
    #c1-column containing the dictionary values

    #sort the dataframes to generate ordered lists
    df1=df1.sort_values([m1,m2])
    #generate a list of the first index
    m1list=list(df1[m1])
   #generate a list of the second index
    m2list=list(df1[m2])
   #ties indices together in a list of tuples
    m1m2list=list(zip(m1list,m2list))
   #generate the list of values for tuple keys
    c1list=list(df1[c1])
   #create dictionary with tuple as key and column as values
    df1_dict=dict(zip(m1m2list,c1list))
    return df1_dict

"""A function that maps from one dataframe to another, conditional on multiple coloumn values
"""
def df_multi_map(df1,df2,m1,m2,c1):
    #df1-dataframe 1 - exporting column values
    #df2-dataframe 2 - importing column values
    #m1-first column from map
    #m2-second (nested) column from map
    #c1-column containing the dictionary values

    #sort values to get ordering
    df2=df2.sort_values([m1,m2])
    #generate the desired mapping from the first dataframe with a tuple-key dictionary
    df1_dict=df_multi_dict(df1,m1,m2,c1)
    #generate the tuple key in the second dataframe
    m1list=list(df2[m1])
    m2list=list(df2[m2])
    df2['tuplelist']= pd.Series(list(zip(m1list,m2list)))
    #generate the empty column to fill with called values
    df2[c1]=""
    #for each tupple in the second dataframe, call the value from the dictionary
    df2[c1]=df2['tuplelist'].map(df1_dict)
    df2.drop('tuplelist',axis=1, inplace=True)
    #test for poor mapping
    print(df2.isna().sum())
    df2.dropna(inplace=True)
    return df2

"""A function creating a single index dictionary from two columns of a dataframe
"""
def df_single_dict(df1,m1,c1):
    #df1-dataframe 1
    #m1-column containing the dictionary key
    #c1-column containing the dictionary values

    #create the list of keys
    m1list=list(df1[m1])
    c1list=list(df1[c1])
    df1_dict=dict(zip(m1list,c1list))
    return df1_dict

"""A function that maps from one dataframe to another with a single key dictionary
"""
def df_single_map(df1,df2,m1,c1):
    #df1-dataframe 1
    #df2-dataframe 2
    #m1-column containing the map, in both dataframes
    #c1-column containing values you want to map

    #take the single key
    df1_dict=df_single_dict(df1,m1,c1)
    #map these values across
    df2[c1]=df2[m1].map(df1_dict)
    #test for poor mapping
    print(df2.isna().sum())
    df2.dropna(inplace=True)
    return df2

"""Test the functions
"""
#ratedftest=ratedf.head(100)
#dftest=df.head(100)
#testoutput=df_multi_map(ratedftest,dftest,'O*NET-SOC Code','Task ID','Data Value')
#testoutput_single=df_single_map(ratedftest,dftest,'O*NET-SOC Code','Task ID')

#load out IWA DWA crosswalk dataframe
iwadf=pd.read_excel(r'C:\Users\Daniel Sharp\Documents\MPhil Thesis\Data and Analysis\DWA Reference.xlsx', header=0)
iwas=list(iwadf['IWA ID'].unique())

#create combined dataframe for DWA and Data Value
dfvalue=df_multi_map(ratedf,df,'O*NET-SOC Code','Task ID','Data Value')
#create another dataframe to add in IWA ID's
dfIWA=df_single_map(iwadf,dfvalue,'DWA ID','IWA ID')
#add on a coloumn for frequencey of task input into each DWA
dffreq=df_multi_map(numtasks,dfIWA,'O*NET-SOC Code','DWA ID', 'Task Freq')

"""This function conducts a nested sort from a list on a GroupBy object
"""
def sort_grp(df, list1):
    #we take the dataframe, as sort along the columns
    df=df.sort_values(list1, ascending=[False,False,False])

    return df

"""This function takes the average value of multiple nested elements in a dataframe
   and adds them to the dataframe
"""
def average_nest(df,m1,m2,avglist):
    #df-dataframe
    #m1-fist column to group by
    #m2-second column to group by
    #avglist-list of columns you wish to average
    #avgnames-list of names of averge values column

    #initalise the new average columns for the dataframe

    for i in avglist:
        #find the mean of each list element 1 in each nested group
        dfmean=df.groupby([m1,m2])[i].mean()
        #create a multi-index dictionary with the multi-index as key, average as value
        list1=dfmean.index.tolist()
        list2=dfmean.tolist()
        avg_dict=dict(zip(list1,list2))
        #read the multi-index dictionary into the dataframe

        #generate the tuple list to map the average values
        m1list=list(df[m1])
        m2list=list(df[m2])
        df['tuplelist']= pd.Series(list(zip(m1list,m2list)))
        #pull average value column name from avgnames
        columnname='Average '+i
        df[columnname]=""
        #map average values from dictionary to dataframe
        df[columnname]=df['tuplelist'].map(avg_dict)
    #clean up the dataframe
    df.drop('tuplelist',axis=1, inplace=True)

    return df

#take the average data value and task freq for each IWA for each datavalue
dfavg=average_nest(dffreq,'O*NET-SOC Code','IWA ID',['Data Value','Task Freq'])

#sort tasks with their associated IWA's by Average Data Value and Average Task Frequency for each Occupation
sortdf=dfavg.groupby('O*NET-SOC Code').apply(sort_grp, list1=['Average Data Value','Average Task Freq','IWA ID'])
sortdf.reset_index(drop=True,inplace=True)

#drop any repetitions of IWA's within SOC's
"""This function drops duplicates of c1 within a GroupBy Object
"""
def within_drop(df,c1):
    df=df.drop_duplicates(keep=False,subset=c1)
    return df
uniIWAdf=sortdf.groupby('O*NET-SOC Code').apply(within_drop, c1='IWA ID')

#construct the weights off the rank or datavalue of each IWA in each Occupation
"""FILL IN ONCE YOU HAVE TALKED TO KIERAN AND MARIA"""

#trim down the dataframe to only include relevant variables
finaldf=uniIWAdf[['O*NET-SOC Code', 'Task ID', 'DWA ID', 'IWA ID', 'Average Data Value', 'Average Task Freq']]
finaldf.reset_index(drop=True,inplace=True)

#check to see any repetitions of IWA's in each SOC
#numiwa=finaldf.groupby(by=['O*NET-SOC Code', 'IWA ID'], as_index=False).count()[['O*NET-SOC Code','DWA ID', 'IWA ID']]
#numiwa.rename(columns={'DWA ID':'IWA Freq'},inplace=True)

#4) Build the weighted bipartite graph from the dataframe
"""This function takes a dataframe and builds a weighted bipartite graph"""

def df_bipartite(df1,v1,v2,w,GraphName):
    #df1-dataframe with partite sets as coloumns, and a column of weights
    #v1-column for first partite set
    #v2-column for second partite set
    #w-column of weights
    #GraphName - name of the graph image and file to be saved

    #initialise the dataframe
    #dfsort=df1.groupby([v1,v2], as_index=False).unique()
    """CHECK THIS"""
    vertex1=list(df1[v1].unique())
    vertex2=list(df1[v2].unique())
    #list of each half of the tuples that form the ends of an edge, and its weight
    tuple1=list(df1[v1])
    tuple2=list(df1[v2])
    tuple3=list(df1[w])
    #list of weighted edges
    weighted_edgelist=list(zip(tuple1,tuple2,tuple3))

    #build the graph
    G=nx.Graph()
    G.add_nodes_from(vertex1, bipartite=0)
    G.add_nodes_from(vertex2, bipartite=1)
    #add all edges and weights
    G.add_weighted_edges_from(weighted_edgelist)

    #generate the Biadjacency matrix, put it into a dataframe, and save as excel
    Adjacency_matrix=bipartite.biadjacency_matrix(G,vertex1,vertex2)
    global Adjacencydf
    Adjacencydf=pd.DataFrame(Adjacency_matrix.toarray())
    Adjacencydf.rename_axis(vertex1, axis=0,inplace=True)
    Adjacencydf.rename_axis(vertex2, axis=1,inplace=True)

    #save dataframe to excel
    ExcelTitle=GraphName+'.xlsx'
    Adjacencydf.to_excel(ExcelTitle,startrow=1, startcol=1)

    #pickle the graph
    GraphTitle=GraphName+'.gpickle'
    nx.write_gpickle(G, GraphTitle)

    #draw the graph
    #create positional dictinoary
    pos={}
    #place respective vertices into place
    pos.update((n, (1, i)) for i, n in enumerate(vertex1))
    pos.update((n, (2, i)) for i, n in enumerate(vertex2))
    nx.draw(G, pos=pos)
    Figname=GraphName+'.png'
    plt.savefig(Figname)
    plt.show()

    return G

#build the weighted bipartite graph, and its adjacency matrix
SOC_IWA_bipartite=df_bipartite(finaldf,'O*NET-SOC Code','IWA ID','Average Data Value','Bipartite')

#find the graphs adjacency  and return it as a dataframe
Adjacency_matrix=bipartite.biadjacency_matrix(SOC_IWA_bipartite,occs,iwas)
Adjacencydf=pd.DataFrame(Adjacency_matrix.toarray())
Adjacencydf.rename_axis(occs, axis=0,inplace=True)
Adjacencydf.rename_axis(iwas, axis=1,inplace=True)


import itertools
flag: bool = True
while flag:

    try:
        # initializing the list
        list1 = ['Red', 'yop', 'der', 'poy', 'op', 'edr']
        # converting all the elements in lowercase
        for counter in range(0, list1.__len__()):
            list1[counter] = list1[counter].lower()
        print(list1)
        # this list will store the characters returned by function permutation
        charperms = []
        # it stores the words when combined
        listperms = []
        num = list1.__len__()
        for item in range(0, list1.__len__()):
            # emptying the list for new use
            charperms = ['']
            # storing the values returned by permuting the each word in the list
            charperms = itertools.permutations(list1[item])
            listperms.clear()
            for each in charperms:
                # storing all the permutations of each word
                listperms.append(''.join(each))
            for others in list1[item + 1:]:
                if listperms.__contains__(others):
                    list1.remove(others)
        for counter in range(0, list1.__len__()):
            print(list1[counter])
    except IndexError:
        print(list1)
    except Exception as exep:
        print("Process stopped because %s" % exep)
    print("To exit press 0 else press any other number")
    if input() == 0:
        flag = False


import db_connect_test
from db_connect_test import Viz_Connector
from flask import Flask, request, session, redirect, url_for, render_template, flash,json,jsonify
import os
app = Flask(__name__)
@app.route('/',methods = ['GET','POST'])
def select_ID():
    if request.method == 'POST':
        ID=request.form['input_ID']
        Node_type = request.form['Node_Type']
        data = Viz_Connector(ID,Node_type).get_data()
        return  jsonify(data)
    return render_template('dropdown.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5003)


from cs1graphics import *
from random import randint
from time import sleep

class Cat(Layer):
    def __init__(self, color = 'white', spots = False, spotColor = 'black', fat = False, expression = 'neutral'):
        '''
        Creates a cat object that can be drawn on a canvas.
        Inherits all the same methods from the Layer class.

        Attributes of Cat
        color        -  String value; sets the color of the cat, includes all the cs1graphics colors as well as a 'black and white' option
        fat          -  Boolean value; makes the cat fat if True, healthy if False
        spots        -  Boolean value; gives cat spots if True, no spots if False
        spotColor    -  String value; sets the color of the spots on the cat, includes all the cs1graphics colors
        expression   -  String value; gives the cat an expression from 'neutral', 'bored', 'angry', 'sad', and 'fed up'

        Methods of Cat
        makeFat          -  makes the cat fat
        makeHealthy      -  makes the cat healthy
        addSpots         -  adds spots to the cat
        changeExpression -  changes the cat's expression
        changeColor      -  changes the cat's color
        changeDirection  -  changes the cat's direction so that its either facing left or right
        speech           -  adds text above the cat
        meow             -  cat meows loudly
        stopMeow         -  stops the meow and returns the cat to a neutral expression
        '''

        super().__init__()
        self._color = color
        self._fat = fat

        if fat:
            self._body = Ellipse(100, 50, Point(0,  0))
            self._body.setDepth(75)
            if self._color == 'black and white':
                self._body.setFillColor('black')
            else:
                self._body.setFillColor(self._color)
            self._leftLeg = Path(Point(-28,20), Point(-31, 24))
            self._leftLeg.setBorderWidth(5)
            self._rightLeg = self._leftLeg.clone()
            self._rightLeg.flip(-2)
            self._rightLeg.move(60,0)
            self._tail = Spline(Point(-47, -6), Point(-58, -14), Point(-64, -12),
                                    Point(-72, -20), Point(-70, -22), Point(-64, -14),
                                    Point(-58, -16), Point(-45, -9))
        else:
            self._body = Ellipse(80, 40, Point(0, 0))
            self._body.setDepth(75)
            if self._color == 'black and white':
                self._body.setFillColor('black')
            else:
                self._body.setFillColor(self._color)
            self._leftLeg = Path(Point(-23,16), Point(-25, 27))
            self._leftLeg.setBorderWidth(5)
            self._rightLeg = self._leftLeg.clone()
            self._rightLeg.flip(-2)
            self._rightLeg.move(44,0)
            self._tail = Spline(Point(-37, -6), Point(-48, -14), Point(-54, -12),
                                    Point(-62, -20), Point(-60, -22), Point(-54, -14),
                                    Point(-48, -16), Point(-35, -9))

        self._body.setDepth(75)
        self._head = Circle(16, Point(33, -20))
        if self._color == 'black and white':
            self._head.setFillColor('black')
        else:
            self._head.setFillColor(self._color)

        self._leftEar = Path(Point(21,-29), Point(21, -38), Point(29, -36))
        self._leftEar.setBorderWidth(3)
        self._rightEar = self._leftEar.clone()
        self._rightEar.flip()
        self._rightEar.move(26,1)
        self._leftEye = Circle(4, Point(26, -24))
        self._leftEye.setFillColor('white')
        self._rightEye = self._leftEye.clone()
        self._rightEye.move(13,0)
        self._leftPupil = Circle(1, Point(26, -24))
        self._leftPupil.setFillColor('black')
        self._rightPupil = self._leftPupil.clone()
        self._rightPupil.move(13,0)
        self._mouth = Spline(Point(27, -15), Point(33, -15), Point(39, -15))
        self._text = ''
        self._direction = 'right'

        self.add(self._body)
        self.add(self._head)
        self.add(self._leftLeg)
        self.add(self._rightLeg)
        self.add(self._leftEar)
        self.add(self._rightEar)
        self.add(self._leftEye)
        self.add(self._rightEye)
        self.add(self._leftPupil)
        self.add(self._rightPupil)
        self.add(self._mouth)
        self.add(self._tail)

        if spots:
            self.addSpots(spotColor)
        self._expression = 'neutral'
        self.changeExpression(expression)
        self.changeColor(color)

    def makeFat(self):
        '''
        makes the cat fat
        '''
        self.remove(self._body)
        self.remove(self._leftLeg)
        self.remove(self._rightLeg)
        self.remove(self._tail)

        self._body = Ellipse(100, 50, Point(0, 0))
        self._body.setDepth(75)
        self._body.setFillColor(self._color)
        self._leftLeg = Path(Point(-28,20), Point(-31, 24))
        self._leftLeg.setBorderWidth(5)
        self._rightLeg = self._leftLeg.clone()
        self._rightLeg.flip(-2)
        self._rightLeg.move(60,0)
        self._tail = Spline(Point(-47, -6), Point(-58, -14), Point(-64, -12),
                                Point(-72, -20), Point(-70, -22), Point(-64, -14),
                                Point(-58, -16), Point(-45, -9))
        if self._direction == 'left':
            self._tail.flip()
            self._tail.move(96, 0)
        self.add(self._body)
        self.add(self._leftLeg)
        self.add(self._rightLeg)
        self.add(self._tail)

    def makeHealthy(self):
        '''
        makes the cat healthy
        '''
        self.remove(self._body)
        self.remove(self._leftLeg)
        self.remove(self._rightLeg)
        self.remove(self._tail)

        self._body = Ellipse(80, 40, Point(0, 0))
        self._body.setDepth(75)
        self._body.setFillColor(self._color)
        self._leftLeg = Path(Point(-23,16), Point(-25, 27))
        self._leftLeg.setBorderWidth(5)
        self._rightLeg = self._leftLeg.clone()
        self._rightLeg.flip(-2)
        self._rightLeg.move(44,0)
        self._tail = Spline(Point(-37, -6), Point(-48, -14), Point(-54, -12),
                                Point(-62, -20), Point(-60, -22), Point(-54, -14),
                                Point(-48, -16), Point(-35, -9))
        if self._direction == 'left':
            self._tail.flip()
            self._tail.move(74, 0)
        self.add(self._body)
        self.add(self._leftLeg)
        self.add(self._rightLeg)
        self.add(self._tail)

    def addSpots(self, spotColor = 'black'):
        '''
        adds spots to the cat

        Attributes
        spotColor  -  String value; includes all regular cs1graphics colors; default value 'black'
        '''
        for spot in range(randint(1,8)):
            spot = Circle(randint(3, 6), Point(randint(-26, 26), randint(-12, 12)))
            spot.setFillColor(spotColor)
            spot.setBorderColor(spotColor)
            spot.setDepth(74)
            self.add(spot)

    def changeExpression(self, expression = 'neutral'):
        '''
        changes the expression of the cat

        Attributes
        expression  -  String value; the expression you want to change to, choose between 'neutral', 'bored', 'angry', 'sad', and 'fed up'; default value 'neutral'
        '''
        if expression == 'neutral':
            if self._expression == 'bored':
                self.remove(self._leftBoredBrow)
                self.remove(self._rightBoredBrow)
            elif self._expression == 'angry':
                self.remove(self._leftAngryBrow)
                self.remove(self._rightAngryBrow)
            elif self._expression == 'sad':
                self.remove(self._leftSadBrow)
                self.remove(self._rightSadBrow)

        if expression == 'fed up':
            if self._expression == 'bored':
                self.remove(self._leftBoredBrow)
                self.remove(self._rightBoredBrow)
            if self._expression == 'angry':
                self.remove(self._leftAngryBrow)
                self.remove(self._rightAngryBrow)
            if self._expression == 'sad':
                self.remove(self._leftSadBrow)
                self.remove(self._rightSadBrow)

            self._leftFedUpBrow = Path(Point(21, -27), Point(32, -27))
            self._rightFedUpBrow = Path(Point(34, -27), Point(45, -27))
            self._leftFedUpBrow.setBorderWidth(2)
            self._rightFedUpBrow.setBorderWidth(2)
            if self._direction == 'left':
                self._leftFedUpBrow.move(-66, 0)
                self._rightFedUpBrow.move(-66, 0)
            self.add(self._leftFedUpBrow)
            self.add(self._rightFedUpBrow)

        if expression == 'bored':
            if self._expression == 'angry':
                self.remove(self._leftAngryBrow)
                self.remove(self._rightAngryBrow)
            if self._expression == 'fed up':
                self.remove(self._leftFedUpBrow)
                self.remove(self._rightFedUpBrow)
            if self._expression == 'sad':
                self.remove(self._leftSadBrow)
                self.remove(self._rightSadBrow)
            self._leftBoredBrow = Path(Point(23, -26), Point(30, -26))
            self._rightBoredBrow = Path(Point(36, -26), Point(43, -26))
            self._leftBoredBrow.setBorderWidth(2)
            self._rightBoredBrow.setBorderWidth(2)
            if self._direction == 'left':
                self._leftBoredBrow.move(-66, 0)
                self._rightBoredBrow.move(-66, 0)
            self.add(self._leftBoredBrow)
            self.add(self._rightBoredBrow)

        if expression == 'angry':
            if self._expression == 'bored':
                self.remove(self._leftBoredBrow)
                self.remove(self._rightBoredBrow)
            if self._expression == 'fed up':
                self.remove(self._leftFedUpBrow)
                self.remove(self._rightFedUpBrow)
            if self._expression == 'sad':
                self.remove(self._leftSadBrow)
                self.remove(self._rightSadBrow)
            self._leftAngryBrow = Path(Point(21, -29), Point(31, -25))
            self._rightAngryBrow = Path(Point(34, -25), Point(44, -29))
            self._leftAngryBrow.setBorderWidth(2)
            self._rightAngryBrow.setBorderWidth(2)
            if self._direction == 'left':
                self._leftAngryBrow.move(-66, 0)
                self._rightAngryBrow.move(-66, 0)
            self.add(self._leftAngryBrow)
            self.add(self._rightAngryBrow)

        if expression == 'sad':
            if self._expression == 'bored':
                self.remove(self._leftBoredBrow)
                self.remove(self._rightBoredBrow)
            if self._expression == 'fed up':
                self.remove(self._leftFedUpBrow)
                self.remove(self._rightFedUpBrow)
            if self._expression == 'angry':
                self.remove(self._leftAngryBrow)
                self.remove(self._rightAngryBrow)
            self._leftSadBrow = Path(Point(21, -25), Point(31, -29))
            self._rightSadBrow = Path(Point(34, -29), Point(44, -25))
            self._leftSadBrow.setBorderWidth(2)
            self._rightSadBrow.setBorderWidth(2)
            if self._direction == 'left':
                self._leftSadBrow.move(-66, 0)
                self._rightSadBrow.move(-66, 0)
            self.add(self._leftSadBrow)
            self.add(self._rightSadBrow)
        self._expression = expression

    def changeColor(self, color = 'white'):
        '''
        changes the color of the cat

        Attributes
        color  - String value; sets the color of the cat; includes all regular cs1graphics colors as well as a 'black and white' option, default value 'white'

        '''
        self._color = color
        if color == 'black and white':
            self._head.setFillColor('white')
            self._body.setFillColor('black')
        else:
            self._head.setFillColor(color)
            self._body.setFillColor(color)

    def meow(self):
        '''
        make the cat meow
        '''
        if self._expression != 'neutral':
            if self._expression == 'bored':
                self.remove(self._leftBoredBrow)
                self.remove(self._rightBoredBrow)
            if self._expression == 'fed up':
                self.remove(self._leftFedUpBrow)
                self.remove(self._rightFedUpBrow)
            if self._expression == 'angry':
                self.remove(self._leftAngryBrow)
            if self._expression == 'sad':
                self.remove(self._leftSadBrow)
                self.remove(self._rightSadBrow)
        self._expression = 'neutral'
        self.remove(self._head)
        self.remove(self._leftEye)
        self.remove(self._rightEye)
        self.remove(self._leftPupil)
        self.remove(self._rightPupil)
        self.remove(self._mouth)
        self.remove(self._leftEar)
        self.remove(self._rightEar)

        self._meowHead = Ellipse(32, 20, Point(33, -18))
        if self._color == 'black and white':
            self._meowHead.setFillColor(('white'))
        else:
            self._meowHead.setFillColor(self._color)
        self._meowLeftEye = Ellipse(8, 4, Point(26, -22))
        self._meowLeftEye.setFillColor('white')
        self._meowRightEye = self._meowLeftEye.clone()
        self._meowRightEye.move(13, 0)
        self._meowLeftPupil = Circle(1, Point(26, -22))
        self._meowLeftPupil.setFillColor('black')
        self._meowRightPupil = Circle(1, Point(39, -22))
        self._meowRightPupil.setFillColor('black')
        self._meowLeftEar = Path(Point(21,-24), Point(21, -30), Point(29, -29))
        self._meowLeftEar.setBorderWidth(3)
        self._meowRightEar = self._meowLeftEar.clone()
        self._meowRightEar.flip()
        self._meowRightEar.move(26,1)
        self._meowMouth = Ellipse(12, 6, Point(33, -13))
        if self._color == 'black':
            self._meowMouth.setFillColor('darkgray')
        else:
            self._meowMouth.setFillColor('black')
        self._meowText = Text('MEEOWOOOW', 20, Point(30, -42))

        if self._direction == 'left':
            self._meowHead.move(-66, 0)
            self._meowLeftEye.move(-66, 0)
            self._meowRightEye.move(-66, 0)
            self._meowLeftEar.move(-66, 0)
            self._meowRightEar.move(-66, 0)
            self._meowLeftPupil.move(-66, 0)
            self._meowRightPupil.move(-66, 0)
            self._meowMouth.move(-66, 0)

        self.add(self._meowHead)
        self.add(self._meowLeftEye)
        self.add(self._meowRightEye)
        self.add(self._meowLeftEar)
        self.add(self._meowRightEar)
        self.add(self._meowLeftPupil)
        self.add(self._meowRightPupil)
        self.add(self._meowMouth)
        self.add(self._meowText)

    def stopMeow(self):
        '''
        stops the cat's meow and returns it to a neutral expression
        '''
        self.remove(self._meowHead)
        self.remove(self._meowLeftEye)
        self.remove(self._meowRightEye)
        self.remove(self._meowLeftEar)
        self.remove(self._meowRightEar)
        self.remove(self._meowLeftPupil)
        self.remove(self._meowRightPupil)
        self.remove(self._meowMouth)
        self.remove(self._meowText)

        self.add(self._head)
        self.add(self._leftEye)
        self.add(self._rightEye)
        self.add(self._leftPupil)
        self.add(self._rightPupil)
        self.add(self._mouth)
        self.add(self._leftEar)
        self.add(self._rightEar)

    def changeDirection(self):
        '''
        changes the direction of the cat so that its facing the left or the right; changes the direction to the opposite of what it is currently
        '''
        if self._direction == 'right':
            self._head.move(-66, 0)
            self._leftEye.move(-66, 0)
            self._rightEye.move(-66, 0)
            self._leftPupil.move(-66, 0)
            self._rightPupil.move(-66, 0)
            self._leftEar.move(-66, 0)
            self._rightEar.move(-66, 0)
            self._mouth.move(-66, 0)
            self._tail.flip()
            if self._fat:
                self._tail.move(96, 0)
            else:
                self._tail.move(74, 0)
            self._direction = 'left'
        else:
            self._head.move(66, 0)
            self._leftEye.move(66, 0)
            self._rightEye.move(66, 0)
            self._leftPupil.move(66, 0)
            self._rightPupil.move(66, 0)
            self._leftEar.move(66, 0)
            self._rightEar.move(66, 0)
            self._mouth.move(66, 0)
            self._tail.flip()
            if not self._fat:
                self._tail.move(-96, 0)
            else:
                self._tail.move(-74, 0)
            self._direction = 'right'

    def speech(self, message, time = 2):
        '''
        adds text above the cat

        Attributes
        message  -  String value, the text that will appear above the cat
        time     -  Int value, how long the text will be displayed, default value of 2 seoncds
        '''
        self._text = Text(message, 14, Point(30, -50))
        self._text
        self.add(self._text)
        sleep(time)
        self.remove(self._text)

if __name__ == "__main__":
    paper = Canvas(500,300)

    cat1 = Cat('white', True, 'black', True, 'bored')
    cat1.move(120, 220)

    cat2 = Cat('darkgray')
    cat2.move(550,220)
    cat2.changeDirection()

    cat3 = Cat('black', True, 'gray', False)
    cat3.move(90,110)
    cat3.changeDirection()
    cat4 = Cat('red', True, 'green', True)
    cat4.move(270,130)
    cat4.changeDirection()
    cat5 = Cat()
    cat5.move(400,90)
    cat6 = Cat('black and white', False, 'black', True)
    cat6.move(430,260)

    paper.add(cat1)
    paper.add(cat2)
    for i in range(50):
        cat2.move(-5, 0)
        sleep(0.01)

    cat2.speech('wanna play?')
    sleep(0.5)
    cat1.speech('no go away')
    sleep(0.5)
    cat2.speech('cmon, get up lets play')
    sleep(0.5)
    cat1.changeExpression('fed up')
    cat1.speech('i said go away')
    sleep(0.5)
    cat2.changeExpression('sad')
    cat2.speech('pleaase i wanna play')
    sleep(0.5)
    cat1.changeExpression('angry')
    cat1.speech('**** OFF')
    cat2.speech('pleeaaase')
    cat1.meow()
    sleep(0.7)
    cat2.meow()
    sleep(0.7)
    paper.add(cat3)
    cat3.meow()
    sleep(0.5)
    paper.add(cat4)
    cat4.meow()
    sleep(0.3)
    paper.add(cat5)
    cat5.meow()
    sleep(0.2)
    paper.add(cat6)
    cat6.meow()
    sleep(3)
    cat1.stopMeow()
    cat2.stopMeow()
    cat3.stopMeow()
    cat4.stopMeow()
    cat5.stopMeow()
    cat6.stopMeow()
    sleep(0.5)

    cat1.makeHealthy()
    cat2.makeFat()
    cat4.addSpots()
    cat5.changeExpression('angry')
    cat6.changeDirection()
    cat3.changeExpression('bored')
    cat5.changeColor('green')


from __future__ import print_function

from keras.models import Model
from keras.layers import Input, LSTM, Dense
import numpy as np
import gc
import io

from pickle import load

from data_generator import DataGenerator

batch_size = 64
epochs = 10
latent_dim = 256
num_samples = 10000

# Parameters
params = {'batch_size': batch_size,
          'n_channels': 1,
          'shuffle': True}

stories = load(open('./data/hackernoon_tutorial/review_dataset.pkl', 'rb'))
print('Loaded Stories %d' % len(stories))
print(type(stories))
print(stories)

# Vectorize the data.
input_texts = []
target_texts = []
input_characters = set()
target_characters = set()
for story in stories:
    input_text = story['story']
    target_text = story['highlights']

    # We use "tab" as the "start sequence" character
    # for the targets, and "\n" as "end sequence" character.
    target_text = '\t' + target_text + '\n'
    input_texts.append(input_text)
    target_texts.append(target_text)
    for char in input_text:
        if char not in input_characters:
            input_characters.add(char)
    for char in target_text:
        if char not in target_characters:
            target_characters.add(char)

input_characters = sorted(list(input_characters))
target_characters = sorted(list(target_characters))
num_encoder_tokens = len(input_characters)
num_decoder_tokens = len(target_characters)
max_encoder_seq_length = max([len(txt) for txt in input_texts])
max_decoder_seq_length = max([len(txt) for txt in target_texts])

print('Number of samples:', len(input_texts))
print('Number of unique input tokens:', num_encoder_tokens)
print('Number of unique output tokens:', num_decoder_tokens)
print('Max sequence length for inputs:', max_encoder_seq_length)
print('Max sequence length for outputs:', max_decoder_seq_length)

input_token_index = dict(
    [(char, i) for i, char in enumerate(input_characters)])
target_token_index = dict(
    [(char, i) for i, char in enumerate(target_characters)])

# encoder_input_data = np.zeros(
#     (len(input_texts), max_encoder_seq_length, num_encoder_tokens),
#     dtype='float32')
# decoder_input_data = np.zeros(
#     (len(input_texts), max_decoder_seq_length, num_decoder_tokens),
#     dtype='float32')
# decoder_target_data = np.zeros(
#     (len(input_texts), max_decoder_seq_length, num_decoder_tokens),
#     dtype='float32')
#
# for i, (input_text, target_text) in enumerate(zip(input_texts, target_texts)):
#     for t, char in enumerate(input_text):
#         encoder_input_data[i, t, input_token_index[char]] = 1.
#     for t, char in enumerate(target_text):
#         # decoder_target_data is ahead of decoder_input_data by one timestep
#         decoder_input_data[i, t, target_token_index[char]] = 1.
#         if t > 0:
#             # decoder_target_data will be ahead by one timestep
#             # and will not include the start character.
#             decoder_target_data[i, t - 1, target_token_index[char]] = 1.

print(target_texts)

training_generator = DataGenerator(input_token_index, target_token_index,
                                   input_texts, target_texts,
                                   max_encoder_seq_length, num_encoder_tokens,
                                   max_decoder_seq_length, num_decoder_tokens, **params)

# Define an input sequence and process it.
encoder_inputs = Input(shape=(None, num_encoder_tokens))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
# We discard `encoder_outputs` and only keep the states.
encoder_states = [state_h, state_c]

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None, num_decoder_tokens))
# We set up our decoder to return full output sequences,
# and to return internal states as well. We don't use the
# return states in the training model, but we will use them in inference.
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
                                     initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

# Define the model that will turn
# `encoder_input_data` & `decoder_input_data` into `decoder_target_data`
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)

# Run training
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
model.fit_generator(generator=training_generator, epochs=epochs)

# Save model
model.save('./data/hackernoon_tutorial/model.h5')


# import vboxapi
# you are fascinated with the ability to do fuck over computer.
import virtualbox
import time
# how to get a running console?
vbox = virtualbox.VirtualBox()
session=virtualbox.Session()
machine=vbox.find_machine("TinyPlus")
progress=machine.launch_vm_process(session,"gui","")
# not working.
# progress=machine.launch_vm_process(session,"console","")
progress.wait_for_completion()
# how to pass it around?
time.sleep(5)
# not receiving shit.
session.console.keyboard.put_keys("Hello, world!")
# how to get output?
# session.unlock_machine()
# we do this process over and over again.
# progress=machine.launch_vm_process(session,"gui","")
# fast like shit.
# without session?
# ['TinyPlus']
# print([m.name for m in vbox.machines])
# it is off.
# print
# what the heck? why not using ssh?
# we have getting used to it. but how to install on tinycore?


from django.test import TestCase
from department.models.department import Department
from department.models.employee import Employee
from department.models.vacation import Vacation
from datetime import date

class DepartmentTest(TestCase):

    def setUp(self):

        self.department = Department.objects.create(
            name="some department")

    def test_label(self):
        department = Department.objects.get(id=self.department.pk)
        field_label = department._meta.get_field('name').verbose_name
        self.assertEqual(field_label, 'Department:')

    def test_unique(self):
        department = Department.objects.get(id=self.department.pk)
        unique = department._meta.get_field('name').unique
        self.assertTrue(unique)

    def test_max_length(self):
        department = Department.objects.get(id=self.department.pk)
        max_length = department._meta.get_field('name').max_length
        self.assertEqual(max_length, 30)

    def test_get_absolute_url(self):
        self.assertEqual(self.department.get_absolute_url(), '/')

    def test_string_representation(self):
        department = Department(name='A sample name')
        self.assertEqual(str(department), department.name)

    def test_content(self):
        self.assertEqual(f'{self.department.name}', 'some department')

    def test_salary(self):
        SALARY = [100, 150, 200, 250, 300, 350, 400, 450, 500]
        salary = []
        for i in range(100, 1000, 100):
            self.employee = Employee.objects.create(
                name_employee=f"employee-{i}",
                dep=self.department,
                salary=i,
                position="some position",
                date=date(2020, 2, 3),
            )
            salary.append(self.department.salary)

        self.assertEqual(SALARY, salary)

    def test_amount(self):
        for i in range(1, 10):
            self.employee = Employee.objects.create(
                name_employee=f"employee-{i}",
                dep=self.department,
                salary=100,
                position="some position",
                date=date(2020, 2, 3),
            )
            self.assertEqual(self.department.amount, i)

class EmployeeTest(TestCase):

    def setUp(self):

        self.department = Department.objects.create(
            name="some department"
        )
        self.employee = Employee.objects.create(
            name_employee="some employee",
            dep=self.department,
            salary=100,
            position="some position",
            date=date(2020, 2, 3),
        )

    def test_label(self):
        employee = Employee.objects.get(id=self.employee.pk)
        field_label = employee._meta.get_field('name_employee').verbose_name
        self.assertEqual(field_label, 'Employee:')
        field_label = employee._meta.get_field('dep').verbose_name
        self.assertEqual(field_label, 'dep')
        field_label = employee._meta.get_field('salary').verbose_name
        self.assertEqual(field_label, 'Salary:')
        field_label = employee._meta.get_field('position').verbose_name
        self.assertEqual(field_label, 'Position:')
        field_label = employee._meta.get_field('date').verbose_name
        self.assertEqual(field_label, 'Date:')

    def test_unique(self):
        employee = Employee.objects.get(id=self.employee.pk)
        unique = employee._meta.get_field('name_employee').unique
        self.assertTrue(unique)

    def test_max_length(self):
        employee = Employee.objects.get(id=self.employee.pk)
        max_length = employee._meta.get_field('name_employee').max_length
        self.assertEqual(max_length, 30)
        max_length = employee._meta.get_field('position').max_length
        self.assertEqual(max_length, 30)

    def test_get_absolute_url(self):
        self.assertEqual(self.employee.get_absolute_url(), '/employee/')

    def test_string_representation(self):
        employee = Employee(name_employee='A sample name')
        self.assertEqual(str(employee), employee.name_employee)

    def test_content(self):
        self.assertEqual(f'{self.employee.name_employee}', 'some employee')
        self.assertEqual(f'{self.employee.dep}', 'some department')
        self.assertEqual(f'{self.employee.salary}', '100')
        self.assertEqual(f'{self.employee.position}', 'some position')
        self.assertEqual(f'{self.employee.date}', '2020-02-03')

class VacationTest(TestCase):

    def setUp(self):

        self.employee = Employee.objects.create(
            name_employee="some employee",
            salary=100,
            date=date(2020, 2, 3),
        )
        self.vacation = Vacation.objects.create(
            name_vacation=self.employee,
            date1=date(2020, 3, 3),
            date2=date(2020, 4, 4)
        )

    def test_label(self):
        vacation = Vacation.objects.get(id=self.vacation.pk)
        field_label = vacation._meta.get_field('date1').verbose_name
        self.assertEqual(field_label, 'Date start:')
        field_label = vacation._meta.get_field('date2').verbose_name
        self.assertEqual(field_label, 'Date end:')

    def test_get_absolute_url(self):
        self.assertEqual(self.vacation.get_absolute_url(), '/vacation/')

    def test_string_representation(self):
        vacation = Vacation(name_vacation=self.employee)
        self.assertEqual(str(vacation), f'{vacation.name_vacation}')

    def test_content(self):
        self.assertEqual(f'{self.vacation.name_vacation}', 'some employee')
        self.assertEqual(f'{self.vacation.date1}', '2020-03-03')
        self.assertEqual(f'{self.vacation.date2}', '2020-04-04')


from pprint import pprint

def incrange(start, end):
    return range(start, end + 1)

def adjacent(x_start, y_start, x_limit=None, y_limit=None):
    square = []
    for x in incrange(x_start - 1, x_start + 1):
        for y in incrange(y_start - 1, y_start + 1):
            if((x == x_start and y == y_start) or
               (x_limit is not None and (x < 0 or x >= x_limit)) or
               (y_limit is not None and (y < 0 or y >= y_limit))):
                continue
            square.append((x, y))
    return square