import asyncio
import datetime
import os

import aiohttp
import defusedxml.minidom
import dotenv
import pandas as pd

import pyrotun

logger = pyrotun.getLogger()

dotenv.load_dotenv()
LONGITUDE = os.getenv("LOCAL_LONGITUDE")
LATITUDE = os.getenv("LOCAL_LATITUDE")
MET_CLIENT_ID = os.getenv("FROST_CLIENT_ID")

class YrConnection:
    def __init__(self):
        self.websession = None

    async def ainit(self, websession=None):
        logger.info("yr.ainit()")
        self.websession = websession
        if self.websession is None:
            self.websession = aiohttp.ClientSession()

    async def nowcast_precipitation_rates(self):
        """Returns a Pandas series with the 5 minute precipitation forecast"""
        async with self.websession.get(
            "https://api.met.no/weatherapi/nowcast/2.0/complete",
            params=dict(lon=LONGITUDE, lat=LATITUDE),
            auth=aiohttp.BasicAuth(MET_CLIENT_ID, ""),
            headers={"User-Agent": "Custom smarthouse using OpenHAB"},
        ) as response:
            result = await response.json()
            dframe = pd.DataFrame(
                [
                    (x["time"], x["data"]["instant"]["details"]["precipitation_rate"])
                    for x in result["properties"]["timeseries"]
                ],
                columns=["datetime", "precipitation_rate"],
            ).set_index("datetime")
            # unit is mm/h
            dframe.index = pd.to_datetime(dframe.index).tz_convert(
                os.getenv("TIMEZONE")
            )
            return dframe["precipitation_rate"]

    async def get_svg_meteogram(self, met_location_id):
        async with self.websession.get(
            "https://www.yr.no/nb/innhold/" + met_location_id + "/meteogram.svg"
        ) as response:
            assert response.status == 200
            svg = await response.text()
            return svg

    async def forecast(self):
        """Returns a dataframe with the current forecast"""
        async with self.websession.get(
            "https://api.met.no/weatherapi/locationforecast/2.0/complete",
            params=dict(lon=LONGITUDE, lat=LATITUDE),
            auth=aiohttp.BasicAuth(MET_CLIENT_ID, ""),
            headers={"User-Agent": "Custom smarthouse using OpenHAB"},
        ) as response:
            result = await response.json()
            time_index = [x["time"] for x in result["properties"]["timeseries"]]
            dframe = pd.DataFrame(
                index=time_index,
                data=[
                    x["data"]["instant"]["details"]
                    for x in result["properties"]["timeseries"]
                ],
            )
            # unit is mm/h
            dframe.index = pd.to_datetime(dframe.index).tz_convert(
                os.getenv("TIMEZONE")
            )

            dframe["symbol_code"] = [
                x["data"]["next_1_hours"]["summary"]["symbol_code"]
                if "next_1_hours" in x["data"]
                else ""
                for x in result["properties"]["timeseries"]
            ]
            prec_frame = pd.DataFrame(
                index=dframe.index,
                data=[
                    x["data"]["next_1_hours"]["details"]
                    if "next_1_hours" in x["data"]
                    else {}
                    for x in result["properties"]["timeseries"]
                ],
            )
            dframe = pd.concat([dframe, prec_frame], axis=1)

            return dframe

    async def get_historical_cloud_fraction(
        self, startdate="2017-01-01", enddate=datetime.datetime.now().date().isoformat()
    ):
        """Returns a series with historical cloud fraction

        Values for every third hour. 0.0 means clear sky, 1.0 means
        overcast.
        """
        async with self.websession.get(
            "https://frost.met.no/observations/v0.jsonld",
            params=dict(
                sources="SN50540",
                referencetime=str(startdate) + "/" + str(enddate),
                elements="cloud_area_fraction",
            ),
            auth=aiohttp.BasicAuth(MET_CLIENT_ID, ""),
            headers={"User-Agent": "Custom smarthouse using OpenHAB"},
        ) as response:
            if response.ok is False:
                return None
            result = await response.json()
            time_index = [x["referenceTime"] for x in result["data"]]
            cloud_fractions = [x["observations"][0]["value"] for x in result["data"]]
            series = pd.Series(
                cloud_fractions,
                index=pd.to_datetime(time_index),
                name="cloud_area_fraction",
            )
            # the series is of type "octa", where 0 is clear sky, and
            # 8 is totally overcast. Translate this to a fraction beteween
            # 0 (clear sky) and 1.0 (overcast)
            series = series / 8.0
            return series

def crop_svg_meteogram(svg) -> str:
    """Removes logos and stuff from yr's meteogram"""
    doc = defusedxml.minidom.parseString(svg)

    root = doc.childNodes[0]
    # Remove all whitespace nodes:
    for node in root.childNodes:
        if node.toxml().strip() == "":
            node.unlink()

    # node 3 should contain <rect> which fill the background with white.
    root.childNodes[3].setAttribute("height", "280")

    # Remove blue yr-logo:
    assert "circle fill" in root.childNodes[5].toxml()
    root.childNodes[5].unlink()

    assert "En tjeneste fra" in root.childNodes[7].toxml()
    root.childNodes[7].unlink()

    # NRK-logo:
    root.childNodes[9].unlink()

    # Meteorologisk institutt-logo:
    root.childNodes[11].unlink()

    assert "Værvarsel for " in root.childNodes[13].toxml()
    root.childNodes[13].unlink()

    # Node 15 er selve meteogrammet, inkludert dato.
    meteo = root.childNodes[15]
    assert "Vindkast" in meteo.toxml()

    assert meteo.getAttribute("transform") == "translate(0, 84.86)"
    meteo.setAttribute("transform", "translate(0, 0)")

    meteo.childNodes[11].unlink()

    return doc.toxml()

async def main():
    yr = YrConnection()
    await yr.ainit()
    res = await yr.get_historical_cloud_fraction()
    print(res)

if __name__ == "__main__":
    asyncio.run(main())


import pygame
import sys
import networkFunctions
import threading

def ping_and_draw(ip_address, bar_x, bar_y, bar_width, bar_height):
    if networkFunctions.ping(ip_address):
        pygame.draw.rect(screen, bar_colors[0], (bar_x, bar_y, bar_width, bar_height))
    else:
        pygame.draw.rect(screen, bar_colors[1], (bar_x, bar_y, bar_width, bar_height))

    font = pygame.font.SysFont("Calibri", 15)
    img = font.render(ip_address, True, (0, 0, 0))
    screen.blit(img, (bar_x, bar_y))

devices_to_ping = [
    {"ip_address": "192.168.0.106", "reachable": False, "response_time": None},
    {"ip_address": "192.168.189.1", "reachable": False, "response_time": None},
    {"ip_address": "192.168.1.3", "reachable": False, "response_time": None},
]

threads = []

# Initialize Pygame
pygame.init()

# Set the dimensions of the screen
screen_width = 400
screen_height = 500
screen = pygame.display.set_mode((screen_width, screen_height))
font = pygame.font.SysFont("Arial", 24)

# Set the color of the bars
bar_colors = [(0, 255, 0), (255, 0, 0)]

# Set the width and height of the bars
bar_width = 0
bar_height = 30

# Set the number of bars with the amount of devices to ping
num_bars = len(devices_to_ping)

# Set the initial positions and speeds of the bars
bars = []
bar_identifier = 0
for i in range(num_bars):
    bar_x = 0
    bar_y = (i + 1) * (bar_height + 10)
    bar_speed = 8
    bar_identifier += 1
    bars.append((bar_x, bar_y, bar_speed, bar_identifier))

# Update the Pygame display
pygame.display.flip()

# Set the clock
clock = pygame.time.Clock()
ping_results = [None] * num_bars

# Game loop
while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Move the bars from left to right
   # for i in range(num_bars):

    # Clear the screen
    screen.fill((255, 255, 255))

    # Draw the bars
    for i in range(num_bars):
        bar_width += 0.8
        if bar_width >= screen_width:
            bar_width = 0

        bar_x, bar_y, bar_speed, bar_identifier = bars[i]
        ip_address = devices_to_ping[i]["ip_address"]

        thread = threading.Thread(target=ping_and_draw, args=(ip_address, bar_x, bar_y, bar_width, bar_height))
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

    # Update the screen
    pygame.display.update()

    # Pause the game loop to control the frame rate
    clock.tick(30)


import tensorflow as tf
from tspmdp.modules.graph_encoder import CustomizableEncoder, GraphEncoder, WouterEncoder
import pytest
import shutil

def test_graph_encoder():
    B, N, F = 512, 14, 2
    n_heads = 8
    d_key = 64
    d_hidden = 256
    depth = 6
    d_model = 128
    model = GraphEncoder(d_model, depth, n_heads, d_key, d_hidden)
    inputs = tf.ones((B, N, F))
    assert model(inputs).shape == (B, N, d_model)

def test_woter_graph_encoder():
    B, N, F = 512, 14, 2
    n_heads = 8
    d_key = 64
    d_hidden = 256
    depth = 6
    d_model = 128
    model = WouterEncoder(d_model, depth, n_heads, d_key, d_hidden)
    inputs = tf.ones((B, N, F))
    assert model(inputs).shape == (B, N, d_model)

@pytest.mark.parametrize("final_ln", [True, False])
@pytest.mark.parametrize("transformer", ["preln", "gate", "linear", "postbn"])
def test_customizable_encoder(transformer, final_ln):
    B, N, F = 512, 14, 2
    n_heads = 8
    d_key = 64
    d_hidden = 256
    depth = 6
    d_model = 128
    model = CustomizableEncoder(d_model, depth, n_heads, d_key, d_hidden)
    inputs = tf.ones((B, N, F))
    assert model(inputs).shape == (B, N, d_model)


from flask import Flask , render_template, url_for ,request, jsonify,redirect, flash
from event import events
from alerts import simulate_event_generation
#from alerts import *
app = Flask(__name__)
@app.route('/')
def index():
    return render_template("index.html")

@app.route("/details" , methods = ['POST'])
def details():
    vehicle_id = request.form['id']
    matching_events = [event for event in events if event['vehicle_id'] == int(vehicle_id)]
    if matching_events:
        return render_template("details.html" , value = vehicle_id)
    else:
        return "<h1> Vehicle does not exist in DB </h1>"

@app.route("/alerts/<vehicle_id>" , methods = ["GET"])
def notify():
    alert = simulate_event_generation(int(request.form["id"]),30 )
    return render_template('alertnotify.html', vehicle_id=request.form["id"], alerts=alert)

"""@app.route('/check_vehicle', methods=['POST'])
def check_vehicle():
        vehicle_id = request.form.get('id')
        matching_events = [event for event in events if event['vehicle_id'] == int(vehicle_id)]
        if matching_events:
            return jsonify({"message: vehicle exists"})
    # Check if the vehicle_id exists in events

        else:
            return jsonify({"message": "Vehicle does not exist in events data."})

"""

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


from django.conf.urls import patterns, include, url
from django.contrib import admin
#from django.conf import settings

# Uncomment the next two lines to enable the admin:
admin.autodiscover()

urlpatterns = patterns('',
    # Global URLs
    url(r'^$', 'py_arduino_web.dj.views.home', name='home'),
    url(r'^connect/?$', 'py_arduino_web.dj.views.connect', name='connect'),

    # URLs for methods
    url(r'^pin_mode/?$', 'py_arduino_web.dj.views.pin_mode', name='pin_mode'),
    url(r'^digital_write/?$', 'py_arduino_web.dj.views.digital_write', name='digital_write'),
    url(r'^analog_write/?$', 'py_arduino_web.dj.views.analog_write', name='analog_write'),
    url(r'^analog_read/?$', 'py_arduino_web.dj.views.analog_read', name='analog_read'),
    url(r'^digital_read/?$', 'py_arduino_web.dj.views.digital_read', name='digital_read'),
    url(r'^delay/?$', 'py_arduino_web.dj.views.delay', name='delay'),
    url(r'^get_avr_cpu_type$', 'py_arduino_web.dj.views.get_avr_cpu_type',
        name='get_avr_cpu_type'),
    url(r'^get_arduino_type_struct$', 'py_arduino_web.dj.views.get_arduino_type_struct',
        name='get_arduino_type_struct'),
    url(r'^ping$', 'py_arduino_web.dj.views.ping', name='ping'),
    url(r'^validate_connection$', 'py_arduino_web.dj.views.validate_connection',
        name='validate_connection'),
    url(r'^get_free_memory$', 'py_arduino_web.dj.views.get_free_memory',
        name='get_free_memory'),
    url(r'^close$', 'py_arduino_web.dj.views.close', name='close'),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

urlpatterns += patterns('django.contrib.staticfiles.views',
    url(r'^static/(?P<path>.*)$', 'serve'),
)


import math
import torch
import torch.nn as nn

class LSTM(nn.Module):
    """
    Own implementation of LSTM cell.
    """

    def __init__(self, lstm_hidden_dim, embedding_size):
        """
        Initialize all parameters of the LSTM class.

        Parameters
        ----------
        lstm_hidden_dim : int
            hidden state dimension.
        embedding_size : int
            size of embedding (and hence input sequence).
        """
        super(LSTM, self).__init__()
        self.hidden_dim = lstm_hidden_dim
        self.embed_dim = embedding_size
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        # embedding weights
        self.w_x = nn.Parameter(
            torch.zeros(4 * self.hidden_dim, self.embed_dim), requires_grad=True
        )
        self.w_h = nn.Parameter(
            torch.zeros(4 * self.hidden_dim, self.hidden_dim), requires_grad=True
        )
        # bias
        self.b_g = nn.Parameter(torch.zeros(self.hidden_dim), requires_grad=True)
        self.b_i = nn.Parameter(torch.zeros(self.hidden_dim), requires_grad=True)
        self.b_f = nn.Parameter(torch.zeros(self.hidden_dim), requires_grad=True)
        self.b_o = nn.Parameter(torch.zeros(self.hidden_dim), requires_grad=True)
        # cell and hidden state
        self.h = None
        self.c = None
        #######################
        # END OF YOUR CODE    #
        #######################
        self.init_parameters()

    def init_parameters(self):
        """
        Parameters initialization.

        Parameters
        ----------
        self.parameters: list of all parameters.
        self.hidden_dim: hidden state dimension.
        """
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        for param in self.parameters():
            # initialize weights as specified by inst
            nn.init.uniform_(
                param, -1 / math.sqrt(self.hidden_dim), 1 / math.sqrt(self.hidden_dim)
            )
        # add one to forget gate bias
        with torch.no_grad():
            self.b_f += 1
        #######################
        # END OF YOUR CODE    #
        #######################

    def forward(self, embeds):
        """
        Forward pass of LSTM.

        Parameters
        ----------
        embeds : array-like
            embedded input sequence with shape
            (input length, batch size, embedding_size)

        Returns
        -------
        output : array-like
            output of LSTM with shape
            (input length, batch size, hidden_size)
        """
        #
        #######################
        # PUT YOUR CODE HERE  #
        #######################

        # initialize output, ensuring its on the same device as embeds
        output = torch.zeros(
            (embeds.shape[0], embeds.shape[1], self.hidden_dim), device=self.w_x.device
        )
        # initialize hidden and cell states if necessary
        if self.h is None:
            self.h = torch.zeros(
                embeds.shape[1], self.hidden_dim, device=self.w_x.device
            )
        if self.c is None:
            self.c = torch.zeros(
                embeds.shape[1], self.hidden_dim, device=self.w_h.device
            )
        # LSTM computation
        for j, seq_el in enumerate(embeds):
            biases = torch.hstack((self.b_i, self.b_f, self.b_o, self.b_g))
            opt_mult = seq_el @ self.w_x.T + self.h @ self.w_h.T + biases
            i, f, o, g = torch.chunk(opt_mult, 4, dim=1)
            g = torch.tanh(g)
            i = torch.sigmoid(i)
            f = torch.sigmoid(f)
            o = torch.sigmoid(o)
            self.c = g * i + self.c * f
            self.h = torch.tanh(self.c) * o
            output[j] = self.h
        return output
        #######################
        # END OF YOUR CODE    #
        #######################

class TextGenerationModel(nn.Module):
    """
    This module uses your implemented LSTM cell for text modelling.
    It should take care of the character embedding,
    and linearly maps the output of the LSTM to your vocabulary.
    """

    def __init__(self, args):
        """
        Initializing the components of the TextGenerationModel.

        Parameters
        ----------
        args.vocabulary_size: int
            The size of the vocabulary.
        args.embedding_size: int
            The size of the embedding.
        args.lstm_hidden_dim: int
            The dimension of the hidden state in the LSTM cell.
        """
        super(TextGenerationModel, self).__init__()
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        self.embedding = nn.Embedding(args.vocabulary_size, args.embedding_size)
        self.lstm = LSTM(args.lstm_hidden_dim, args.embedding_size)
        self.linear = nn.Linear(args.lstm_hidden_dim, args.vocabulary_size)
        self.vocabulary_size = args.vocabulary_size
        #######################
        # END OF YOUR CODE    #
        #######################

    def forward(self, x):
        """
        Forward pass.

        Parameters
        ----------
        x : array-like
            input sequence with shape (seq_len, batch_size)
        """
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        # embedding gives (seq_len, batch_size, embedding_size)
        x = self.embedding(x)
        # lstm forward gives (seq_len, batch_size, hidden_size)
        x = self.lstm(x)
        # linear forward gives (seq_len, batch_size, vocabulary_size)
        out = self.linear(x)
        return out
        #######################
        # END OF YOUR CODE    #
        #######################

    def sample(self, batch_size=4, sample_length=30, temperature=0.0):
        """
        Sampling from the text generation model.

        Parameters
        ----------
        batch_size : int
            Number of samples to return
        sample_length : int
            length of desired sample.
        temperature: float
            temperature of the sampling process (see exercise sheet for definition).

        Returns
        -------
        samples : array-like
            samples with shape (sample_length, batch_size)
        """
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        # initialize characters randomly
        chars = torch.randint(self.vocabulary_size, (sample_length, batch_size))

        # overwrite all chars except first with sampled characters
        for step in range(1, sample_length):
            # use previous step, hidden/cell state are stored and kept track of BTS
            pred = self.forward(chars[step - 1].view(1, -1))[-1]
            # pred is of shape (1, batch_size, vocabulary_size)
            if temperature == 0:
                # argmax gives (1, batch_size)
                new_char = pred.argmax(dim=-1)
            else:
                # randomly sample using temperature-scaled softmax weights
                new_char = torch.multinomial(
                    torch.softmax(pred / temperature, dim=-1), 1
                ).squeeze()
            # save new char to the current step
            chars[step] = new_char

        return chars
        #######################
        # END OF YOUR CODE    #
        #######################

if __name__ == "__main__":
    hidden_dim = 5
    embed_size = 10
    batch_n = 3

    lstm = LSTM(hidden_dim, embed_size)
    out = lstm.forward(torch.randn(2, batch_n, embed_size))
    print(out.shape)


# importing the nltk suite
import nltk

# importing edit distance
from nltk.metrics.distance import edit_distance

# Downloading and importing package 'words'
nltk.download('words')
from nltk.corpus import words

# Assigning to variable
crt_wrds = words.words()

# loop for finding correct spellings based on edit distance and printing the correct words
def auto_crt(wrd):
	temp = [(edit_distance(wrd, w),w) for w in crt_wrds if w[0]==wrd[0]]
	return(sorted(temp, key = lambda val:val[0])[0][1])

# taking input from you
in_wrds=list(input("Enter words:").split(","))

# looping the list you have given and calling the auto corrector to print
for wrd in in_wrds:
    print(auto_crt(wrd.lower()))


import matplotlib.pyplot as plt

NONE = 1
LEFT = 2
UP = 4
INFINITY = 1e300 # беконечность

def dtw(s, n, h, m):
    #Привязка первой точки образа
	#1-Привязывать обязательно с первой точки исходной кривой
	#2-Разрешено привязывать с любой точки исходной кривой
    firstLineVariant = int(input("Enter first line variant (1 or 2): ")) # 1 or 2

    #Сжатие образца
	#1-сжатие запрещено
	#2-сжатие разрешено без штрафа
	#3-сжатие разрешено со штрафом
    deflateVariant = int(input("Enter deflate variant (1, 2 or 3): ")) # 1, 2 or 3

    #растяжение образца
	#1-растяжение запрещено
	#2-растяжение разрешено без штрафа
	#3-растяжение разрешено со штрафом
    stretchVariant = int(input("Enter stretch variant (1, 2 or 3): ")) # 1, 2 or 3

    #Привязка последней точки образа
	#1-разрешено заканчиваться на любой точке исходной кривой
	#2-привязывать обязательно к последней точке исходной кривой
    lastLineVariant = int(input("Enter last line variant (1 or 2): ")) # 1 or 2

    D = [[INFINITY for j in range(m)] for i in range(n)] # выделяем память под матрицу и заполняем элементы бесконечностями
    ways = [[-1 for j in range(m)] for i in range(n)]

    # проход по первой строке
    for j in range(m):
        if firstLineVariant == 1:
            for k in range(j + 1):
                D[0][j] += abs(s[0] - h[k])
        else:
            D[0][j] = abs(s[0] - h[j])

    # проход по всем строкам
    for i in range(n - 1):
        for j in range(m - 1):
            D[i + 1][j + 1] = min(D[i + 1][j + 1], D[i][j] + abs(s[i + 1] - h[j + 1])) # наложение образца
            ways[i + 1][j + 1] = ways[i + 1][j + 1] if D[i + 1][j + 1] < D[i][j] + abs(s[i + 1] - h[j + 1]) else UP + LEFT

            # сжатие
            if deflateVariant == 1:
                D[i + 1][j] = D[i + 1][j] # сжатие запрещено
                ways[i + 1][j] = ways[i + 1][j]
            elif deflateVariant == 2:
                D[i + 1][j] = min(D[i + 1][j], D[i][j]) # сжатие разрешено без штрафа
                ways[i + 1][j] = ways[i + 1][j] if D[i + 1][j] < D[i][j] else UP
            elif deflateVariant == 3:
                D[i + 1][j] = min(D[i + 1][j], D[i][j] + abs(s[i + 1]- h[j])) # сжатие разрешено со штрафом
                ways[i + 1][j] = ways[i + 1][j] if D[i + 1][j] < D[i][j] + abs(s[i + 1] - h[j]) else UP

            # растяжение
            if stretchVariant == 1:
                D[i][j + 1] = D[i][j + 1] # растяжение запрещено
                ways[i][j + 1] = ways[i][j + 1]
            elif stretchVariant == 1:
                D[i][j + 1] = min(D[i][j + 1], D[i][j]) # растяжение разрешено без штрафа
                ways[i][j + 1] = ways[i][j + 1] if D[i][j + 1] < D[i][j] else LEFT
            elif stretchVariant == 3:
                D[i][j + 1] = min(D[i][j + 1], D[i][j] + abs(s[i] - h[j + 1])) # растяжение разрешено со штрафом
                ways[i][j + 1] = ways[i][j + 1] if D[i][j + 1] < D[i][j] + abs(s[i] - h[j + 1]) else LEFT

    # проход по последней строке
    last = n - 1

    for j in range(m - 1):
        if lastLineVariant == 1:
            D[last][j + 1] = min(D[last][j + 1], D[last][j]) # можно связать с любой точкой
            ways[last][j + 1] = ways[last][j + 1] if D[last][j + 1] < D[last][j] else LEFT
        else:
            D[last][j + 1] = min(D[last][j + 1], D[last][j] + abs(s[last] - h[j + 1])) # обязательно привязать к последней
            ways[last][j + 1] = ways[last][j + 1] if D[last][j + 1] < D[last][j] + abs(s[last] - h[j + 1]) else LEFT

    lasti = n - 1
    lastj = m - 1

    # если не требуется привязка к последней точке, то ищем минимум в последней строке
    if lastLineVariant == 1:
        lastj = 0

        for j in range(1, m):
            if D[n - 1][j] < D[n - 1][lastj]:
                lastj = j

    way = [lasti * m + lastj] # создаём массив для пути обратно и запоминаем последнюю ячейку

    if D[lasti][lastj] == INFINITY:
        return None

    # пока не дойдём до конца
    while lasti != 0:
        if ways[lasti][lastj] == LEFT:
            lastj -= 1
        elif ways[lasti][lastj] == UP:
            lasti -= 1
        elif ways[lasti][lastj] == LEFT + UP:
            lastj -= 1
            lasti -= 1

        way.append(lasti * m + lastj)

    return reversed(way)

#Функция чтения из файла
def read(lst,lst_val,nametxt):
        c=0
        with open(nametxt) as file:
                for line in file.readlines():
                        a,b=[float(i) for i in line.split()]
                        lst.append(a)
                        lst_val.append(b)
#Функция записи в файл
def write(lst,nametxt):
        for item in lst:
            nametxt.write("%s\n" % item)

values1 = [] # считываем значения из первого файла
v1=[]
v2=[]
values2 = [] # считываем значения из второго файла
read(v1,values1,"y.txt")
read(v2,values2,"x.txt")
way = dtw(values1, len(values1), values2, len(values2))
result_x=[]
result_y=[]
#поднимем один график для удобства
for i in range(len(values1)):
    values1[i]+=2
if way is not None:
    # выводим путь
    print("Way:")
    with open("result.txt", "w") as f:
        for k in way:
            i = k // len(values2)
            j = k % len(values2)

            print(i + 1, j + 1)
            f.write(str(i + 1) + " " + str(j + 1) + "\n")

    read(result_x,result_y,"result.txt")

    plt.plot(values1,v1)
    plt.plot(values2,v2, color="red")

    i=0

    for j in range(0,len(result_x),10):#начинаем строить соответствие по ранее сохраненным границам y с максимальным коэффициентом корреляции
        plt.plot((values1[int(result_x[j])-1],values2[int(result_y[j])-1]),(v1[int(result_x[j])-1],v2[int(result_y[j])-1]),color='violet')
    plt.show()
else:
    print('No way')


import sys
import time
from PyQt5 import QtCore, QtGui, QtWidgets
from pyqtkeybind import keybinder
import pyautogui
from tensor2tensor import models
from user_problems import *
from translate import Translator
from configs import *

class WinEventFilter(QtCore.QAbstractNativeEventFilter):
    def __init__(self, keybinder):
        self.keybinder = keybinder
        super().__init__()

    def nativeEventFilter(self, eventType, message):
        ret = self.keybinder.handler(eventType, message)
        return ret, 0

class Ui_MainWindow(object):
    def __init__(self):

        self.translate_direction = 0  # 0: En -> Vi; 1: Vi -> En
        self.envi_translator = Translator(UniEnViConfig)
        self.vien_translator = Translator(UniViEnConfig)

        self.app = QtWidgets.QApplication(sys.argv)
        self.main_window = QtWidgets.QMainWindow()
        self.stylesheet = """
        QPushButton#switch_button{
            background-color: rgba(255, 255, 255, 0);
            border-color: #0b5ed7;
            border-style: solid;
            border-width: 2px;
            border-radius: 7px;
        }
        QPushButton#switch_button:hover{
            background-color: #0b5ed7
        }

        QPushButton#clear_button{
            color:#ffffff;
            background-color:#0d6efd;
            border-style: outset;
            border-width: 2px;
            border-radius: 10px;
        }
        QPushButton#clear_button:hover{
            background-color: #0b5ed7
        }

        QPushButton#translate_button{
            color:#ffffff;
            background-color:#0d6efd;
            border-style: outset;
            border-width: 2px;
            border-radius: 10px;
        }
        QPushButton#translate_button:hover{
            background-color: #0b5ed7
        }

        """
        self.setupUi(self.main_window)
        self.setup_shortcuts()
        self.main_window.show()
        self.app.setStyleSheet(self.stylesheet)
        sys.exit(self.app.exec_())

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(781, 591)
        MainWindow.setFocusPolicy(QtCore.Qt.NoFocus)
        MainWindow.setStyleSheet("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.input_box = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.input_box.setGeometry(QtCore.QRect(30, 170, 341, 231))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.input_box.setFont(font)
        self.input_box.setObjectName("input_box")
        self.output_box = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.output_box.setReadOnly(True)
        self.output_box.setGeometry(QtCore.QRect(410, 170, 341, 231))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.output_box.setFont(font)
        self.output_box.setObjectName("output_box")
        self.input_lang_label = QtWidgets.QLabel(self.centralwidget)
        self.input_lang_label.setGeometry(QtCore.QRect(30, 110, 241, 51))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.input_lang_label.setFont(font)
        self.input_lang_label.setStyleSheet("color: #1967d2")
        self.input_lang_label.setObjectName("input_lang_label")
        self.output_lang_lablel = QtWidgets.QLabel(self.centralwidget)
        self.output_lang_lablel.setGeometry(QtCore.QRect(510, 110, 241, 51))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.output_lang_lablel.setFont(font)
        self.output_lang_lablel.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        self.output_lang_lablel.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.output_lang_lablel.setStyleSheet("color: #1967d2")
        self.output_lang_lablel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.output_lang_lablel.setObjectName("output_lang_lablel")
        self.switch_button = QtWidgets.QPushButton(self.centralwidget, clicked=lambda: self.click_switch())
        self.switch_button.setGeometry(QtCore.QRect(355, 120, 71, 31))
        self.switch_button.setAutoFillBackground(False)
        self.switch_button.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("gui/images/two-way-arrow-2.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.switch_button.setIcon(icon)
        self.switch_button.setIconSize(QtCore.QSize(20, 20))
        self.switch_button.setObjectName("switch_button")
        self.clear_button = QtWidgets.QPushButton(self.centralwidget, clicked=lambda: self.click_clear())
        self.clear_button.setGeometry(QtCore.QRect(30, 420, 81, 41))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.clear_button.setFont(font)
        self.clear_button.setObjectName("clear_button")
        self.translate_button = QtWidgets.QPushButton(self.centralwidget, clicked=lambda: self.click_translate())
        self.translate_button.setGeometry(QtCore.QRect(325, 460, 131, 51))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(14)
        self.translate_button.setFont(font)
        self.translate_button.setObjectName("translate_button")
        self.app_name_label = QtWidgets.QLabel(self.centralwidget)
        self.app_name_label.setGeometry(QtCore.QRect(170, 20, 441, 51))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.app_name_label.setFont(font)
        self.app_name_label.setStyleSheet("color: #1967d2")
        self.app_name_label.setAlignment(QtCore.Qt.AlignCenter)
        self.app_name_label.setObjectName("app_name_label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 781, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def setup_shortcuts(self):
        # self.translate_shortcut = QtWidgets.QShortcut(
        #     QtGui.QKeySequence('Ctrl+D'),
        #     self.main_window
        # )
        # self.translate_shortcut.activated.connect(lambda: self.click_translate())

        # shortcut when not focus
        keybinder.init()
        keybinder.register_hotkey(self.main_window.winId(), 'Ctrl+D', self.translate_selected_text)
        self.win_event_filter = WinEventFilter(keybinder)
        self.event_dispatcher = QtCore.QAbstractEventDispatcher.instance()
        self.event_dispatcher.installNativeEventFilter(self.win_event_filter)

    def click_clear(self):
        self.input_box.setPlainText('')

    def click_translate(self):
        print('Clicked Translate Button')
        self.translate_button.setEnabled(False)
        # self.output_box.setPlainText('Translating.....')
        input_text = self.input_box.toPlainText().strip()
        print('input: ', input_text)
        if self.translate_direction == 0:
            output_text = self.envi_translator.translate_docs(input_text)
        else:
            output_text = self.vien_translator.translate_docs(input_text)
        self.output_box.setPlainText(output_text)
        print('output: ', output_text)
        self.translate_button.setEnabled(True)

    def click_switch(self):
        if self.translate_direction == 0:
            self.translate_direction = 1
            self.input_lang_label.setText('Vietnamese')
            self.output_lang_lablel.setText('English')
        else:
            self.translate_direction = 0
            self.input_lang_label.setText('English')
            self.output_lang_lablel.setText('Vietnamese')

    def translate_selected_text(self):
        pyautogui.hotkey('ctrl', 'c')
        time.sleep(0.03)
        text = QtWidgets.QApplication.clipboard().text()
        print(text)
        self.centralwidget.activateWindow()
        self.input_box.setPlainText(text)
        self.click_translate()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "My Translator"))
        self.input_box.setPlaceholderText(_translate("MainWindow", "Input"))
        self.output_box.setPlaceholderText(_translate("MainWindow", "Translation"))
        self.input_lang_label.setText(_translate("MainWindow", "English" if self.translate_direction == 0 else "Vietnamese"))
        self.output_lang_lablel.setText(_translate("MainWindow", "Vietnamese" if self.translate_direction == 0 else "English"))
        self.clear_button.setText(_translate("MainWindow", "Clear"))
        self.translate_button.setText(_translate("MainWindow", "Translate"))
        self.app_name_label.setText(_translate("MainWindow", "ABC TRANSLATOR"))

if __name__ == '__main__':
    Ui_MainWindow()


import re
import sys
from collections import namedtuple
from copy import deepcopy

pattern = re.compile(r"(-?\d+)")

Pos = namedtuple("Pos", "x, y")
Vel = namedtuple("Vel", "x, y")

def parse():
    pos = []
    vel = []
    with open(r".././data/day_10.txt") as f:
        for line in f:
            p1, p2, v1, v2 = re.findall(pattern, line)
            p = Pos(int(p1), int(p2))
            v = Vel(int(v1), int(v2))
            pos.append(p)
            vel.append(v)
    return pos, vel

def grid(rows, cols):
    return [["."] * rows for _ in range(cols)]

def part01(grid, new, offset):
    for n in new:
        grid[n.y - offset][n.x - offset] = "#"
    for g in grid:
        print(" ".join(g))

def get_row_col_and_offsets(pos):

    cols = [p.x for p in pos]
    rows = [p.y for p in pos]
    cmin, col = min(cols), max(cols)
    rmin, row = min(rows), max(rows)
    cols_offset = abs(cmin)
    rows_offset = abs(rmin)

    return col, row, cols_offset, rows_offset

if __name__ == "__main__":
    pos, vel = parse()
    col, row, cols_offset, rows_offset = get_row_col_and_offsets(pos)
    start = [Pos(p.x + cols_offset, p.y + rows_offset) for p in pos]
    size = [col + cols_offset, row + rows_offset]

    for count in range(1, sys.maxsize):
        new = []
        for i in range(len(start)):
            new.append(Pos(start[i].x + vel[i].x, start[i].y + vel[i].y))
        col, row, cols_offset, rows_offset = get_row_col_and_offsets(new)

        new_size = [col + cols_offset, row + rows_offset]

        if size[0] < new_size[0] or size[1] < new_size[1]:
            print(f"A winner in `{count}` seconds")
            # Part 2 answer
            assert count == 10081

            grid = grid(col - cols_offset + 1, row - rows_offset + 1)
            part01(grid, new, cols_offset)

            break

        size = new_size
        start = new


import shutil
import tempfile
from random import randint

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase, override_settings
from django.urls import reverse

from ..forms import PostForm
from ..models import Follow, Group, Post

User = get_user_model()

TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)

@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)
class TaskPagesTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user(username='auth')
        cls.small_gif = (
            b'\x47\x49\x46\x38\x39\x61\x02\x00'
            b'\x01\x00\x80\x00\x00\x00\x00\x00'
            b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'
            b'\x00\x00\x00\x2C\x00\x00\x00\x00'
            b'\x02\x00\x01\x00\x00\x02\x02\x0C'
            b'\x0A\x00\x3B'
        )
        cls.uploaded = SimpleUploadedFile(
            name='small.gif',
            content=cls.small_gif,
            content_type='image/gif'
        )
        cls.group = Group.objects.create(
            title='test-title',
            slug='test-slug',
            description='Тестовое описание',
        )
        cls.post = Post.objects.create(
            author=cls.user,
            text='Тестовый постfasdfasdf',
            group=cls.group,
            image=cls.uploaded
        )

    @classmethod
    def tearDownClass(cls):
        super().tearDownClass()
        shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)

    def setUp(self):
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)
        cache.clear()

    def test_correct_context_index(self):
        """Правильность контекста главной страницы."""
        response = self.client.get(reverse('posts:index'))
        self.assertIn('page_obj', response.context)
        self.assertEqual(response.context['page_obj'][0], self.post)

    def test_correct_context_group(self):
        """Правильность контекста списка постов группы."""
        response = self.client.get(reverse(
            'posts:group_list', kwargs={'slug': 'test-slug'}))
        self.assertIn('group', response.context)
        self.assertIn('page_obj', response.context)
        self.assertEqual(response.context['page_obj'][0].group,
                         self.group)
        self.assertEqual(response.context['page_obj'][0], self.post)

    def test_correct_context_post_detail(self):
        """Тест контекста страницы поста."""
        response = self.client.get(reverse(
            'posts:post_detail', args=(self.post.id,)))
        self.assertIn('post', response.context)
        self.assertEqual(response.context['post'],
                         self.post)

    def test_correct_context_profile(self):
        """Правильность контекста профиля пользователя."""
        response = self.client.get(reverse(
            'posts:profile', args=(self.user,)))
        self.assertIn('author', response.context)
        self.assertIn('page_obj', response.context)
        self.assertEqual(response.context['author'],
                         self.user)
        self.assertEqual(response.context['page_obj'][0], self.post)

    def test_correct_context_post_edit(self):
        """Контекст страницы создания/редактирования
        поста для авторизованного пользователя."""
        response = self.authorized_client.get(reverse(
            'posts:post_edit', args=(self.post.id,)))
        self.assertIn('form', response.context)
        self.assertIsInstance(response.context['form'], PostForm)
        if 'is_edit' in response.context:
            self.assertEqual(response.context['is_edit'], True)

class FollowTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user(username='auth')
        cls.small_gif = (
            b'\x47\x49\x46\x38\x39\x61\x02\x00'
            b'\x01\x00\x80\x00\x00\x00\x00\x00'
            b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'
            b'\x00\x00\x00\x2C\x00\x00\x00\x00'
            b'\x02\x00\x01\x00\x00\x02\x02\x0C'
            b'\x0A\x00\x3B'
        )
        cls.uploaded = SimpleUploadedFile(
            name='small.gif',
            content=cls.small_gif,
            content_type='image/gif'
        )
        cls.group = Group.objects.create(
            title='test-title',
            slug='test-slug',
            description='Тестовое описание',
        )
        cls.post = Post.objects.create(
            author=cls.user,
            text='Тестовый постfasdfasdf',
            group=cls.group,
            image=cls.uploaded
        )

    def setUp(self):
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)
        cache.clear()

    def test_an_authorized_user_can_follow(self):
        """Авторизованный пользователь может
        подписываться на других пользователей.
        """
        follows_count = Follow.objects.count()
        test_user = User.objects.create_user(username='pypa')
        self.authorized_client.get(
            reverse('posts:profile_follow', args=(test_user.username,)),
            follow=True)
        self.assertEqual(Follow.objects.count(), follows_count + 1)

    def test_an_authorized_user_can_unfollow(self):
        """Авторизованный пользователь может
        отписываться от других пользователей.
        """
        test_user = User.objects.create_user(username='pypa')
        Follow.objects.create(user=self.user,
                              author=test_user)
        follows_count = Follow.objects.count()
        self.authorized_client.get(
            reverse('posts:profile_unfollow', args=(test_user.username,)),
        )
        self.assertEqual(Follow.objects.count(), follows_count - 1)

    def test_new_user_record_appears_in_subscribers(self):
        """Новая запись пользователя появляется в
            ленте тех, кто на него подписан.
        """
        test_user = User.objects.create_user(username='pypa')
        Follow.objects.create(user=self.user,
                              author=test_user)
        post = Post.objects.create(
            author=test_user,
            text='perfect'
        )
        self.authorized_client.get(
            reverse('posts:profile_follow', args=(test_user.username,)),
            follow=True)
        response = self.authorized_client.get(
            reverse('posts:follow_index')
        )
        content_index = response.context['page_obj'][0]
        self.assertEqual(post, content_index)

    def test_new_user_does_not_appear_in_subscribers(self):
        """Новая запись пользователя не появляется
        в ленте тех, кто не подписан."""
        test_user = User.objects.create_user(username='мира')
        post = Post.objects.create(
            author=test_user,
            text='perfecto'
        )
        response = self.authorized_client.get(
            reverse('posts:follow_index')
        )
        posts_all = response.context['page_obj']
        self.assertNotIn(post, posts_all)

class PaginatorViewsTest(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='auth')
        cls.group = Group.objects.create(
            title='test-title',
            slug='test-slug',
            description='Тестовое описание',
        )
        cls.posts_count = randint(
            settings.NUMBER_OF_POSTED + 1, settings.NUMBER_OF_POSTED * 2)

        Post.objects.bulk_create([Post(
            author=cls.user,
            text='Тестовый постfasdfasdf',
            group=cls.group)
            for _ in range(cls.posts_count)])

    def test_page_contains_ten_records(self):
        """тестирование паджинатора 1-2 стр"""
        pages = {
            '?page=1': settings.NUMBER_OF_POSTED,
            '?page=2': self.posts_count - settings.NUMBER_OF_POSTED
        }
        for address, counts in pages.items():
            with self.subTest(address=address):
                response = self.client.get(reverse('posts:index') + address)
        self.assertEqual(len(response.context.get(
            'page_obj').object_list), counts)

class CacheTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user(username='auth')
        cls.group = Group.objects.create(
            title='test-title',
            slug='test-slug',
            description='Тестовое описание',
        )

    def test_cache_home_page(self):
        """Тестирование кэша."""
        response = self.client.get(reverse('posts:index'))
        Post.objects.create(
            text='Тестовый пост',
            author=self.user,
        )
        response_two = self.client.get(reverse('posts:index'))
        self.assertEqual(response.content, response_two.content)
        cache.clear()
        response_three = self.client.get(reverse('posts:index'))
        self.assertNotEqual(response_two.content, response_three.content)


# -*- coding: utf-8 -*-
import numpy as np
import scipy.integrate as sci
import scipy.optimize as opt
import time
import tarfile
import os
import csv
import argparse
from montagn import *
import gui_getoption
from sys import argv, exit

#from IPython import parallel
#import thread
from multiprocessing import Pool
#from multiprocessing import Process

def usemontagn(liste):
    #filename="test_"+str(int(n))

    #Translation of the list params
    n=liste[0]
    ask_in=liste[1]
    usemodel_in=liste[2]
    add_in=liste[3]
    usethermal_in=liste[4]
    nphot_in=liste[5]
    filename_in=liste[6]
    nscattmax_in=liste[7]
    modelmont_in=liste[8]
    display_in=liste[9]
    cluster_in=liste[10]
    thetaobs_in=liste[11]
    dthetaobs_in=liste[12]
    path_in=liste[13]
    cmap_in=liste[14]
    force_wvl_in=liste[15]
    paramfile_in=liste[16]

    #adapting the filenames for multpile runs
    if(n<10):
        number='00'+str(int(n))
    elif(n<100) :
        number='0'+str(int(n))
    else:
        number=str(int(n))
    if(filename_in is None):
        filename="test_"+number
    else:
        filename=filename_in+'_'+number

    #managing the ask, paramfile and usemodel parameters
    ask=0 #ask unavailable in parallel launch
    if(paramfile_in=='void' or paramfile_in=='None' or paramfile_in==None):
        if(usemodel_in==None):
            print('No paramfile or model specified')
            print('Using model 0')
            ask=0
            usemodel=0
        else:
            usemodel=float(usemodel_in)
            ask=0
    else:
        usemodel=None

    #Setting defaults values if none
    if(add_in==None):
        add=0
    else:
        add=int(add_in)
    if(usethermal_in==None):
        usethermal=0
    else:
        usethermal=int(usethermal_in)
    if(nphot_in==None):
        print('No photon number given')
        print('launching 100 packets')
        nphot=100
    else:
        nphot=int(nphot_in)
    if(nscattmax_in==None):
        nscattmax=50
    else:
        nscattmax=int(nscattmax_in)
    modelmont=[] #no model already computed usable
    if(display_in==None):
        display=0 #No display available
    else:
        display=int(display_in)
    if(cluster_in==None):
        cluster=0
    else:
        cluster=int(cluster_in)
    #if(thetaobs : unused keyword)
    #if(sthetaobs : unused keyword)
    if(path_in==None):
        path=''
    else:
        path=path_in
    if(display_in==1):
        if(cmap_in==None):
            cmap=[] #No cmap available because no display
    else:
        cmap=[]
    if(force_wvl_in==None or force_wvl_in=='None' or force_wvl_in=='none'):
        force_wvl=[]
    else:
        if(float(force_wvl_in)<1e-9):
            force_wvl=[]
        else:
            force_wvl=float(force_wvl_in)
    if(paramfile_in=='void' or paramfile_in==None):
        paramfile=[]
    else:
        paramfile=paramfile_in

    #Launching
    #model=montAGN(ask=int(liste[1]),usemodel=float(liste[2]),add=int(liste[3]),usethermal=int(liste[4]),nphot=int(liste[5]),filename=filename,ndiffmax=int(liste[7]),display=int(liste[9]),cluster=int(liste[10]),path=path,force_wvl=liste[15],paramfile=paramfile,nsimu=int(n))
    model=montAGN(ask=ask,usemodel=usemodel,add=add,usethermal=usethermal,nphot=nphot,filename=filename,nscattmax=nscattmax,display=display,cluster=cluster,path=path,force_wvl=force_wvl,paramfile=paramfile,nsimu=int(n))

def main():

    # initialisation
    sc = gui_getoption.getoption(opt='wes', optval='r', param=['add','display','cluster'], paramval=['usemodel','nphot','filename','nscattmax','nlaunch','thetaobs','dthetaobs','cmap','force_wvl','paramfile','ask','usethermal','path'], man='This is the manual page. Thanks you for using getoption')

    # appel de la commande
    sc(argv)

    # test option de commande
    if sc['r'] is not None: print("r option was given")

    if 'h' in sc.optkey:
        print(sc.man)
        #exit()

    #for tycho usage
    if(sc['cluster']==1):
        #n=os.getenv("i")
        if(sc['nlaunch'] is None):
            n=1
        else:
            n=int(sc['nlaunch'])
        if(n is None): n=1
        liste=[n,sc['ask'],sc['usemodel'],sc['add'],sc['usethermal'],sc['nphot'],sc['filename'],sc['nscattmax'],sc['modelmont'],sc['display'],sc['cluster'],sc['thetaobs'],sc['dthetaobs'],sc['path'],sc['cmap'],sc['force_wvl'],sc['paramfile']]
        #print liste
        usemontagn(liste)

        #for normal usage
    else:
        if(sc['nlaunch'] is None):
            n=1
        else:
            n=int(sc['nlaunch'])
        #name=np.linspace(1,n,n)
        liste=[]
        for i in range(n):
            liste.append([i+1,sc['ask'],sc['usemodel'],sc['add'],sc['usethermal'],sc['nphot'],sc['filename'],sc['nscattmax'],sc['modelmont'],sc['display'],sc['cluster'],sc['thetaobs'],sc['dthetaobs'],sc['path'],sc['cmap'],sc['force_wvl'],sc['paramfile']])

        #print liste
        #Pool(n).map(usemontagn,name)
        if(n>1):
            Pool(n).map(usemontagn,liste)
        else:
            liste=['1',sc['ask'],sc['usemodel'],sc['add'],sc['usethermal'],sc['nphot'],sc['filename'],sc['nscattmax'],sc['modelmont'],sc['display'],sc['cluster'],sc['thetaobs'],sc['dthetaobs'],sc['path'],sc['cmap'],sc['force_wvl'],sc['paramfile']]
            usemontagn(liste)
        #Pool(n).apply_async(usemontagn[,scriptcall])

if __name__ == '__main__':

    main()


import Signal_Processing
import numpy as np
import matplotlib.pyplot as plt

# Create Single class
SP1 = Signal_Processing.Sig_Proc('192.168.10.10',5005)
# Testing values
N = 1024
T = 1.0/800.0
x = np.linspace(0.0,N*T,N)
y = np.sin(50.0*2.0*np.pi*x)

# Fucntion Calls
SP1.stream_data = y #sample data
SP1.run()
print(np.angle(SP1.fft_data[0],deg=1))
print(np.angle(SP1.fft_data[1],deg=1))
print(np.angle(SP1.fft_data[2],deg=1))
print(np.angle(SP1.fft_data[3],deg=1))
print(np.angle(SP1.fft_data[4],deg=1))
print(np.angle(SP1.fft_data[5],deg=1))
# Plot results
freq = np.linspace(-0.5, 0.5, 1024)
plt.plot(freq, SP1.fft_data)
plt.axis([-0.5, 0.5, -50, 100])
plt.title("Frequency response of the Hanning window")
plt.ylabel("Normalized magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.show()