'''Integration test of agent setup of Moulder and Actuator organs with multiple
output Directions and Resource Maps

'''
import pytest
from fjarrsyn.core.agent import Agent

from fjarrsyn.core.instructor import Moulder, Actuator
from fjarrsyn.core.message import Belief, Direction, Resource, MessageOperator
from fjarrsyn.core.scaffold_map import ResourceMap, MapCollection
from fjarrsyn.core.array import EmptyFlashError

REF_REPO = [('v', 0, 1.0), ('h', -1, 0.5), ('v', -1, 1.0), ('h', 1, 0.5)]
REF_E = [15.0, 10.0]

def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

def make_decision(s, h, a):
    energy_tot = 0.0
    if s < 50.0:
        return 0, 0.0, 0, 0.0, energy_tot
    else:
        h_m = 0.5
        a_m = 1.0
        if h < 1.0:
            h_d = -1
            energy_tot += 5.0
        else:
            h_d = 1
            energy_tot += 3.0

        if a < -0.3:
            a_d = -1
            energy_tot += 2.0
        elif a > 0.3:
            a_d = 1
            energy_tot += 2.0
        else:
            a_d = 0
            energy_tot += 0.0

        return h_d, h_m, a_d, a_m, -1.0 * energy_tot

REPO = []
def move_rule_horizontal(d, m):
    REPO.append(('h',d,m))
def move_rule_vertical(d, m):
    REPO.append(('v',d,m))

def test_main():
    #
    # Define Messages
    #
    belief = Belief('Projectile status', ('speed', 'height', 'angle'))
    belief.set_values([100.0, 0.3, 0.2])
    direction = Direction('motion', ('horizontal direction',
                                     'horizontal magnitude',
                                     'vertical direction',
                                     'vertical magnitude'))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_resource', ('internal_energy',))
    agent_resources.set_values(20.0)
    change_energy = ResourceMap('adjust_energy', 'delta', 'internal_energy', ('expend_energy',))

    #
    # Define Organs and their associated messages
    #
    moulder = Moulder('take evasive action?', make_decision,
                      belief, direction,
                      change_energy)
    splitter_1 = MessageOperator(direction, slice_labels=['horizontal direction',
                                                          'horizontal magnitude'])
    splitter_2 = MessageOperator(direction, slice_labels=['vertical direction',
                                                          'vertical magnitude'])
    actuator1 = Actuator('move left right', move_rule_horizontal, splitter_1)
    actuator2 = Actuator('move up down', move_rule_vertical, splitter_2)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(moulder)
    agent.set_organ(actuator1)
    agent.set_organ(actuator2)
    agent.set_scaffold(agent_resources)
    agent.set_message(belief)

    #
    # Decide on direction and execute action
    #
    agent.mould('take evasive action?')
    agent.act('move up down')
    agent.act('move left right')
    assert (agent.resource['internal_energy'] == REF_E[0])
    belief.set_values([100.0, 1.3, -0.5])
    agent.mould('take evasive action?')
    agent.act('move up down')
    agent.act('move left right')
    assert (agent.resource['internal_energy'] == REF_E[1])
    for e1, e2 in zip(REPO, REF_REPO):
        assert(e1 == e2)

    try:
        agent.act('move up down')
        raise AssertionError('Action without preceding moulding did not raise exception')
    except EmptyFlashError:
        pass
    else:
        raise AssertionError('Action without preceding moulding did not raise expected exception')
    try:
        agent.act('move left right')
        raise AssertionError('Action without preceding moulding did not raise exception')
    except EmptyFlashError:
        pass
    else:
        raise AssertionError('Action without preceding moulding did not raise expected exception')


#-*-coding:utf-8-*-
# 游戏主程序

from gui.graph import *
from pygame.locals import *
import pygame
from sys import exit

from tools.game import Game
from gui.graph import Graph
from gui.lost import Lost
from gui.win import Win
from gui.welcome import Welcome

row=4# 行数
gb=Game(row,True)
gb.start_test()
gr=Graph(row)
gr.start_graph('2048')

we=Welcome(gr.screen)
we.get_welcome()

# 随机生成数和位置并初始化
n=gb.get_rand_num()
v=gb.get_rand_vector()
gb.change_num(v,n)
gr.background()
box=gb.get_box()
gr.playbox(box)
gr.flash()

win_number=2048

end=0# 结束因子，0为未结束，1为输，2为赢

while end==0 or end==2:
    d=None
    for event in pygame.event.get():
        if event.type==QUIT:
            exit()
        elif event.type==KEYDOWN:
                if event.key==K_ESCAPE:
                    exit()
                elif event.key==K_UP:
                    d='u'
                elif event.key==K_DOWN:
                    d='d'
                elif event.key==K_LEFT:
                    d='l'
                elif event.key==K_RIGHT:
                    d='r'

    if d:
        # 移动
        gb.move(d)
        gr.playbox(gb.get_box())
        gr.flash()
        n=gb.get_rand_num()
        v=gb.get_rand_vector()
        if v:
            gb.change_num(v,n)
        else:
            end=1

        max=gb.get_max()# 判断最大值
        # 赢时的画面
        if max==win_number and end==0:
            win=Win(gr.screen)
            win.get_win()
            end=2

    gr.playbox(gb.get_box())
    gr.flash()

# 输时的画面
if end==1:
    lost=Lost(gr.screen)
    lost.get_lost()

gb.end_test()


import os
import random
import shutil

# 定义文件夹路径和切分比例

folder_path = r"D:\04DataSets\03myDataSet28/"
target_name = "03myDataSet28/"
img_end = r"\images\train2017/"
txt_end = r"\labels\train2017/"

img_src_dir = folder_path + img_end
txt_src_dir = folder_path + txt_end
img_dsc_dir = folder_path + img_end.replace("train2017", "val2017")
txt_dsc_dir = folder_path + txt_end.replace("train2017", "val2017")
os.makedirs(img_dsc_dir, exist_ok=True)
os.makedirs(txt_dsc_dir, exist_ok=True)
split_ratio = 0.7
# 读取文件夹下所有文件
file_list = os.listdir(img_src_dir)

# 打乱文件列表的顺序
random.shuffle(file_list)

# 计算切分点
split_index = int(len(file_list) * split_ratio)

# 切分文件列表
train_file_list = file_list[:split_index]
val_file_list = file_list[split_index:]

# 复制测试集文件到特定目录
for file in val_file_list:
    img_src_path = img_src_dir + file
    img_dst_path = img_dsc_dir + file
    shutil.move(img_src_path, img_dst_path)
    txt_src_path = txt_src_dir + file.replace("bmp", "txt")
    txt_dst_path = txt_dsc_dir + file.replace("bmp", "txt")
    shutil.move(txt_src_path, txt_dst_path)


from pathlib import Path
import pandas as pd

import nltk
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
import string

# Importing Gensim
import gensim
from gensim import corpora

# to suppress warnings
from warnings import filterwarnings
filterwarnings('ignore')

proc_data_dir = Path('Prepared data')
proc_data_dir = Path('Raw data')
data = pd.read_excel(proc_data_dir / 'training_data_AlixPartners_Val_Dist.xlsx')

corpus = list(data['Paragraph'])
corpus = list(set(corpus))
############## Pre-proc
# stop loss words
stop = set(stopwords.words('english'))

# punctuation
exclude = set(string.punctuation)

# lemmatization
lemma = WordNetLemmatizer()

# One function for all the steps:
def clean(doc):

    # convert text into lower case + split into words
    stop_free = " ".join([i for i in doc.lower().split() if i not in stop])

    # remove any stop words present
    punc_free = ''.join(ch for ch in stop_free if ch not in exclude)

    # remove punctuations + normalize the text
    normalized = " ".join(lemma.lemmatize(word) for word in punc_free.split())
    return normalized

# clean data stored in a new list
clean_corpus = [clean(doc).split() for doc in corpus]

dict_ = corpora.Dictionary(clean_corpus)
doc_term_matrix = [dict_.doc2bow(i) for i in clean_corpus]

Lda = gensim.models.ldamodel.LdaModel
ldamodel = Lda(doc_term_matrix, num_topics=10, id2word = dict_, passes=1, random_state=0, eval_every=None)
ldamodel.print_topics()
print(ldamodel.print_topics(num_topics=10, num_words=5))

count = 0
for i in ldamodel[doc_term_matrix]:
    print("doc : ",count,i)
    count += 1


#Python 2.x program to transcribe an Audio file
import speech_recognition as sr
from gtts import gTTS
import os
AUDIO_FILE = ("Recording.wav")

# use the audio file as the audio source

r = sr.Recognizer()

with sr.AudioFile(AUDIO_FILE) as source:
	#reads the audio file. Here we use record instead of
	#listen
	audio = r.record(source)

try:
    x=r.recognize_google(audio)
    print("The audio file contains: " + x)

except sr.UnknownValueError:
	print("Google Speech Recognition could not understand audio")

except sr.RequestError as e:
	print("Could not request results from Google Speech Recognition service; {0}".format(e))

language='en'
myobj = gTTS(text=x, lang=language, slow=False)
myobj.save("welcome.wav")

# Playing the converted file
os.system("mpg321 recording.wav")


from typing import List
from fastapi import Depends, Request, APIRouter
from pydantic import BaseModel
from sqlalchemy.orm import Session
from auth.database import User
from models.models import *
from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory="templates")
router = APIRouter()

@router.get('/')
def select_all_templates(request: Request, db: Session = Depends(get_db)):
    html_templates = db.query(HTMLtemplate).all()
    return templates.TemplateResponse("main_page.html", {"request": request, 'templates': html_templates})
    #return html_templates

@router.get("/post/{name}")
async def get_post_by_name(request: Request, name: str, db: Session = Depends(get_db)):
    post = db.query(HTMLtemplate).filter(HTMLtemplate.title == name)
    #return {"post": post.__str__()}
    return templates.TemplateResponse("main_page.html", {"request": request, 'templates': post, 'message': 'Шаблоны по вашему запросу:'})

@router.get("/posts/{{ tag_title }}")
def get_posts_on_tag(tag_title: str, db: Session = Depends(get_db)):
    posts = db.query(HTMLtemplate).join(HTMLtemplate.tags).filter(Tag.title == tag_title).all()
    return posts

@router.delete('/post_delete')
def delete_template(db: Session = Depends(get_db), title: str = 'post name'):
    post = db.query(HTMLtemplate).filter(HTMLtemplate.title == title).first()
    if post:
        db.delete(post)
        db.commit()
        return f'Пост "{ title }" успешно удалён'
    else:
        return f'Пост "{ title }" не найден ('

class HTMLtemplateCreate(BaseModel):
    title: str
    text: str
    tag_ids: List[int]

@router.post("/htmltemplates")
def create_htmltemplate(htmltemplate_data: HTMLtemplateCreate, db: Session = Depends(get_db)):
    tag_ids = htmltemplate_data.tag_ids
    htmltemplate = HTMLtemplate(title=htmltemplate_data.title, text=htmltemplate_data.text)

    # берём юзера и теги для добавления
    tags = db.query(Tag).filter(Tag.id.in_(tag_ids)).all()
    author = db.query(User).all()

    # добавляем связь тегов и юзера с постом
    htmltemplate.tags = tags
    htmltemplate.author = author

    # Добавление объекта в сессию и сохранение изменений
    db.add(htmltemplate)
    db.commit()
    db.refresh(htmltemplate)

    #return {"message": "HTMLtemplate created successfully"}
    return htmltemplate


a,b,c = [int(i) for i in input().split()]

difer1 = abs(a-b)
difer2 = abs(b-c)

if (a>b and c>=b) :
	feliz = True
elif (a<b and b>=c) :
	feliz = False
elif (a<b<c):
	if difer1>difer2:
		feliz = False
	else :
		feliz = True
elif (a>b>c) :
	if difer1>difer2:
		feliz = True
	else :
		feliz = False
elif a==b :
	if c>b :
		feliz = True
	else :
		feliz = False

if feliz :
	print(":)")
else :
	print(":(")


import unittest
from overseer import Overseer, OverseerWithModQuality, OverseerNoQuality

from mnm_repr import Model
from archive import Archive, CheckPointFail, NewResults, AcceptedResults, AdditionalModels, CheckPointSuccess
from revision_module import RevCAddB, RevCIAddR
from experiment_module import BasicExpModuleNoCosts
from oracle import Oracle
from quality_module import QualityModule

class OverseerTest(unittest.TestCase):
	def setUp(self):
		archive = Archive()
		rev_mod = RevCAddB(archive)
		exp_mod = BasicExpModuleNoCosts(archive, None)
		oracle = Oracle(archive, [], [], None, [], [], [])
		qual_mod = QualityModule(archive)
		stop_threshold = 2
		max_time = 4
		suffix = 'test'
		self.overseer_qual = OverseerWithModQuality(archive, rev_mod, exp_mod, oracle, 2, qual_mod, max_time, suffix, stop_threshold)
		self.overseer_no_qual = OverseerNoQuality(archive, rev_mod, exp_mod, oracle, 2, max_time, suffix, stop_threshold)

	def test_available_transitions(self):
		self.overseer_qual.current_state = 'quality_recalculated'
		self.overseer_no_qual.current_state = 'models_tested_and_revised'
		qual_av = self.overseer_qual.available_transitions()
		no_qual_av = self.overseer_no_qual.available_transitions()
		self.assertEqual(len(qual_av), 2)
		self.assertEqual(len(no_qual_av), 2)

	def test_do_transition(self):
		state_before = self.overseer_qual.current_state
		self.overseer_qual.do_transition('start_development')
		state_after = self.overseer_qual.current_state
		self.assertEqual(state_before, 'start')
		self.assertEqual(state_after, 'models_tested_and_revised')

	def test_do_check_ignoring_negative(self):
		mod = Model('m_0', [], [], [])
		archive = Archive()
		archive.working_models.update([mod])
		rev_mod = RevCIAddR(archive)
		exp_mod = BasicExpModuleNoCosts(archive, None)
		oracle = Oracle(archive, [], [], None, [], [], [])
		qual_mod = QualityModule(archive)
		max_time = 4
		suffix = 'test'
		overseer = OverseerWithModQuality(archive, rev_mod, exp_mod, oracle, 2, qual_mod, 10, max_time, suffix, 2)
		overseer.cycles_since_last_new_model = 5
		overseer.cycles_since_best_model_changed = 5
		overseer.current_best_models = set([mod])
		before = list(overseer.archive.development_history)
		overseer.do_check()
		after = overseer.archive.development_history[-1]
		self.assertEqual(before, [])
		self.assertIsInstance(after, CheckPointFail)

	def test_do_check_noignoring_negative(self):
		before = list(self.overseer_qual.archive.development_history)
		self.overseer_qual.do_check()
		after = self.overseer_qual.archive.development_history[-1]
		self.assertEqual(before, [])
		self.assertIsInstance(after, CheckPointFail)

	def test_record_result_positive(self):
		self.overseer_qual.archive.development_history.append(NewResults([]))
		self.overseer_qual.record_result()
		after = self.overseer_qual.archive.development_history[-1]
		self.assertIsInstance(after, AcceptedResults)

	def test_record_result_error(self):
		self.overseer_qual.archive.development_history.append(1)
		self.assertRaises(TypeError, self.overseer_qual.record_result)

	def test_was_new_model_produced_since_last_check_positive(self):
		self.overseer_qual.archive.development_history.append(CheckPointSuccess())
		self.overseer_qual.archive.development_history.append(AdditionalModels([]))
		out = self.overseer_qual.was_new_model_produced_since_last_check()
		self.assertEqual(out, True)

	def test_was_new_model_produced_since_last_check_negative_one(self):
		self.overseer_qual.archive.development_history.append(CheckPointSuccess())
		out = self.overseer_qual.was_new_model_produced_since_last_check()
		self.assertEqual(out, False)

	def test_was_new_model_produced_since_last_check_negative_two(self):
		out = self.overseer_qual.was_new_model_produced_since_last_check()
		self.assertEqual(out, False)

	def test_did_the_best_model_change_since_last_check_positive(self):
		mod = Model('m_0', [], [], [])
		self.overseer_qual.archive.working_models.update([mod])
		out = self.overseer_qual.did_the_best_model_change_since_last_check()
		self.assertEqual(out, True)

	def test_did_the_best_model_change_since_last_check_negative(self):
		mod = Model('m_0', [], [], [])
		self.overseer_qual.archive.working_models.update([mod])
		self.overseer_qual.current_best_models = set([mod])
		out = self.overseer_qual.did_the_best_model_change_since_last_check()
		self.assertEqual(out, False)

#	def test_cond_1_with_qual_positive(self):

#	def test_cond_1_with_qual_negative(self):

#	def test_cond_2_with_qual_positive(self):

#	def test_cond_2_with_qual_negative(self):

#	def test_cond_1_positive(self): # no qual

#	def test_cond_1_negative(self): # no qual

#	def test_cond_2_positive(self): # no qual

#	def test_cond_2_negative(self): # no qual

#	def test_cond_3_positive(self): # no qual

#	def test_cond_3_negative(self): # no qual

#	def test_cond_4_positive(self): # no qual

#	def test_cond_4_negative(self): # no qual


# Class to maintain the state of the program
class Config():
    """ Class to hold on to all instance variables used for state.
    """
    def __init__(self,
                 address,
                 tcpPort,
                 sessionID,
                 name,
                 peerList,
                 multiCastAddress,
                 multiCastPort,
                 downloadPath):
        self.address = address  # this is the local IP
        # port for file receiver to listen on
        self.tcpPort = tcpPort
        self.sessionID = sessionID
        self.name = name
        self.peerList = peerList
        self.multiCastAddress = multiCastAddress
        self.multiCastPort = multiCastPort
        self.downloadPath = downloadPath
        self.sessions = {}
        ''' Sessions currently downloading, only the Session IDs '''
        self.dlSessions = set()

    def closeSession(self, session):
        del self.sessions[session.id]


from PIL import Image
#import skimage as sk
#from skimage import io as sk_io
#import cv2

import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import image as mp_image

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

#file_path = filedialog.askopenfilename()
file_path = filedialog.askopenfilenames()

print(file_path)

images = []

for file in file_path:
  print(file)
  pil_image = Image.open(file)
  images.append(pil_image)

# Set up a figure of an appropriate size
fig = plt.figure(figsize=(12, 12))

image_num = 0
num_images = len(images)
# loop through the images
for image_idx in range(num_images):
    # Keep an incrementing count of each image
    a=fig.add_subplot(1, num_images, image_idx+1)
    # Add the image to the plot
    image_plot = plt.imshow(images[image_idx])
    # Add a caption with the folder name
    a.set_title("Image " + str(image_idx+1))

# Show the plot
plt.show()

image_num = 0
num_images = len(images)
# loop through the images
for image_idx in range(num_images):
    # Keep an incrementing count of each image
    a=fig.add_subplot(1, num_images, image_idx+1)
    # Add the image to the plot
    image_plot = plt.imshow(images[image_idx])
    # Add a caption with the folder name
    a.set_title("Image " + str(image_idx+1))
plt.show()


#!/usr/bin/python3.5

def add(p, q, a, b):
    return (b*q, a*q + p)

def gcd(a, b):
    while b > 0:
        a, b = b, a % b

    return a

t = int(input())
for e in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))

    p, q = b[-1], a[-1]
    #print('{}/{}'.format(p, q))
    for i in range(n-2, -1, -1):
        #print(i)
        #print('p : {}, q: {}, a: {}, b {}'.format(p, q, a[i], b[i]))
        p, q = add(p, q, a[i], b[i])

    t = gcd(p, q)
    p //= t
    q //= t

    print('{}/{}'.format(p, q))


# -*- coding: utf-8 -*-
"""Create instance of vrayscene."""
import os
import json
import appdirs
import requests

from maya import cmds
import maya.app.renderSetup.model.renderSetup as renderSetup

from openpype.hosts.maya.api import (
    lib,
    plugin
)
from openpype.settings import (
    get_system_settings,
    get_project_settings
)

from openpype.lib import requests_get
from openpype.pipeline import (
    CreatorError,
    legacy_io,
)
from openpype.modules import ModulesManager

class CreateVRayScene(plugin.Creator):
    """Create Vray Scene."""

    label = "VRay Scene"
    family = "vrayscene"
    icon = "cubes"

    _project_settings = None

    def __init__(self, *args, **kwargs):
        """Entry."""
        super(CreateVRayScene, self).__init__(*args, **kwargs)
        self._rs = renderSetup.instance()
        self.data["exportOnFarm"] = False
        deadline_settings = get_system_settings()["modules"]["deadline"]

        manager = ModulesManager()
        self.deadline_module = manager.modules_by_name["deadline"]

        if not deadline_settings["enabled"]:
            self.deadline_servers = {}
            return
        self._project_settings = get_project_settings(
            legacy_io.Session["AVALON_PROJECT"])

        try:
            default_servers = deadline_settings["deadline_urls"]
            project_servers = (
                self._project_settings["deadline"]["deadline_servers"]
            )
            self.deadline_servers = {
                k: default_servers[k]
                for k in project_servers
                if k in default_servers
            }

            if not self.deadline_servers:
                self.deadline_servers = default_servers

        except AttributeError:
            # Handle situation were we had only one url for deadline.
            # get default deadline webservice url from deadline module
            self.deadline_servers = self.deadline_module.deadline_urls

    def process(self):
        """Entry point."""
        exists = cmds.ls(self.name)
        if exists:
            return cmds.warning("%s already exists." % exists[0])

        use_selection = self.options.get("useSelection")
        with lib.undo_chunk():
            self._create_vray_instance_settings()
            self.instance = super(CreateVRayScene, self).process()

            index = 1
            namespace_name = "_{}".format(str(self.instance))
            try:
                cmds.namespace(rm=namespace_name)
            except RuntimeError:
                # namespace is not empty, so we leave it untouched
                pass

            while(cmds.namespace(exists=namespace_name)):
                namespace_name = "_{}{}".format(str(self.instance), index)
                index += 1

            namespace = cmds.namespace(add=namespace_name)

            # add Deadline server selection list
            if self.deadline_servers:
                cmds.scriptJob(
                    attributeChange=[
                        "{}.deadlineServers".format(self.instance),
                        self._deadline_webservice_changed
                    ])

            # create namespace with instance
            layers = self._rs.getRenderLayers()
            if use_selection:
                print(">>> processing existing layers")
                sets = []
                for layer in layers:
                    print("  - creating set for {}".format(layer.name()))
                    render_set = cmds.sets(
                        n="{}:{}".format(namespace, layer.name()))
                    sets.append(render_set)
                cmds.sets(sets, forceElement=self.instance)

            # if no render layers are present, create default one with
            # asterix selector
            if not layers:
                render_layer = self._rs.createRenderLayer('Main')
                collection = render_layer.createCollection("defaultCollection")
                collection.getSelector().setPattern('*')

    def _deadline_webservice_changed(self):
        """Refresh Deadline server dependent options."""
        # get selected server
        from maya import cmds
        webservice = self.deadline_servers[
            self.server_aliases[
                cmds.getAttr("{}.deadlineServers".format(self.instance))
            ]
        ]
        pools = self.deadline_module.get_deadline_pools(webservice)
        cmds.deleteAttr("{}.primaryPool".format(self.instance))
        cmds.deleteAttr("{}.secondaryPool".format(self.instance))
        cmds.addAttr(self.instance, longName="primaryPool",
                     attributeType="enum",
                     enumName=":".join(pools))
        cmds.addAttr(self.instance, longName="secondaryPool",
                     attributeType="enum",
                     enumName=":".join(["-"] + pools))

    def _create_vray_instance_settings(self):
        # get pools
        pools = []

        system_settings = get_system_settings()["modules"]

        deadline_enabled = system_settings["deadline"]["enabled"]
        muster_enabled = system_settings["muster"]["enabled"]
        muster_url = system_settings["muster"]["MUSTER_REST_URL"]

        if deadline_enabled and muster_enabled:
            self.log.error(
                "Both Deadline and Muster are enabled. " "Cannot support both."
            )
            raise CreatorError("Both Deadline and Muster are enabled")

        self.server_aliases = self.deadline_servers.keys()
        self.data["deadlineServers"] = self.server_aliases

        if deadline_enabled:
            # if default server is not between selected, use first one for
            # initial list of pools.
            try:
                deadline_url = self.deadline_servers["default"]
            except KeyError:
                deadline_url = [
                    self.deadline_servers[k]
                    for k in self.deadline_servers.keys()
                ][0]

            pool_names = self.deadline_module.get_deadline_pools(deadline_url)

        if muster_enabled:
            self.log.info(">>> Loading Muster credentials ...")
            self._load_credentials()
            self.log.info(">>> Getting pools ...")
            try:
                pools = self._get_muster_pools()
            except requests.exceptions.HTTPError as e:
                if e.startswith("401"):
                    self.log.warning("access token expired")
                    self._show_login()
                    raise CreatorError("Access token expired")
            except requests.exceptions.ConnectionError:
                self.log.error("Cannot connect to Muster API endpoint.")
                raise CreatorError("Cannot connect to {}".format(muster_url))
            pool_names = []
            for pool in pools:
                self.log.info("  - pool: {}".format(pool["name"]))
                pool_names.append(pool["name"])

            self.data["primaryPool"] = pool_names

        self.data["suspendPublishJob"] = False
        self.data["priority"] = 50
        self.data["whitelist"] = False
        self.data["machineList"] = ""
        self.data["vraySceneMultipleFiles"] = False
        self.options = {"useSelection": False}  # Force no content

    def _load_credentials(self):
        """Load Muster credentials.

        Load Muster credentials from file and set ``MUSTER_USER``,
        ``MUSTER_PASSWORD``, ``MUSTER_REST_URL`` is loaded from presets.

        Raises:
            CreatorError: If loaded credentials are invalid.
            AttributeError: If ``MUSTER_REST_URL`` is not set.

        """
        app_dir = os.path.normpath(appdirs.user_data_dir("pype-app", "pype"))
        file_name = "muster_cred.json"
        fpath = os.path.join(app_dir, file_name)
        file = open(fpath, "r")
        muster_json = json.load(file)
        self._token = muster_json.get("token", None)
        if not self._token:
            self._show_login()
            raise CreatorError("Invalid access token for Muster")
        file.close()
        self.MUSTER_REST_URL = os.environ.get("MUSTER_REST_URL")
        if not self.MUSTER_REST_URL:
            raise AttributeError("Muster REST API url not set")

    def _get_muster_pools(self):
        """Get render pools from Muster.

        Raises:
            CreatorError: If pool list cannot be obtained from Muster.

        """
        params = {"authToken": self._token}
        api_entry = "/api/pools/list"
        response = requests_get(self.MUSTER_REST_URL + api_entry,
                                params=params)
        if response.status_code != 200:
            if response.status_code == 401:
                self.log.warning("Authentication token expired.")
                self._show_login()
            else:
                self.log.error(
                    ("Cannot get pools from "
                     "Muster: {}").format(response.status_code)
                )
                raise CreatorError("Cannot get pools from Muster")
        try:
            pools = response.json()["ResponseData"]["pools"]
        except ValueError as e:
            self.log.error("Invalid response from Muster server {}".format(e))
            raise CreatorError("Invalid response from Muster server")

        return pools

    def _show_login(self):
        # authentication token expired so we need to login to Muster
        # again to get it. We use Pype API call to show login window.
        api_url = "{}/muster/show_login".format(
            os.environ["OPENPYPE_WEBSERVER_URL"])
        self.log.debug(api_url)
        login_response = requests_get(api_url, timeout=1)
        if login_response.status_code != 200:
            self.log.error("Cannot show login form to Muster")
            raise CreatorError("Cannot show login form to Muster")


#!/usr/bin/python3
""" Lockboxes """

def canUnlockAll(boxes):
    """ LockBoxes Function """
    T = []
    for i in range(1, len(boxes)):
        order = [T.extend(x) for x in boxes[:i] + boxes[i + 1:]]
        if i in T:
            T = []
        else:
            return False
    return True


import numpy as np
import time
from sklearn import preprocessing
import os.path
import re
import pandas as pd
import random
from dtw import dtw
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt

from autoencoder import AutoEncoder
from lstm_ad import LSTMAD
from lstm_enc_dec_axl import LSTMED
from rnn_ebm import RecurrentEBM

rootdir = "E://760//Project//PhaseI//"

filenamelist = list()

for parent, dirnames, filenames in os.walk(rootdir):
    for filename in filenames:
        if ".txt" in filename:
            filenamelist.append(filename)

result_list = []
anomaly_list = []
data_list = []
split_point_list = []
for index, value in enumerate(filenamelist):
    df = pd.read_csv(rootdir + value, names=['values'])
    data = df.values
    # preprocessing
    min_max_scaler = preprocessing.MinMaxScaler()
    data = min_max_scaler.fit_transform(data)

    split_point = int(re.findall("\d+", value)[1])
    data = data[0:split_point, ]

    # Get the split point of training and test set
    split_point = int(np.floor(0.7 * split_point))
    split_point_list.append(split_point)

    data_list.append(data)

'''
# Get the clusters of 25 datasets
# Use dtw method
distance_matrix = np.zeros((len(data_list),len(data_list)), dtype=float)
a = 0
for i in range(len(data_list)-1):
    for j in range(i+1, len(data_list)):
        if len(data_list[i]) > 20000:
            x = data_list[i][0:20000]
        else:
            x = data_list[i]
        if len(data_list[j]) > 20000:
            y = data_list[j][0:20000]
        else:
            y = data_list[j]

        manhattan_distance = lambda x, y: np.abs(x - y)
        d = dtw(x, y, manhattan_distance)[0]
        distance_matrix[i,j] = d
        distance_matrix[j,i] = d
    a += 1
    print(a)

min_max_scaler = preprocessing.MinMaxScaler()
distance_matrix = min_max_scaler.fit_transform(distance_matrix)

# Use DBSCAN to cluster the distance metric
y_pred = DBSCAN(eps=0.3, min_samples=3, metric='precomputed').fit(distance_matrix)
print()
'''

# List the result labels of clusters
labels = [0,0,0,4,1,1,1,1,1,1,0,0,2,2,0,0,0,2,3,3,3,3,3,4,4]

accuracy_list = []
for kk in range(5):
    result_list = [0] * 25
    for i in range(len(set(labels))):
        index = [k for k, x in enumerate(labels) if x == i]
        data = data_list[index[0]]

        # Add anomaly
        mu = 0
        sigma = 0.8
        anomaly_point = random.randint(split_point_list[index[0]], data.shape[0])
        anomaly_list.append(anomaly_point)
        temp = random.gauss(mu, sigma)
        if 0 <= temp < 0.3 or -0.3 < temp <= 0:
            temp = random.gauss(mu, sigma)
        data[anomaly_point] += temp

        '''
        # Add noise
        # 0.5% noise
        mu = 0
        sigma = 0.3
        noise_amount = int(np.ceil(0.005 * data.shape[0]))
        if noise_amount < 5:
            noise_amount = 5

        for i in range(noise_amount):
            noise_point = random.randint(0, data.shape[0])
            data[noise_point] += random.gauss(mu, sigma)
        '''

        # 2% noise
        mu = 0
        sigma = 0.3
        noise_amount = np.ceil(0.02 * data.shape[0])
        if noise_amount < 20:
            noise_amount = 20

        for ll in range(int(noise_amount)):
            noise_point = random.randint(0, data.shape[0]-2)
            data[noise_point] += random.gauss(mu, sigma)

        # Resplit data
        train = data[0:split_point_list[index[0]], ]
        train = pd.DataFrame(train)
        test = data[split_point_list[index[0]]:data.shape[0], ]
        test = pd.DataFrame(test)

        # Train the DNN models by the basic data
        model = AutoEncoder(num_epochs=40, hidden_size=10)
        model.fit(train)

        error = model.predict(test)
        error = np.abs(error)

        result = np.argmax(error) + split_point_list[index[0]]
        result_list[index[0]] = result

        # Fit the other data in the same clusters
        for j in range(1, len(index)):
            data = data_list[index[j]]

            # Add anomaly
            mu = 0
            sigma = 0.8
            anomaly_point = random.randint(split_point_list[index[j]], data.shape[0] - 1)
            anomaly_list.append(anomaly_point)
            temp = random.gauss(mu, sigma)
            if 0 <= temp < 0.3 or -0.3 < temp <= 0:
                temp = random.gauss(mu, sigma)
            data[anomaly_point] += temp

            '''
            # Add noise
            # 0.5% noise
            mu = 0
            sigma = 0.3
            noise_amount = int(np.ceil(0.005 * data.shape[0]))
            if noise_amount < 5:
                noise_amount = 5

            for i in range(noise_amount):
                noise_point = random.randint(0, data.shape[0])
                data[noise_point] += random.gauss(mu, sigma)
            '''

            '''
            # 2% noise
            mu = 0
            sigma = 0.4
            noise_amount = np.ceil(0.02 * data.shape[0])
            if noise_amount < 20:
                noise_amount = 20

            for i in range(len(noise_amount)):
                noise_point = random.randint(0, data.shape[0])
                data[noise_point] += random.gauss(mu, sigma)
            '''

            # Resplit data
            train = data[0:split_point_list[index[j]], ]
            train = pd.DataFrame(train)
            test = data[split_point_list[index[j]]:data.shape[0], ]
            test = pd.DataFrame(test)

            # Fit the other data in the same
            error = model.predict(test)
            error = np.abs(error)

            result = np.argmax(error) + split_point_list[index[j]]
            result_list[index[j]] = result

    right = 0
    for i in range(len(result_list)):
        if i != 24:
            if result_list[i] in range(anomaly_list[i] - 101, anomaly_list[i] + 101):
                right += 1
        else:
            if result_list[i] in range(anomaly_list[i] - 11, anomaly_list[i] + 11):
                right += 1

    print("The accuracy is: ", right / 25)
    accuracy_list.append(right / 25)

print("The mean accuracy of 20 times is: ", np.mean(accuracy_list))
print("The accuracy variance of 20 times is: ", np.var(accuracy_list))


import base64
import logging
import os
import subprocess
import sys
import tempfile
import unittest

from PIL import Image
from PIL import ImageChops

import z3c.rml.tests
from z3c.rml import rml2pdf

LOG_FILE = os.path.join(os.path.dirname(__file__), 'render.log')

def gs_command(path):
    return ('gs', '-q', '-sNOPAUSE', '-sDEVICE=png256',
            '-sOutputFile=%s[Page-%%d].png' % path[:-4],
            path, '-c', 'quit')

class RMLRenderingTestCase(unittest.TestCase):

    def __init__(self, inPath, outPath):
        self._inPath = inPath
        self._outPath = outPath
        unittest.TestCase.__init__(self)

    def setUp(self):
        import z3c.rml.tests.module
        sys.modules['module'] = z3c.rml.tests.module
        sys.modules['mymodule'] = z3c.rml.tests.module

    def tearDown(self):
        del sys.modules['module']
        del sys.modules['mymodule']

        from z3c.rml.document import LOGGER_NAME
        for handler in logging.getLogger(LOGGER_NAME).handlers:
            if handler.baseFilename == LOG_FILE:
                handler.close()

        if os.path.exists(LOG_FILE):
            os.remove(LOG_FILE)

    def runTest(self):
        rml2pdf.go(self._inPath, self._outPath)

class ComparePDFTestCase(unittest.TestCase):

    level = 2

    def __init__(self, basePath, testPath):
        self._basePath = basePath
        self._testPath = testPath
        unittest.TestCase.__init__(self)

    def assertSameImage(self, baseImage, testImage):
        base_file = open(baseImage, 'rb')
        test_file = open(testImage, 'rb')
        base_image = Image.open(base_file)
        base = base_image.getdata()
        test_image = Image.open(test_file)
        test = test_image.getdata()

        has_diff = True
        for i in range(len(base)):
            # Stop at first difference
            if (base[i] - test[i]) != 0:
                break
        else:
            has_diff = False

        if has_diff and 'SHOW_IMAGE_DIFF' in os.environ:
            test_image.show()
            base_image.show()
            differ = ImageChops.subtract(test_image, base_image)
            differ.show()
            differ2 = ImageChops.subtract(base_image, test_image)
            differ2.show()
            # output the result as base64 for travis debugging
            if 'SHOW_DIFF_DEBUG' in os.environ:
                print(base64.b64encode(differ.tobytes()))
                print(base64.b64encode(differ2.tobytes()))

        if has_diff and 'SHOW_DIFF_DEBUG' in os.environ:
            print()
            print(os.system("gs --version"))

            base_file.seek(0)
            print(baseImage)
            print(base64.b64encode(base_file.read()))
            print(self._basePath)
            with open(self._basePath, 'rb') as base_pdf:
                print(base64.b64encode(base_pdf.read()))

            test_file.seek(0)
            print(testImage)
            print(base64.b64encode(test_file.read()))
            print(self._testPath)
            with open(self._testPath, 'rb') as test_pdf:
                print(base64.b64encode(test_pdf.read()))

        base_file.close()
        test_file.close()

        if has_diff:
            self.fail(
                'Image is not the same: %s' % os.path.basename(baseImage))

    def runTest(self):
        # Convert the base PDF to image(s)
        status = subprocess.Popen(gs_command(self._basePath)).wait()
        if status:
            return
        # Convert the test PDF to image(s)
        status = subprocess.Popen(gs_command(self._testPath)).wait()
        if status:
            return
        # Go through all pages and ensure their equality
        n = 1
        while True:
            baseImage = self._basePath[:-4] + '[Page-%i].png' % n
            testImage = self._testPath[:-4] + '[Page-%i].png' % n
            if os.path.exists(baseImage) and os.path.exists(testImage):
                self.assertSameImage(baseImage, testImage)
            else:
                break
            n += 1

class CompareFileTestCase(unittest.TestCase):

    def __init__(self, testPath, contains):
        self._testPath = testPath
        self._contains = contains
        unittest.TestCase.__init__(self)

    def runTest(self):
        with open(self._testPath, 'rb') as io:
            contents = io.read()

            if self._contains not in contents:
                self.fail(
                    'PDF file does not contain: %s' % self._contains
                )

def test_suite():
    if False:
        # Debug info
        import pkg_resources
        print("Environment\n===========")
        print("reportlab:")
        print(pkg_resources.get_distribution('reportlab').version)
        print("ghostscript:")
        os.system("gs --version")

    suite = unittest.TestSuite()
    here = os.path.dirname(z3c.rml.tests.__file__)
    inputDir = os.path.join(here, 'input')
    outputDir = tempfile.mkdtemp('z3c.rml-output')
    print(f'output dir: {outputDir}')
    expectDir = os.path.join(here, 'expected')
    for filename in os.listdir(inputDir):
        if not filename.endswith(".rml"):
            continue

        inPath = os.path.join(inputDir, filename)
        outPath = os.path.join(outputDir, filename[:-4] + '.pdf')
        expectPath = os.path.join(expectDir, filename[:-4] + '.pdf')

        # ** Test RML to PDF rendering **
        # Create new type, so that we can get test matching
        TestCase = type(filename[:-4], (RMLRenderingTestCase,), {})
        case = TestCase(inPath, outPath)
        suite.addTest(case)
        # ** Test PDF rendering correctness **
        TestCase = type('compare-' + filename[:-4], (ComparePDFTestCase,), {})
        case = TestCase(expectPath, outPath)
        suite.addTest(case)

        if filename == 'printScaling.rml':
            TestCase = type('compare-file-' + filename[:-4],
                            (CompareFileTestCase,), {})
            case = TestCase(outPath, b'/PrintScaling /None')
            suite.addTest(case)

    return suite


'''
Airmass related funcitons.

Don't you think these must be implemented to astropy...?
'''
from warnings import warn

import numpy as np
from astropy.io import fits
from astropy import units as u
from astropy.coordinates import AltAz, EarthLocation, SkyCoord
from astropy.io.fits import Card
from astropy.time import Time

from .hduutil import get_if_none, cmt2hdr
from .misc import change_to_quantity

__all__ = ["calc_airmass", "airmass_obs", "airmass_to_hdr", "airmass_from_hdr"]

def calc_airmass(zd_deg=None, cos_zd=None, scale=750.):
    ''' Calculate airmass by nonrefracting radially symmetric atmosphere model.

    Parameters
    ----------
    zd_deg : float, optional
        The zenithal distance in degrees

    cos_zd : float, optional
        The cosine of zenithal distance. If given, ``zd_deg`` is not used.

    scale : float, optional
        Earth radius divided by the atmospheric height (usually scale height)
        of the atmosphere. In IRAF documentation, it is mistakenly written that
        this ``scale`` is the "scale height".

    Notes
    -----
    Wiki:

        https://en.wikipedia.org/wiki/Air_mass_(astronomy)#Nonrefracting_radially_symmetrical_atmosphere

    Identical to the airmass calculation for a given observational run of
    IRAF's asutil.setairmass:

        http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?setairmass

    '''
    if not ((zd_deg is None) ^ (cos_zd is None)):
        raise ValueError("One and only one of `zd_deg` or `cos_zd` should be given.")

    # NOTE: for this part, using numexpr is slower than using numpy. It is
    # because this airmass calculation is usually done for a single zd value
    # from a single exposure. If one needs a large amount of such calculations,
    # numexpr may boost the speed, but that will be like few ms to us order.
    # Using numexpr will introduce a large overhead for the calculation if this
    # is repeated for thousands of images:
    # numexpr version:
    # %timeit yfu.calc_airmass(10)
    # 21.3 µs +/- 2.44 µs per loop (mean +/- std. dev. of 7 runs, 10000 loops each)
    # numpy version:
    # %timeit yfu.calc_airmass(10)
    # 3.65 µs +/- 93.5 ns per loop (mean +/- std. dev. of 7 runs, 100000 loops each)

    if cos_zd is None:
        cos_zd = np.cos(np.deg2rad(zd_deg))

    am = np.sqrt((scale*cos_zd)**2 + 2*scale + 1) - scale*cos_zd

    return am

def airmass_obs(targetcoord, obscoord, ut, exptime, scale=750., full=False, in_deg=True):
    ''' Calculate airmass by nonrefracting radially symmetric atmosphere model.

    Parameters
    ----------
    targetcoord: astropy.SkyCoord
        The target's coorndinate.

    obscoord : astropy.EarthLocation
        The observer's location.

    ut : astropy.Time
        The time when the exposure is started.

    exptime : astropy.Quantity
        The exposure time.

    scale : float, optional
        Earth radius divided by the atmospheric height (usually scale height)
        of the atmosphere. In IRAF documentation, it is mistakenly written that
        this `scale` is the "scale height".

    in_deg : bool, optional
        If True, return alt/az in degrees. Otherwise, return in string with separation ":".

    Notes
    -----
    Wiki:

        https://en.wikipedia.org/wiki/Air_mass_(astronomy)#Nonrefracting_radially_symmetrical_atmosphere

    Identical to the airmass calculation for a given observational run of
    IRAF's asutil.setairmass:

        http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?setairmass

    Partly contributed by Geonwoo Kang (Seoul National University) in Apr 2018.
    '''
    if not isinstance(ut, Time):
        warn("ut is not Time object. Assume format='isot', scale='utc'.")
        ut = Time(ut, format='isot', scale='utc')
    if not isinstance(exptime, u.Quantity):
        warn("exptime is not astropy Quantity. Assume it is in seconds.")
        exptime = exptime * u.s

    t_start = ut
    t_mid = ut + exptime / 2
    t_final = ut + exptime

    alldict = {"alt": [], "az": [], "zd": [], "am": []}
    for t in [t_start, t_mid, t_final]:
        C_altaz = AltAz(obstime=t, location=obscoord)
        target = targetcoord.transform_to(C_altaz)
        if in_deg:
            alt = target.alt.to_value(unit=u.deg)
            az = target.az.to_value(unit=u.deg)
        else:
            alt = target.alt.to_string(unit=u.deg, sep=':')
            az = target.az.to_string(unit=u.deg, sep=':')
        zd = target.zen.to(u.deg).value
        am = calc_airmass(zd_deg=zd, scale=scale)
        alldict["alt"].append(alt)
        alldict["az"].append(az)
        alldict["zd"].append(zd)
        alldict["am"].append(am)

    am_eff = (alldict["am"][0] + 4*alldict["am"][1] + alldict["am"][2]) / 6

    if full:
        return am_eff, alldict

    return am_eff

def airmass_to_hdr(
    header: fits.Header,
    obscoord: EarthLocation,
    targetcoord: SkyCoord = None,
    ra: str | float | u.Quantity = "RA",
    dec: str | float | u.Quantity = "DEC",
    time_start: str | Time = "DATE-OBS",
    time_scale: str = "utc",
    exptime: str | float | u.Quantity = "EXPTIME",
    scale=750.,
    in_deg=True,
    frame: str = "icrs",
):
    """
    Calculates airmass from a given header and location information

    Parameters
    ----------
    header : fits.Header
        The header of the image to calculate airmass from.

    obscoord : EarthLocation
        The location of the observatory.

    targetcoord : SkyCoord, optional
        The coordinate of the target. If not given, it will be calculated from
        the header.

    ra, dec : str|float|u.Quantity, optional
        The name of the header keyword or the value of the RA and DEC of the
        target. If float, it should be in [deg].

    time_start : str|Time, optional
        The name of the header keyword or the value of the time when the
        exposure started.

    time_scale : str, optional
        The scale of the time if it is read from header. Default is "utc".

    exptime : str|float|u.Quantity, optional
        The name of the header keyword or the value of the exposure time. If
        given as float, it should be in [sec].

    scale : float, optional
        Earth radius divided by the atmospheric height (usually scale height)
        of the atmosphere. In IRAF documentation, it is mistakenly written that
        this `scale` is the "scale height".
    in_deg : bool, optional
        If True, return alt/az in degrees. Otherwise, return in string with separation ":".

    """
    _t = Time.now()
    if obscoord is None:
        ra = change_to_quantity(header.get(ra) if isinstance(ra, str) else ra, u.deg)
        de = change_to_quantity(header.get(dec) if isinstance(dec, str) else dec, u.deg)
        obscoord = SkyCoord(ra, de, frame=frame)

    t0 = Time(
        header[time_start] if isinstance(time_start, str) else time_start,
        scale=time_scale
    )
    expt = change_to_quantity(header[exptime] if isinstance(exptime, str) else exptime, u.s)
    # if isinstance(time_start, str)

    am_eff, alldict = airmass_obs(
        targetcoord, obscoord, ut=t0, exptime=expt, scale=scale, full=True, in_deg=in_deg
    )

    header.set("AIRMASS", am_eff, "Effective airmass (Stetson 1988; see COMMENT)")
    header.set("AM_STR", alldict["am"][0], "[deg] Airmass (start of exposure)")
    header.set("ZD_STR", alldict["zd"][0], "[deg] Zenithal distance (start of exposure)")
    header.set("ALT_STR", alldict["alt"][0], "[deg] Altitude (start of exposure)")
    header.set("AZ_STR", alldict["az"][0], "[deg] Azimuth (start of exposure)")
    header.set("AM_MID", alldict["am"][1], "[deg] Airmass (midpoint of exposure)")
    header.set("ZD_MID", alldict["zd"][1], "[deg] Zenithal distance (midpoint of exposure)")
    header.set("ALT_MID", alldict["alt"][1], "[deg] Altitude (midpoint of exposure)")
    header.set("AZ_MID", alldict["az"][1], "[deg] Azimuth (midpoint of exposure)")
    header.set("AM_END", alldict["am"][2], "[deg] Airmass (end of exposure)")
    header.set("ZD_END", alldict["zd"][2], "[deg] Zenithal distance (end of exposure)")
    header.set("ALT_END", alldict["alt"][2], "[deg] Altitude (end of exposure)")
    header.set("AZ_END", alldict["az"][2], "[deg] Azimuth (end of exposure)")
    cmt2hdr(
        header, "c", t_ref=_t,
        s=("[yfu.airmass] AIRMASS, AM_XXX, ZD_XXX, ALT_XXX, AZ_XXX are calculated. "
           + "`ysfitsutilpy` uses airmass calculation algorithm identical to IRAF: See "
           + "'Some Factors Affecting the Accuracy of Stellar Photometry with CCDs', "
           + "by P. Stetson, DAO preprint, September 1988. "
           ))

# TODO: change key, unit, etc as input dict.
def airmass_from_hdr(
        header,
        ra=None,
        dec=None,
        ut=None,
        exptime=None,
        lon=None,
        lat=None,
        height=None,
        equinox=None,
        frame=None,
        scale=750.,
        ra_key="RA",
        dec_key="DEC",
        ut_key="DATE-OBS",
        lon_key="LONGITUD",
        lat_key="LATITUDE",
        height_key="HEIGHT",
        exptime_key="EXPTIME",
        equinox_key="EPOCH",
        frame_key="RADECSYS",
        ra_unit=u.hourangle,
        dec_unit=u.deg, exptime_unit=u.s,
        lon_unit=u.deg,
        lat_unit=u.deg,
        height_unit=u.m,
        ut_format='isot',
        ut_scale='utc',
        return_header=False,
        verbose=False
):
    ''' Calculate airmass using the header.
    Parameters
    ----------
    ra, dec: float or Quantity, optional
        The RA and DEC of the target. If not specified, it tries to find them
        in the header using ``ra_key`` and ``dec_key``.

    ut: str or Time, optional
        The *starting* time of the observation in UT.

    exptime: float or Time, optional
        The exposure time.

    lon, lat, height: str, float, or Quantity
        The longitude, latitude, and height of the observatory. See
        astropy.coordinates.EarthLocation.

    equinox, frame: str, optional
        The `equinox` and `frame` for SkyCoord.

    scale: float, optional
        Earth radius divided by the atmospheric height (usually scale height)
        of the atmosphere.

    XX_key: str, optional
        The header key to find XX if ``XX`` is `None`.

    XX_unit: Quantity, optional
        The unit of ``XX``

    ut_format, ut_scale: str, optional
        The `format` and `scale` for Time.

    return_header: bool, optional
        Whether to return the updated header.
    '''
    # If there is no header keyword matches the ``key``, it should give
    # KeyError. For such reason, I didn't use ``get_from_header`` here.
    def _conversion(header, val, key, unit=None):
        if val is None:
            val = header[key]  # assume it is in the unit of ``unit``.
        elif unit is not None:
            if isinstance(val, u.Quantity):
                val = val.to(unit).value
            # else: just return ``val``.
        return val

    def _cards_airmass(am_eff, alldict):
        ''' Gives airmass and alt-az related header cards.
        '''
        amstr = (
            "ysfitsutilpy's airmass calculation uses the same algorithm as IRAF: From "
            + "'Some Factors Affecting the Accuracy of Stellar Photometry with CCDs' by "
            + "P. Stetson, DAO preprint, September 1988.")

        # At some times, hdr["AIRMASS"] = am, for example, did not work for
        # some reasons which I don't know.... So I used Card. -
        # YPBach 2018-05-04
        cs = [
            Card("AIRMASS", am_eff,
                 "Effective airmass (Stetson 1988; see COMMENT)"),
            Card("ZD", alldict["zd"][0],
                 "[deg] Zenithal distance (start of the exposure)"),
            Card("ALT", alldict["alt"][0],
                 "Altitude (start of the exposure)"),
            Card("AZ", alldict["az"][0],
                 "Azimuth (start of the exposure)"),
            Card("ALT_MID", alldict["alt"][1],
                 "Altitude (midpoint of the exposure)"),
            Card("AZ_MID", alldict["az"][1],
                 "Azimuth (midpoint of the exposure)"),
            Card("ZD_MID", alldict["zd"][1],
                 "[deg] Zenithal distance (midpoint of the exposure)"),
            Card("ALT_END", alldict["alt"][2],
                 "Altitude (end of the exposure)"),
            Card("AZ_END", alldict["az"][2],
                 "Azimuth (end of the exposure)"),
            Card("ZD_END", alldict["zd"][2],
                 "[deg] Zenithal distance (end of the exposure)"),
            Card("COMMENT", amstr),
            Card("HISTORY", "ALT-AZ calculated from ysfitsutilpy."),
            Card("HISTORY", "AIRMASS calculated from ysfitsutilpy.")
        ]
        return cs

    ra = get_if_none(ra, header, ra_key, unit=ra_unit, verbose=verbose)[0]
    dec = get_if_none(dec, header, dec_key, unit=dec_unit, verbose=verbose)[0]
    exptime = get_if_none(exptime, header, exptime_key, unit=exptime_unit,
                          verbose=verbose)[0]
    lon = get_if_none(lon, header, lon_key, lon_unit)[0]
    lat = get_if_none(lat, header, lat_key, lat_unit)[0]
    height = get_if_none(height, header, height_key, height_unit)[0]
    equinox = get_if_none(equinox, header, equinox_key)[0]
    frame = get_if_none(frame, header, frame_key)[0]

    ra = _conversion(header, ra, ra_key, ra_unit)
    dec = _conversion(header, dec, dec_key, dec_unit)
    exptime = _conversion(header, exptime, exptime_key, exptime_unit)
    lon = _conversion(header, lon, lon_key, lon_unit)
    lat = _conversion(header, lat, lat_key, lat_unit)
    height = _conversion(header, height, height_key, height_unit)
    equinox = _conversion(header, equinox, equinox_key)
    frame = _conversion(header, frame, frame_key)

    if ut is None:
        ut = header[ut_key]
    elif isinstance(ut, Time):
        ut = ut.isot
        # ut_format = 'isot'
        # ut_scale = 'utc'

    targetcoord = SkyCoord(
        ra=ra, dec=dec, unit=(ra_unit, dec_unit), frame=frame, equinox=equinox
    )

    try:  # It should work here but just in case I put except...
        observcoord = EarthLocation(lon=lon*lon_unit, lat=lat*lat_unit, height=height*height_unit)
    except ValueError:
        observcoord = EarthLocation(lon=lon, lat=lat, height=height)

    am_eff, alldict = airmass_obs(
        targetcoord=targetcoord,
        obscoord=observcoord,
        ut=ut,
        exptime=exptime*exptime_unit,
        scale=scale,
        full=True
    )

    if return_header:
        nhdr = header.copy()
        cards = _cards_airmass(am_eff, alldict)
        # Remove if there is, e.g., AIRMASS a priori to the original header:
        for c in cards:
            try:
                nhdr.remove(c.keyword)
            except KeyError:
                continue
        nhdr = nhdr + cards
        return nhdr

    else:
        return am_eff, alldict


from enum import Enum

from typing_extensions import Final

class GCODE(str, Enum):
    HOME = "G28.2"
    MOVE = "G0"
    DWELL = "G4"
    CURRENT_POSITION = "M114.2"
    LIMIT_SWITCH_STATUS = "M119"
    PROBE = "G38.2"
    ABSOLUTE_COORDS = "G90"
    RELATIVE_COORDS = "G91"
    RESET_FROM_ERROR = "M999"
    PUSH_SPEED = "M120"
    POP_SPEED = "M121"
    SET_SPEED = "G0"
    STEPS_PER_MM = "M92"
    READ_INSTRUMENT_ID = "M369"
    WRITE_INSTRUMENT_ID = "M370"
    READ_INSTRUMENT_MODEL = "M371"
    WRITE_INSTRUMENT_MODEL = "M372"
    SET_MAX_SPEED = "M203.1"
    SET_CURRENT = "M907"
    DISENGAGE_MOTOR = "M18"
    HOMING_STATUS = "G28.6"
    ACCELERATION = "M204"
    WAIT = "M400"
    PIPETTE_RETRACT = "M365.3"
    PIPETTE_DEBOUNCE = "M365.2"
    PIPETTE_MAX_TRAVEL = "M365.1"
    PIPETTE_HOME = "M365.0"
    MICROSTEPPING_B_ENABLE = "M52"
    MICROSTEPPING_B_DISABLE = "M53"
    MICROSTEPPING_C_ENABLE = "M54"
    MICROSTEPPING_C_DISABLE = "M55"
    VERSION = "version"

HOMED_POSITION: Final = {
    "X": 418.0,
    "Y": 353.0,
    "Z": 218.0,
    "A": 218.0,
    "B": 19.0,
    "C": 19.0,
}

Y_BOUND_OVERRIDE: Final = 370

SMOOTHIE_COMMAND_TERMINATOR = "\r\n\r\n"

SMOOTHIE_ACK = "ok\r\nok\r\n"

PLUNGER_BACKLASH_MM = 0.3

LOW_CURRENT_Z_SPEED = 30

CURRENT_CHANGE_DELAY = 0.005

PIPETTE_READ_DELAY = 0.1

Y_SWITCH_BACK_OFF_MM = 28

Y_SWITCH_REVERSE_BACK_OFF_MM = 10

Y_BACKOFF_LOW_CURRENT = 0.8

Y_BACKOFF_SLOW_SPEED = 50

Y_RETRACT_SPEED = 8

Y_RETRACT_DISTANCE = 3

UNSTICK_DISTANCE = 1

UNSTICK_SPEED = 1

DEFAULT_AXES_SPEED = 400

XY_HOMING_SPEED = 80

HOME_SEQUENCE = ["ZABC", "X", "Y"]

AXES = "".join(HOME_SEQUENCE)

DISABLE_AXES = ""
"""Ignore these axis when sending move or home command"""

MOVEMENT_ERROR_MARGIN = 1 / 160  # Largest movement in mm for any step

SEC_PER_MIN = 60

DEFAULT_ACK_TIMEOUT = 5

DEFAULT_EXECUTE_TIMEOUT = 12000

DEFAULT_SMOOTHIE_TIMEOUT = 1

DEFAULT_MOVEMENT_TIMEOUT = 30

SMOOTHIE_BOOT_TIMEOUT = 3

DEFAULT_STABILIZE_DELAY = 0.1

DEFAULT_COMMAND_RETRIES = 3

MICROSTEPPING_GCODES = {
    "B": {
        "ENABLE": GCODE.MICROSTEPPING_B_ENABLE,
        "DISABLE": GCODE.MICROSTEPPING_B_DISABLE,
    },
    "C": {
        "ENABLE": GCODE.MICROSTEPPING_C_ENABLE,
        "DISABLE": GCODE.MICROSTEPPING_C_DISABLE,
    },
}

GCODE_ROUNDING_PRECISION = 3
"""Number of digits after the decimal point for coordinates being sent to Smoothie"""


from pydantic import BaseModel, Field
from kubernetes.client.rest import ApiException

class InputSchema(BaseModel):
    k8s_cli_string: str = Field(
        title='Kubectl Command',
        description='kubectl execute a command in pod',
        default='kubectl exec {pod_name} {command} -n {namespace}'
    )
    pod_name: str = Field(
        title='Pod Name',
        description='Pod Name'
    )
    command: str = Field(
        title='Command',
        description='Command'
    )
    namespace: str = Field(
        title='Namespace',
        description='Namespace'
    )

def k8s_kubectl_exec_command_printer(data: str):
    if data is None:
        print("Error while executing command")
        return

    print (data)

def k8s_kubectl_exec_command(
        handle,
        k8s_cli_string: str,
        pod_name:str,
        command: str,
        namespace: str
        ) -> str:
    """k8s_kubectl_exec_command executes the given kubectl command on the pod

        :type handle: object
        :param handle: Object returned from the Task validate method

        :type k8s_cli_string: str
        :param k8s_cli_string: kubectl exec {pod_name} {command} -n {namespace}.

        :type pod_name: str
        :param pod_name: Pod Name.

        :type command: str
        :param command: Command.

        :type namespace: str
        :param namespace: Namespace.

        :rtype: String, Output of the command in python string format or
        Empty String in case of Error.
    """
    k8s_cli_string = k8s_cli_string.format(pod_name=pod_name, command=command, namespace=namespace)
    result = handle.run_native_cmd(k8s_cli_string)

    if result is None:
        print(
            f"Error while executing command ({k8s_cli_string}) (empty response)")
        return ""

    if result.stderr:
        raise ApiException(f"Error occurred while executing command {k8s_cli_string} {result.stderr}")

    return result.stdout


class Solution:
    def minOperations(self, nums: List[int]) -> int:
        length=len(nums)
        nums=sorted(set(nums))
        res=length
        r=0
        for l in range(len(nums)):
            while r<len(nums) and nums[r]<length+nums[l]:
                r+=1
            window=r-l
            res=min(res,length-window)
        return res
''' Time Complexity--O(n^2)
    Space Complexity--O(1)'''

2009. Minimum Number of Operations to Make Array Continuous.py


from authtools.views import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.views.generic import ListView, CreateView

from . import models

class HomeView(LoginRequiredMixin, ListView):
    model = models.Expense

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)

    def total(self):
        qs = self.get_queryset()
        return sum(x.amount for x in qs)

class AddView(LoginRequiredMixin, CreateView):
    model = models.Expense
    fields = (
        'timestamp',
        'amount',
        'details',
    )
    success_url = reverse_lazy("home")

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)


class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        # get index of val in nums
        val_ind = [i for i, v in enumerate(nums) if v == val]
        # track num of val occurrence
        ct = 0
        # loop through nums and modify in place
        for i in val_ind:
            nums.pop(i - ct)
            nums.append('_')
            ct += 1
        return len(nums) - ct

Algorithms - Python/Arrays/27. Remove Element.py


#!/usr/bin/env python3
import cgi
import cgitb
import sys
import sqlite3
cgitb.enable()

def get_24hour(hour, period):
    """
    Converts 12-hour time string to 24-hour
    :param hour: string
    :param period: either 'AM' or 'PM' string
    :return: 24-hour string
    """
    if period == "PM":
        if hour != "12":
            return str(int(hour) + 12)
    elif hour == "12":
            return '0'
    return hour

def check_duration(duration):
    """
    Sanitizes input from text box
    :param duration: Text box input
    :return: Sanitized duration or error message
    """
    if not duration:
        return "empty"
    if len(duration) > 3:
        return "bad length"
    try:
        int(duration)
    except ValueError:
        return "not int"
    if int(duration) < 0 or int(duration) > 300:
        return "out of range"
    return duration

# SQLITE database
DATABASE = '/tmp/waterings.db'

# Print header
print('Content-type: text/html\r\n\r\n')
sys.stdout.flush()

# Bool indicating if command was successful
success = False
# Connect to database and run SQL command
conn = sqlite3.connect(DATABASE)
form = cgi.FieldStorage()
day = form.getvalue('day')
if isinstance(day, list) and len(day) > 0:
    for d in day:
        hour = get_24hour(form.getvalue('hour'), form.getvalue('period'))
        minute = form.getvalue('minute')
        duration = check_duration(form.getvalue('duration'))
        if duration == "empty":
            print('
ERROR: Duration must be set
')
            print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
            quit()
        if duration == "bad length" or duration == "out of range":
            print('
ERROR: Duration can only be in range of 1 to 300 minutes
')
            print('
<form action="/watering_schedule.html"><input type="Submit" value="Return"/></form>')
            quit()
        elif duration == "not int":
            print('
ERROR: Input is not an integer
')
            print('
<form action="/watering_schedule.html"><input type="Submit" value="Return"/></form>')
            quit()
        cur = conn.execute('INSERT INTO waterings (day, hour, minute, duration) VALUES (?, ?, ?, ?)',
                           (d, hour, minute, duration))
        if cur.rowcount == 1:
            success = True
elif not day:
    print('
ERROR: Must enter a day
')
    print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
    quit()
else:
    hour = get_24hour(form.getvalue('hour'), form.getvalue('period'))
    minute = form.getvalue('minute')
    duration = check_duration(form.getvalue('duration'))
    if duration == "empty":
        print('
ERROR: Duration must be set
')
        print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
        quit()
    elif duration == "bad length" or duration == "out of range":
        print('
ERROR: Duration can only be in range of 1 to 300 minutes
')
        print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
        quit()
    elif duration == "not int":
        print('
ERROR: Input is not an integer
')
        print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
        quit()
    cur = conn.execute('INSERT INTO waterings (day, hour, minute, duration) VALUES (?, ?, ?, ?)',
                       (day, hour, minute, duration))
    if cur.rowcount == 1:
        success = True
conn.commit()
conn.close()

if success:
    print('
Watering has been added to schedule
')
else:
    print('
ERROR: Not able to add watering to schedule
')

print('
<form action="/schedule_watering.html"><input type="Submit" value="Add another watering to schedule"/></form>')
print('
<form action="/cgi-bin/watering_schedule.py"><input type="Submit" value="Return to schedule"/></form>')


# -*-coding: utf8-*-
import operator
from grid import *

class SudokuSolver:
    """Cette classe permet d'explorer les solutions d'une grille de Sudoku pour la résoudre.
    Elle fait intervenir des notions de programmation par contraintes
    que vous n'avez pas à maîtriser pour ce projet."""

    def __init__(self, grid):
        """À COMPLÉTER
        Ce constructeur initialise une nouvelle instance de solver à partir d'une grille initiale.
        Il construit les ensembles de valeurs possibles pour chaque case vide de la grille,
        en respectant les contraintes définissant un Sudoku valide.
        Ces contraintes seront appliquées en appelant la méthode ``reduce_all_domains``.
        :param grid: Une grille de Sudoku
        :type grid: SudokuGrid
        """
        self.solutions = []
        self.grid = grid
        self.reduce_all_domains()

    def reduce_all_domains(self):
        """À COMPLÉTER
        Cette méthode devrait être appelée à l'initialisation
        et élimine toutes les valeurs impossibles pour chaque case vide.
        *Indication: Vous pouvez utiliser les fonction ``get_row``, ``get_col`` et ``get_region`` de la grille*
        """
        for element in self.grid.get_empty_positions():
            liste_valeurs_possibles = set()
            ligne_tuple = list(self.grid.get_row(element[0]))
            colonne_tuple = list(self.grid.get_col(element[1]))
            region_tuple = list(self.grid.get_region(element[0] // 3, element[1] // 3))

            for i in range(1, 10):
                if i not in ligne_tuple and i not in colonne_tuple and i not in region_tuple:
                    liste_valeurs_possibles.add(i)

            self.solutions.append((element, liste_valeurs_possibles))

    def reduce_domains(self, last_i, last_j, last_v):
        """À COMPLÉTER
        Cette méthode devrait être appelée à chaque mise à jour de la grille,
        et élimine la dernière valeur affectée à une case
        pour toutes les autres cases concernées par cette mise à jour (même ligne, même colonne ou même région).
        :param last_i: Numéro de ligne de la dernière case modifiée, entre 0 et 8
        :param last_j: Numéro de colonne de la dernière case modifiée, entre 0 et 8
        :param last_v: Valeur affecté à la dernière case modifiée, entre 1 et 9
        :type last_i: int
        :type last_j: int
        :type last_v: int
        """
        for element in self.solutions:
            region_element = (element[0][0] // 3, element[0][1] // 3)
            region_last = (last_i // 3, last_j // 3)
            if last_v in element[1] and (
                    element[0][0] == last_i or element[0][1] == last_j or (region_element == region_last)):
                element[1].remove(last_v)

    def commit_one_var(self):
        """À COMPLÉTER
        Cette méthode cherche une case pour laquelle il n'y a plus qu'une seule possibilité.
        Si elle en trouve une, elle écrit cette unique valeur possible dans la grille
        et renvoie la position de la case et la valeur inscrite.
        :return: Le numéro de ligne, de colonne et la valeur inscrite dans la case
        ou ``None`` si aucune case n'a pu être remplie.
        :rtype: tuple of int or None
        """
        infos = ()
        for element in self.solutions:
            if len(element[1]) == 1:
                self.grid.write(element[0][0], element[0][1], next(iter(element[1])))
                infos = (element[0][0], element[0][1], next(iter(element[1])))
                return infos

        return None

    def solve_step(self):
        """À COMPLÉTER
        Cette méthode alterne entre l'affectation de case pour lesquelles il n'y a plus qu'une possibilité
        et l'élimination des nouvelles valeurs impossibles pour les autres cases concernées.
        Elle répète cette alternance tant qu'il reste des cases à remplir,
        et correspond à la résolution de Sudokus dits «simple».
        *Variante avancée: en plus de vérifier s'il ne reste plus qu'une seule possibilité pour une case,
        il est aussi possible de vérifier s'il ne reste plus qu'une seule position valide pour une certaine valeur
        sur chaque ligne, chaque colonne et dans chaque région*
        """
        last_change = -1
        while last_change is not None:
            last_change = self.commit_one_var()
            if last_change is not None:
                self.reduce_domains(last_change[0], last_change[1], last_change[2])
                self.clean_solutions(last_change)
                last_change = ()
            else:
                pass

    def is_valid(self):
        """À COMPLÉTER
        Cette méthode vérifie qu'il reste des possibilités pour chaque case vide
        dans la solution partielle actuelle.
        :return: Un booléen indiquant si la solution partielle actuelle peut encore mener à une solution valide
        :rtype: bool
        """
        for element in self.solutions:
            if element[1] != set():
                return True
            else:
                return False

    def is_solved(self):
        """À COMPLÉTER
        Cette méthode vérifie si la solution actuelle est complète,
        c'est-à-dire qu'il ne reste plus aucune case vide.
        :return: Un booléen indiquant si la solution actuelle est complète.
        :rtype: bool
        """
        solution_complete = False
        if not list(self.grid.get_empty_positions()):
            solution_complete = True

        return solution_complete

    def branch(self):
        """À COMPLÉTER
        Cette méthode sélectionne une variable libre dans la solution partielle actuelle,
        et crée autant de sous-problèmes que d'affectation possible pour cette variable.
        Ces sous-problèmes seront sous la forme de nouvelles instances de solver
        initialisées avec une grille partiellement remplie.
        *Variante avancée: Renvoyez un générateur au lieu d'une liste.*
        *Variante avancée: Un choix judicieux de variable libre,
        ainsi que l'ordre dans lequel les affectations sont testées
        peut fortement améliorer les performances de votre solver.*
        :return: Une liste de sous-problèmes ayant chacun une valeur différente pour la variable choisie
        :rtype: list of SudokuSolver
        """
        list_solutions = []
        coordonnees_mini = ()
        set_mini = {}
        self.solutions.sort(key=lambda oui: len(oui[1]))
        coordonnees_mini = self.solutions[0][0]
        set_mini = self.solutions[0][1]
        for i in set_mini:
            grille_sudoku_en_cours = self.grid.copy()
            grille_sudoku_en_cours.write(coordonnees_mini[0], coordonnees_mini[1], i)
            sous_probleme = self.__class__(grille_sudoku_en_cours)
            list_solutions.append(sous_probleme)

        return list_solutions

    def solve(self):
        """
        Cette méthode implémente la fonction principale de la programmation par contrainte.
        Elle cherche d'abord à affiner au mieux la solution partielle actuelle par un appel à ``solve_step``.
        Si la solution est complète, elle la retourne.
        Si elle est invalide, elle renvoie ``None`` pour indiquer un cul-de-sac dans la recherche de solution
        et déclencher un retour vers la précédente solution valide.
        Sinon, elle crée plusieurs sous-problèmes pour explorer différentes possibilités
        en appelant récursivement ``solve`` sur ces sous-problèmes.
        :return: Une solution pour la grille de Sudoku donnée à l'initialisation du solver
        (ou None si pas de solution)
        :rtype: SudokuGrid or None
        """
        self.solve_step()
        if self.is_solved():
            return self.grid
        elif self.is_valid():
            oui = self.branch()
            for element in oui:
                s = element.solve()
                if s is not None:
                    return s
            return None
        else:
            return None

    def clean_solutions(self, last_change):
        self.solutions.remove(((last_change[0], last_change[1]), set()))


# Advent of code day 5, part 2. If You Give A Seed A Fertilizer.
# https://adventofcode.com/2023/day/5

from icecream import ic

def parse_seeds(a: str) -> list:
    simple_list = [int(seed) for seed in a.replace('seeds:', '').split()]

    # Each item in list is a tuple. (start, length)
    seeds= []

    start = None
    while len(simple_list) != 0:
        next = simple_list.pop(0)
        if start is None:
            start = next
        else:
            seeds.append((start, next))
            start = None

    return seeds

def parse_map(a: str) -> tuple:
    terms = a.split('-')
    return terms[0], terms[2].replace(' map:', '')

def parse_range(a: str) -> list:
    return [int(term) for term in a.split(' ')]

def correspond(source: int, mappings: list) -> int:
    for destination_range_start, source_range_start, range_length in mappings:
        # 50, 98, 2
        # 98 + 2 = 100
        if source >= source_range_start and source < source_range_start + range_length:
            return destination_range_start - source_range_start + source
    return source

def seed_exists(candidate_seed: int, seeds: list) -> bool:
    for start, length in seeds:
        if start <= candidate_seed < start + length:
            return True
    return False

def back_correspond(target: int, mappings: list) -> int:
    for destination_range_start, source_range_start, range_length in mappings:
        backwards = source_range_start + target - destination_range_start
        if backwards >= source_range_start and backwards < source_range_start + range_length:
            return backwards
    return target

with open('input.txt', 'r') as file:
    almanac_str = file.read()

map_from, map_to, destination_range_start, source_range_start, range_length = None, None, None, None, None
mappings = []

# Key = tuple (map_from, map_to)
# Value = list of mappings. Each mappings is tuple (destination_range_start, source_range_start, range_length)
almanac = {}

# Key = destination, eg. "soil".
# Value = source, eg, "seed".
destination_to_source = {}

for line in almanac_str.split('\n'):
    if 'seeds:' in line:
        seeds = parse_seeds(line)

    elif len(line) != 0:            # Skip blank lines.
        # ic(line)

        if "map:" in line:
            if len(mappings) != 0:
                almanac[(map_from, map_to)] = mappings

            map_from, map_to = parse_map(line)
            destination_to_source[map_to] = map_from
            mappings = []

        else:
            destination_range_start, source_range_start, range_length = parse_range(line)
            mappings.append((destination_range_start, source_range_start, range_length))

        # ic(map_from, map_to, mappings)

almanac[(map_from, map_to)] = mappings

ic(seeds, almanac, destination_to_source)

start_target = 1
done = False

while not done:
    target = start_target
    map_to = 'location'
    map_from = destination_to_source[map_to]

    failure = False
    while not failure and map_to != 'seed':
        target = back_correspond(target=target, mappings=almanac[(map_from, map_to)])

        if target < 0:
            failure = True
        else:
            map_to = map_from
            if map_to in destination_to_source:
                map_from = destination_to_source[map_to]

    if not failure:
        if seed_exists(candidate_seed=target, seeds=seeds):
            done = True

    if not done:
        start_target += 1

    if start_target % 1000000 == 0:
        ic(start_target)

ic(failure, start_target)


from django import forms

from .models import *
from .widget import *
from django.utils.translation import gettext_lazy as _

class EngagementForm(forms.ModelForm):
    class Meta:
        model = Engagement

        fields = ['provider', 'parent', 'start_date',
                  'time_code', 'fye', 'type']

        widgets = {
            'fye': DatePickerInput,
            'start_date': DatePickerInput
        }

class EditEngagementForm(forms.ModelForm):
    class Meta:
        model = Engagement

        fields = ['provider', 'parent', 'start_date',
                  'time_code', 'budget_hours', 'fye', 'type', 'srg_id']

        widgets = {
            'fye': DatePickerInput,
            'start_date': DatePickerInput
        }

class CompleteEngagementForm(forms.ModelForm):
    class Meta:
        model = Engagement

        fields = ['is_complete']

        labels = {
            'is_complete': _('Is Complete')
        }

class AssignmentForm(forms.ModelForm):
    class Meta:
        model = Assignments

        fields = ['engagement', 'assignee']

class TimeForm(forms.ModelForm):
    class Meta:
        model = Time

        fields = ['date', 'hours', 'time_type_id', 'note']

        labels = {
            'date': _('Date'),
            'hours': _('Hours'),
            'time_type_id': _('Type'),
            'note': _('Note')
        }

        widgets = {
            'note': forms.Textarea(attrs={'rows': 5, 'cols': 40}),
            'date': DatePickerInput()
        }

class EditTimeForm(forms.ModelForm):
    class Meta:
        model = Time

        fields = ['engagement', 'date', 'hours', 'note']

        labels = {
            'engagement': _('Engagement'),
            'date': _('Date'),
            'hours': _('Hours'),
            'note': _('Note')
        }

        widgets = {
            'note': forms.Textarea(attrs={'rows': 5, 'cols': 40}),
            'date': DatePickerInput()
        }

class NewTimeCodeForm(forms.ModelForm):
    class Meta:
        model = Timecode

        fields = ['time_code', 'time_code_desc', 'time_code_hours']

        labels = {
            'time_code': _('Time Code'),
            'time_code_desc': _('Description'),
            'time_code_hours': _('Hours Budget')
        }

        widgets = {
            'time_code': forms.TextInput(attrs={'size': 5}),
            'time_code_desc': forms.TextInput(attrs={'size': 75}),
            'time_code_hours': forms.TextInput(attrs={'size': 5})
        }

class EditTimeCodeForm(forms.ModelForm):
    class Meta:
        model = Timecode

        fields = ['time_code_desc', 'time_code_hours']

        labels = {
            'time_code_desc': _('Description'),
            'time_code_hours': _('Hours Budget')
        }

        widgets = {
            'time_code_desc': forms.TextInput(attrs={'size': 75}),
            'time_code_hours': forms.TextInput(attrs={'size': 5})
        }

class TodoForm(forms.ModelForm):
    class Meta:
        model = Todolist

        fields = ['todo_date', 'anticipated_hours', 'note']

        labels = {
            'todo_date': _('Start Date'),
            'anticipated_hours': _('Expected Hours'),
            'note': _('Note')
        }

        widgets = {
            'note': forms.Textarea(attrs={'rows': 5, 'cols': 40}),
            'todo_date': DatePickerInput()
        }

class ExpenseForm(forms.ModelForm):
    class Meta:
        model = Expense

        fields = ['expense_category', 'expense_amount']

        labels = {
            'engagement': _('Engagement'),
            'expense_category': _('Category'),
            'expense_amount': _('Amount')
        }


import sys
import requests

if __name__ == "__main__":
    order = sys.argv[1].lower()

    user = None
    users = None

    if order == "get_json":
        resp = requests.get("http://localhost:5000/api/users/1")
        user = resp.json()
    elif order == "list_json":
        resp = requests.get("http://localhost:5000/api/users")
        users = resp.json()
    elif order == "create_json":
        body = {
            "name": "Lance Armstrong",
            "occupation": "Cyclist",
            "birthday": "2000-01-01",
        }
        resp = requests.post("http://localhost:5000/api/users/new", json=body)
        user = resp.json()
    elif order == "update_json":
        body = {
            "name": "Bob Barker",
            "occupation": "TV Show Host",
            "birthday": "1923-12-12",
        }
        resp = requests.put("http://localhost:5000/api/users/1", json=body)
        user = resp.json()
    elif order == "delete_json":
        resp = requests.delete("http://localhost:5000/api/users/1")
        user = resp.json()
    else:
        print("Invalid command")
        sys.exit(1)

    print(resp.status_code)
    print(resp.text)

    if user:
        print(user)

    if users:
        print(users)


from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
from pdf2image import convert_from_path

def pdf2img_converter():
    try:
        # convert_from_path will get the PDF file from the entry widget we created in GUI.
        imgs = convert_from_path(str(entry.get()))
        for i in range(len(imgs)):
            # Saves the images as JPEG File format using .save function
            imgs[i].save('page'+str(i)+'.jpg', 'JPEG')

    # If error or exception is found then it will show the error message box.
    except Exception as e:
        # Prints the exception in console.
        print(e)
        # Shows the result message box saying "No PDF Found"
        messagebox.showinfo("Result", "NO PDF Found")
    else:
        # else if no error found, then it show success message box.
        messagebox.showinfo("Result", "Converted to Image Successfully")

# Function which will browse for pdf file.
def source_filename():
    # configures the state of entry to normal
    entry.configure(state='normal')
    # clears the input in the entry
    entry.delete(0, END)
    # ask for file open with file types only PDF.
    src = askopenfilename(
        title="Choose a File",
        filetypes=[('PDF Files', '.pdf')])
    # Inserts the path of PDF file in the entry
    entry.insert(0, src)
    # again configures the state of entry to disabled.
    entry.configure(state='disabled')

# Creating GUI Window
mainWindow = Tk()
# Title for Window
mainWindow.title("PDF2IMG CONVERTER")
# This will prevent program window to resize.
mainWindow.resizable(width=False, height=False)

# Title Heading for Program Name
titleHeading = Label(mainWindow, text="PDF2IMG CONVERTER", font=("New Times Roman", 20, "italic"))
# .grid is used to place widgets in grid, column and row. We just have to mention row and column value.
titleHeading.grid(row=0, column=0, columnspan=3, padx=10, pady=10)

# Label (Text) for Choosing File.
chooseFileLabel = Label(mainWindow, text="Choose File").grid(row=1, column=0)

# Entry widget is used to get input from user, in this case we will use it get the PDF file location.
entry = Entry(mainWindow, width=30)
entry.grid(row=1, column=1)

# Button widget for browsing the file explorer and locating file.
btnOpenFile = Button(mainWindow, text="Browse", command=lambda: source_filename())
btnOpenFile.grid(row=1, column=2)

# Button which will convert PDF to Image on click.
btnConvert = Button(mainWindow, text="CONVERT", command=pdf2img_converter, font=("New Times Roman", 12, "bold"))
btnConvert.grid(row=3, column=1, padx=5, pady=5)

# mainloop method is used when you program is ready to run.
# mainloop() is infinite loop which runs until program is not closed
mainWindow.mainloop()


import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation, rc
from shapely.geometry import Point, LineString
from HamSandwich.GeomUtils import *

def prepare_axis(min_x=-10,max_x=10,min_y=-10,max_y=10):
    plt.grid(True,which='major')
    ax = plt.gca()
    min_x = int(min_x)
    max_x = int(max_x)
    min_y = int(min_y)
    max_y = int(max_y)
    ax.set_xlim(min_x,max_x)
    ax.set_ylim(min_y,max_y)
    plt.xticks(np.arange(min(np.array(ax.get_xlim())), max(np.array(ax.get_xlim()))+1, 1.0))
    plt.yticks(np.arange(min(np.array(ax.get_ylim())), max(np.array(ax.get_ylim()))+1, 1.0))
    plt.axhline(0, color='black')
    plt.axvline(0, color='black')

def plot_line(L, linestyle='--', color='b'):
    """Add line to axis

    Arguments:
        L {GeomUtils.Line}
    """
    axes = plt.gca()
    x_vals = np.array(axes.get_xlim())
    y_vals = L.b + L.m * x_vals
    plt.plot(x_vals, y_vals, ls=linestyle, color=color)

def plot_vertical_line(x, linestyle=':', color='g', linewidth=2):
    """Plot vertical line on axis

    Arguments:
        x {int} -- X coordinate
    """
    plt.axvline(x=x, ls=linestyle, color=color, linewidth=linewidth)

def plot_line_segment(L, linestyle='-', color='b'):
    """Add line segment to axis

    Arguments:
        L {GeomUtils.LineSegment}
    """
    plt.plot([L.p1.x,L.p2.x],[L.p1.y,L.p2.y], ls=linestyle, color=color, linewidth=4)

def plot_point(P, marker='o', color='b',size=5):
    """Add point to axis

    Arguments:
        P {shapely.geometry Point}
    """
    plt.plot(P.x,P.y, marker=marker, color=color,markersize=size)

def plot_interval(I, linestyle=':', color='g'):
    plot_vertical_line(I.l, linestyle=linestyle, color=color, linewidth=2)
    plot_vertical_line(I.r, linestyle=linestyle, color=color, linewidth=2)

def plot_points_and_duals(ham_instance,x=0.5):
    for p,d in zip(ham_instance.red_points, ham_instance.red_duals):
        plot_point(p, color='r')
        plt.draw()
        plt.pause(x)
        plot_line(d, color='r')
        plt.draw()
        plt.pause(x)
    if ham_instance.extra_red:
        plot_point(ham_instance.extra_red, color='r')
        plt.draw()
        plt.pause(x)
        plot_line(compute_dual_line(ham_instance.extra_red), color='r')
        plt.draw()
        plt.pause(x)
    for p,d in zip(ham_instance.blue_points, ham_instance.blue_duals):
        plot_point(p, color='b')
        plt.draw()
        plt.pause(x)
        plot_line(d, color='b')
        plt.draw()
        plt.pause(x)
    if ham_instance.extra_blue:
        plot_point(ham_instance.extra_blue, color='b')
        plt.pause(x)
        plot_line(compute_dual_line(ham_instance.extra_blue), color='b')
        plt.pause(x)

def plot_point_set(ham_instance,x=0.5):
    for p in ham_instance.red_points:
        plot_point(p, color='r')
        plt.draw()
        plt.pause(x)
    if ham_instance.extra_red:
        plot_point(ham_instance.extra_red, color='r')
        plt.pause(x)
    for p in ham_instance.blue_points:
        plot_point(p, color='b')
        plt.draw()
        plt.pause(x)
    if ham_instance.extra_blue:
        plot_point(ham_instance.extra_blue, color='b')
        plt.pause(x)


# Exercicio 1:

# Escreva um programa que retorne uma lista com os valores numericos de 1 a N, mas com as seguintes excecoes:

# Numeros divisiveis por 3 deve aparecer como 'Fizz' ao inves do numero;

# Numeros divisiveis por 5 devem aparecer como 'Buzz' ao inves do numero;

# Numeros divisiveis por 3 e 5 devem aparecer como 'FizzBuzz' ao inves do numero';

def fizzbuzz(n):
    store_result = [];
    for index in range(1, n+1):
        divisible_by_three = index % 3 == 0;
        divisible_by_five = index % 5 == 0;
        if (divisible_by_three and divisible_by_five):
            store_result.append('FizzBuzz')
        elif (divisible_by_three):
            store_result.append('Fizz')
        elif (divisible_by_five):
            store_result.append('Buzz')
        else:
            store_result.append(index)
    return store_result


class Sardinas_Patterson:
    # Sardinas and patterson
    def multiply(self,lang1, lang2):
        newLang = set()
        for u in lang1 :
            for v in lang2 :
                if len(u) >= len(v) and u.find(v) == 0:
                    newLang.add(u[len(v):])
        return newLang

    def removeVoid(self,language):
        result = set()
        for u in language:
            if u != '' :
                result.add(u)

        return result

    def sardinas_patterson(self,language):
        uN = self.removeVoid(self.multiply(language, language))
        uN_1 = []
        while True :
            uN_1.append(set(uN))
            uN = self.multiply(uN, language).union(self.multiply(language, uN))

            for value in uN :
                if value == "":
                    return 0

            for value in uN_1 :
                if value == uN :
                    return 1


import numpy as np
from joblib import Parallel, delayed
from scipy.interpolate import interp1d
from scipy.special import erf, erfinv
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import FLOAT_DTYPES, check_array, check_is_fitted

class GaussRankScaler(BaseEstimator, TransformerMixin):
    """Transform features by scaling each feature to a normal distribution.
    Parameters
        ----------
        epsilon : float, optional, default 1e-4
            A small amount added to the lower bound or subtracted
            from the upper bound. This value prevents infinite number
            from occurring when applying the inverse error function.
        copy : boolean, optional, default True
            If False, try to avoid a copy and do inplace scaling instead.
            This is not guaranteed to always work inplace; e.g. if the data is
            not a NumPy array, a copy may still be returned.
        n_jobs : int or None, optional, default None
            Number of jobs to run in parallel.
            ``None`` means 1 and ``-1`` means using all processors.
        interp_kind : str or int, optional, default 'linear'
           Specifies the kind of interpolation as a string
            ('linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
            'previous', 'next', where 'zero', 'slinear', 'quadratic' and 'cubic'
            refer to a spline interpolation of zeroth, first, second or third
            order; 'previous' and 'next' simply return the previous or next value
            of the point) or as an integer specifying the order of the spline
            interpolator to use.
        interp_copy : bool, optional, default False
            If True, the interpolation function makes internal copies of x and y.
            If False, references to `x` and `y` are used.
        Attributes
        ----------
        interp_func_ : list
            The interpolation function for each feature in the training set.
    """

    def __init__(
        self,
        epsilon=1e-4,
        copy=True,
        n_jobs=None,
        interp_kind="linear",
        interp_copy=False,
    ):
        self.epsilon = epsilon
        self.copy = copy
        self.interp_kind = interp_kind
        self.interp_copy = interp_copy
        self.fill_value = "extrapolate"
        self.n_jobs = n_jobs
        self.bound = 1.0 - self.epsilon

    def fit(self, X, y=None):
        """Fit interpolation function to link rank with original data for future scaling
        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            The data used to fit interpolation function for later scaling along the features axis.
        y
            Ignored
        """
        X = check_array(
            X, copy=self.copy, estimator=self, dtype=FLOAT_DTYPES, force_all_finite=True
        )

        self.interp_func_ = Parallel(n_jobs=self.n_jobs)(
            delayed(self._fit)(x) for x in X.T
        )
        return self

    def _fit(self, x):
        x = self.drop_duplicates(x)
        rank = np.argsort(np.argsort(x))
        factor = np.max(rank) / 2.0 * self.bound
        scaled_rank = np.clip(rank / factor - self.bound, -self.bound, self.bound)
        return interp1d(
            x,
            scaled_rank,
            kind=self.interp_kind,
            copy=self.interp_copy,
            fill_value=self.fill_value,
        )

    def transform(self, X, copy=None):
        """Scale the data with the Gauss Rank algorithm
        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            The data used to scale along the features axis.
        copy : bool, optional (default: None)
            Copy the input X or not.
        """
        check_is_fitted(self, "interp_func_")

        copy = copy if copy is not None else self.copy
        X = check_array(
            X, copy=copy, estimator=self, dtype=FLOAT_DTYPES, force_all_finite=True
        )

        X = np.array(
            Parallel(n_jobs=self.n_jobs)(
                delayed(self._transform)(i, x) for i, x in enumerate(X.T)
            )
        ).T
        return X

    def _transform(self, i, x):
        clipped = np.clip(self.interp_func_[i](x), -self.bound, self.bound)
        return erfinv(clipped)

    def inverse_transform(self, X, copy=None):
        """Scale back the data to the original representation
        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            The data used to scale along the features axis.
        copy : bool, optional (default: None)
            Copy the input X or not.
        """
        check_is_fitted(self, "interp_func_")

        copy = copy if copy is not None else self.copy
        X = check_array(
            X, copy=copy, estimator=self, dtype=FLOAT_DTYPES, force_all_finite=True
        )

        X = np.array(
            Parallel(n_jobs=self.n_jobs)(
                delayed(self._inverse_transform)(i, x) for i, x in enumerate(X.T)
            )
        ).T
        return X

    def _inverse_transform(self, i, x):
        inv_interp_func = interp1d(
            self.interp_func_[i].y,
            self.interp_func_[i].x,
            kind=self.interp_kind,
            copy=self.interp_copy,
            fill_value=self.fill_value,
        )
        return inv_interp_func(erf(x))

    @staticmethod
    def drop_duplicates(x):
        is_unique = np.zeros_like(x, dtype=bool)
        is_unique[np.unique(x, return_index=True)[1]] = True
        return x[is_unique]


from django import forms

from .models import ColorPickerImageHolder

# В этом разделе создаются формы для html-страниц

# Создаем класс формы, который связан с моделью ColorPickerImageHolder из базы данных

class ImageUploadForm(forms.ModelForm):
    class Meta:

        # Связываем данную форму с моделью ColorPickerImageHolder из базы данных
        # Берем поля модели за основу формы

        model = ColorPickerImageHolder

        # Отображаем только следующие поля модели

        fields = ("image_title", "image_file", )

        # Видоизменяем поля модели в поля формы и добавляем стороние атрибуты

        widgets = {

            # Текстовое поле

            "image_title": forms.TextInput(
                attrs={'type': 'text', 'class': 'form-control mt-1', 'placeholder': 'Название изображения',
                       'name': 'image_title',
                       'required': 'required'}),

            # Поле выбора файлов

            "image_file": forms.ClearableFileInput(
                attrs={'type': 'file', 'class': 'form-control mt-2', 'name': 'image-for-color-picker-path',
                       'accept': 'image/png, image/jpeg',
                       'required': 'required'}),

        }