import matplotlib.pyplot as plt
import pandas as pd
import random
import simpy
import math
import numpy as np
np.set_printoptions(precision=4)
np.set_printoptions(suppress=True)

pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)

#def PrintCustomers(customers):
#    print("%s    %s      %s     %s     %s     %s" % ("name", "timeOfArrival", "waitTime", "startTime", "serviceTime", "departureTime"))
#    for customer in customers:
#        customer.Print()

def CustomersToArray(customers):
    arr = np.empty([0,6])
    for customer in customers:
        row = np.array([customer.name, customer.timeOfArrival, customer.waitTime, customer.startTime, customer.serviceTime, customer.departureTime])
        arr = np.vstack((arr,row))
    return arr

def ArrayToDataFrame(arr):
    return pd.DataFrame(arr, columns=["id","timeOfArrival","waitTime","startTime","serviceTime","departureTime"])

def CustomersToDataFrame(customers):
    arr = CustomersToArray(customers)
    df = ArrayToDataFrame(arr)
    return df

class Customer():
    def __init__(self, simu, name, timeOfArrival, waitTime, startTime, serviceTime, departureTime):
        self.simu = simu
        self.name = name
        self.timeOfArrival = timeOfArrival
        self.waitTime = waitTime
        self.startTime = startTime
        self.serviceTime = serviceTime
        self.departureTime = departureTime

    def Arrival(self, env):
        with self.simu.servers.request() as request:
            yield request
            yield env.process(self.simu.Serve(self))

    #def Print(self):
    #    print("%s          %8.4f      %8.4f      %8.4f        %8.4f          %8.4f" % (self.name, self.timeOfArrival, self.waitTime, self.startTime, self.serviceTime, self.departureTime))

class Simu:
    def __init__(self, numServers, serviceTime, arrivalTime, duration):
        self.numServers = numServers          # Number of agents taking chats
        self.serviceTime = serviceTime         # AHT (Average Handle Time = Number of seconds it takes to help a customer, once the chat has begun)
        self.arrivalTime = arrivalTime         # AAT (Average Arrival Time = Number of seconds between customer's arrivals)
        self.duration = duration           # Simulation time in Seconds

        self.queueSize = 0
        self.customers = []
        self.statesQueueSize = []

        # Create an environment and start the Queue process
        self.env = simpy.Environment()
        self.servers = simpy.Resource(self.env, self.numServers)

        self.env.process(self.State())
        self.env.process(self.Queue())

    def RunSimu(self):
        self.env.run(until=self.duration)

    def State(self):
        while True:
            self.statesQueueSize.append(self.queueSize)
            yield self.env.timeout(1)

    def Queue(self):
        i = 0

        #Create more customers while the simulation is running
        while True:
            arrivalTime = random.expovariate(1.0/self.arrivalTime)
            yield self.env.timeout(arrivalTime)
            i += 1
            customer = Customer(self, name=i, timeOfArrival=self.env.now, waitTime=None, startTime=None, serviceTime=None, departureTime=None)
            self.queueSize += 1
            self.env.process(customer.Arrival(self.env))

    def Serve(self, customer):
        customer.waitTime = self.env.now - customer.timeOfArrival
        customer.startTime = self.env.now

        #customer.serviceTime = random.normalvariate(self.serviceTime,)
        #customer.serviceTime = random.expovariate(1.0/self.serviceTime)

        mu = self.serviceTime
        std = 553.867816
        mu2 = math.log(mu)-0.5*math.log(math.pow(std/mu,2)+1)
        std2 = 0.716256793
        customer.serviceTime = random.lognormvariate(mu2,std2)
        yield self.env.timeout(customer.serviceTime)

        self.queueSize -= 1

        customer.departureTime = self.env.now
        self.customers.append(customer)

    def PrintResults(self):
        #print("")

        df = CustomersToDataFrame(self.customers)
        #print(df)

        #print(hist)

# Model Variables
NumberOfAgents = 5
#ServiceTime = 676.5
ServiceTime = 676.5
ArrivalTime = 115
Duration = 3600
NumberOfSimulations = 1

figA, (axA0, axA1, axA2) = plt.subplots(nrows=3, ncols=1) # two axes on figure
figA.set_figheight=12

# RunSimulations
simulations = []
for i in range(NumberOfSimulations):
    sim = Simu(NumberOfAgents, ServiceTime, ArrivalTime, Duration)
    sim.RunSimu()
    simulations.append(sim)

# Get Summary Data
i = 0
custArr = np.empty([0,7])
queueSizeArr = np.empty([Duration,0])
for x in simulations:
    custArr_u = CustomersToArray(x.customers)
    custArr = np.vstack((custArr,np.hstack((np.array(np.zeros(len(x.customers))+i)[np.newaxis].T, custArr_u))))
    queueSizeArr = np.hstack((queueSizeArr, np.asarray(x.statesQueueSize)[np.newaxis].T))

    custData = pd.DataFrame(custArr_u, columns=["custId","timeOfArrival","waitTime","startTime","serviceTime","departureTime"])

    axA0.set_title('Histogram of Waittimes')
    bins = [x/2 for x in range(0,100,1)]
    axA0.hist(custData['waitTime'], bins=bins, density=True, alpha=0.5)
    axA1.set_title('Queue Size by Time')
    axA1.plot(x.statesQueueSize)

    i += 1

customerData = pd.DataFrame(custArr, columns=["simId","custId","timeOfArrival","waitTime","startTime","serviceTime","departureTime"])
print(customerData.describe())

queueSizeData = pd.DataFrame(queueSizeArr)
print(queueSizeData.describe())

#print(customerData)

# Get Average Queue Sizes by State
tmp = np.zeros([Duration,1])
for i in range(0,len(tmp)):
    tmp[i] = sum(queueSizeArr[i])/len(queueSizeArr[i])

axA2.set_title('Average Queue Size')
axA2.plot(tmp, marker='o')


from pathlib import Path
import subprocess
import platform

import librosa
from matplotlib import pyplot as plt
from pydub import AudioSegment

from common.io import get_dir, get_file_name, get_dir_file_name

def read_wav_data(wav_filepath):
    return librosa.load(wav_filepath)

def get_ffmpeg_executable_filepath():
    if platform.system() == 'Windows':
        ffmpeg_path_bytes = subprocess.check_output("where ffmpeg", shell=True)  # returns bytes
    elif platform.system() == 'Linux':
        ffmpeg_path_bytes = subprocess.check_output("which ffmpeg", shell=True)
    ffmpeg_executable_path = ffmpeg_path_bytes.decode().strip()
    return ffmpeg_executable_path

def invoke_ffmpeg(command):
    ffmpeg_executable_path = get_ffmpeg_executable_filepath()
    print("ffmpeg_executable_path: ", ffmpeg_executable_path)
    cmd_command = f"{ffmpeg_executable_path} {command}"
    returned_value = subprocess.call(
        cmd_command, shell=True
    )  # returns the exit code in unix
    print("returned value:", returned_value)
    return returned_value

def convert_wav_to_mp4(mp3_filepath, mp4_filepath, image_filepath=None):
    if image_filepath is None:
        dir = get_dir(mp4_filepath)
        filename = get_file_name(mp4_filepath)
        image_filepath = f"{dir}/{filename}.png"
        waveform, sample_rate = read_wav_data(mp3_filepath)
        save_waveform_to_image(waveform, sample_rate, image_filepath)

    # ffmpeg_command = f"-loop 1 -i {image_filepath} -i {mp3_filepath} -c:a copy -c:v libx264 -shortest {mp4_filepath}"
    ffmpeg_command = f"-loop 1 -i {image_filepath} -i {mp3_filepath} -c:a aac -b:a 160k -c:v libx264 -shortest {mp4_filepath}"
    return invoke_ffmpeg(ffmpeg_command)

def save_waveform_to_image(waveform, sample_rate, image_filepath, text=''):
    """
    Args:
        waveform: Input signal
        sample_rate: Sampling rate of x
        text: Text to print
    """
    # print('%s Fs = %d, x.shape = %s, x.dtype = %s' % (text, sample_rate, waveform.shape, waveform.dtype))
    plt.figure(figsize=(8, 2))
    plt.plot(waveform, color='gray')
    plt.title(f'Original waveform sr={sample_rate}')
    plt.xlim([0, waveform.shape[0]])
    plt.xlabel('Time (samples)')
    plt.ylabel('Amplitude')
    plt.tight_layout()
    # plt.show()
    # import IPython.display as ipd
    # ipd.display(ipd.Audio(data=waveform, rate=sample_rate))
    plt.savefig(image_filepath)


import sys
import os
from numpy import allclose
import pytest
import warnings

import lxmls.classifiers.gaussian_naive_bayes as gnbc
import lxmls.classifiers.max_ent_batch as mebc
import lxmls.classifiers.max_ent_online as meoc
import lxmls.classifiers.mira as mirac
import lxmls.classifiers.perceptron as percc
import lxmls.classifiers.svm as svmc
import lxmls.readers.sentiment_reader as srs
import lxmls.readers.simple_data_set as sds
from lxmls.classifiers import multinomial_naive_bayes as mnbb

tolerance = 1e-5

@pytest.fixture(scope='module')
def scr():
    return srs.SentimentCorpus("books")

# Exercise 1.1
def test_naive_bayes(scr):
    mnb = mnbb.MultinomialNaiveBayes()

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        # In this exercise, python should yield the following warning:
        # RuntimeWarning: divide by zero encountered in log
        params_nb_sc = mnb.train(scr.train_X,scr.train_y)
        # TODO: make a test to check if the warning was issued

    y_pred_train = mnb.test(scr.train_X,params_nb_sc)
    acc_train = mnb.evaluate(scr.train_y, y_pred_train)
    assert allclose(acc_train, 0.987500, tolerance)

    y_pred_test = mnb.test(scr.test_X,params_nb_sc)
    acc_test = mnb.evaluate(scr.test_y, y_pred_test)
    assert allclose(acc_test, 0.635000, tolerance)

@pytest.fixture(scope='module')
def sd():
    return sds.SimpleDataSet(
        nr_examples=100,
        g1=[[-1,-1],1],
        g2=[[1,1],1],
        balance=0.5,
        split=[0.5,0,0.5]
    )

# Exercise 1.2
def test_perceptron(sd):
    perc = percc.Perceptron()
    params_perc_sd = perc.train(sd.train_X,sd.train_y)

    y_pred_train = perc.test(sd.train_X,params_perc_sd)
    acc_train = perc.evaluate(sd.train_y, y_pred_train)
    assert allclose(acc_train, 0.960000, tolerance)

    y_pred_test = perc.test(sd.test_X,params_perc_sd)
    acc_test = perc.evaluate(sd.test_y, y_pred_test)
    assert allclose(acc_test, 0.960000, tolerance)

# Exercise 1.3
def test_mira(sd):
    mira = mirac.Mira()
    mira.regularizer = 1.0 # This is lambda
    params_mira_sd = mira.train(sd.train_X,sd.train_y)

    y_pred_train = mira.test(sd.train_X,params_mira_sd)
    acc_train = mira.evaluate(sd.train_y, y_pred_train)
    assert allclose(acc_train, 1.000000, tolerance)

    y_pred_test = mira.test(sd.test_X,params_mira_sd)
    acc_test = mira.evaluate(sd.test_y, y_pred_test)
    assert allclose(acc_test, 0.960000, tolerance)

# Exercise 1.4
def test_maxent_batch(sd, scr):
    me_lbfgs = mebc.MaxEntBatch()

    params_meb_sd = me_lbfgs.train(sd.train_X, sd.train_y)
    y_pred_train = me_lbfgs.test(sd.train_X, params_meb_sd)
    acc_train = me_lbfgs.evaluate(sd.train_y, y_pred_train)
    assert allclose(acc_train, 0.980000, tolerance)

    y_pred_test = me_lbfgs.test(sd.test_X, params_meb_sd)
    acc_test = me_lbfgs.evaluate(sd.test_y, y_pred_test)
    assert allclose(acc_test, 0.960000, tolerance)

    params_meb_sc = me_lbfgs.train(scr.train_X,scr.train_y)
    y_pred_train = me_lbfgs.test(scr.train_X,params_meb_sc)
    acc_train = me_lbfgs.evaluate(scr.train_y, y_pred_train)
    assert allclose(acc_train, 0.858125, tolerance)

    y_pred_test = me_lbfgs.test(scr.test_X,params_meb_sc)
    acc_test = me_lbfgs.evaluate(scr.test_y, y_pred_test)
    assert allclose(acc_test, 0.790000, tolerance)

def test_maxent_online(scr):
    me_sgd = meoc.MaxEntOnline()
    me_sgd.regularizer = 1.0
    params_meo_sc = me_sgd.train(scr.train_X,scr.train_y)

    y_pred_train = me_sgd.test(scr.train_X,params_meo_sc)
    acc_train = me_sgd.evaluate(scr.train_y, y_pred_train)
    assert allclose(acc_train, 0.860000, tolerance)

    y_pred_test = me_sgd.test(scr.test_X,params_meo_sc)
    acc_test = me_sgd.evaluate(scr.test_y, y_pred_test)
    assert allclose(acc_test, 0.795000, tolerance)

# Exercise 1.5
def test_svm_online(sd, scr):
    svm = svmc.SVM()
    svm.regularizer = 1.0 # This is lambda
    params_svm_sd = svm.train(sd.train_X,sd.train_y)

    y_pred_train = svm.test(sd.train_X,params_svm_sd)
    acc_train = svm.evaluate(sd.train_y, y_pred_train)
    assert allclose(acc_train, 0.940000, tolerance)

    y_pred_test = svm.test(sd.test_X,params_svm_sd)
    acc_test = svm.evaluate(sd.test_y, y_pred_test)
    assert allclose(acc_test, 0.960000, tolerance)

    params_svm_sc = svm.train(scr.train_X,scr.train_y)

    y_pred_train = svm.test(scr.train_X,params_svm_sc)
    acc_train = svm.evaluate(scr.train_y, y_pred_train)
    assert allclose(acc_train, 0.87875, 0.01)

    y_pred_test = svm.test(scr.test_X,params_svm_sc)
    acc_test = svm.evaluate(scr.test_y, y_pred_test)
    # TODO: py2 gives 0.805, check the reason for the different value
    assert allclose(acc_test, 0.810000, 0.01)

if __name__ == '__main__':
    pytest.main([__file__])


import collections

class FirstNonDup(object):
    def __init__(self, *args, **kwargs):
        self.dq = collections.deque()
        self.cnt = collections.Counter()
        return super().__init__(*args, **kwargs)

    def income(self, val):
        self.cnt[val] += 1
        self.dq.append(val)
        while self.dq and self.cnt[self.dq[0]] >= 2:
            self.dq.popleft()
        print(self.dq)
        if self.dq:
            return self.dq[0]
        else:
            return None

fnd = FirstNonDup()
for val in [0, 1, 0, 3, 1, 4, 5]:
    print(fnd.income(val))


from PIL.Image import new
from db import db
from db import User
from db import Clothes
from db import Clothing_Image
from flask import Flask
from flask import request
import requests
import json
import os

app = Flask(__name__)
db_filename = "fashion.db"

app.config["SQLALCHEMY_DABASE_URI"] = "sqlite:///%s" % db_filename
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ECHO"] = True

db.init_app(app)
with app.app_context():
    db.create_all()

def success_response(data, code=200):
    return json.dumps({"success": True, "data": data}), code

def failure_response(message, code=404):
    return json.dumps({"success": False, "error": message}), code

@app.route("/")
def get_default_weather():
    response = requests.get("http://api.openweathermap.org/data/2.5/weather?zip=14853,us&appid=de52b0de5733de9964224287de84c5e6&units=metric")
    return success_response(response.json())

@app.route("/user/", methods=['POST'])
def create_user():
    body = json.loads(request.data)
    new_user = User(
        name = body.get('name'),
        location = body.get('location')
    )
    if not new_user.name:
        return failure_response("Name not provided", 400)
    if not new_user.location:
        return failure_response("Zip Code not provided", 400)
    if new_user.location < 10000:
        return failure_response("Zip Code not valid", 400)
    db.session.add(new_user)
    db.session.commit()
    return success_response(new_user.serialize(), 201)

@app.route("/user/<int:userid>/")
def get_specific_user(userid):
    user = User.query.filter_by(id=userid).first()
    if user is None:
        return failure_response("User does not exist")
    return success_response(user.serialize())

@app.route("/<int:userid>/clothing/", methods=['POST'])
def upload_clothing(userid):
    user = User.query.filter_by(id=userid).first()
    if user is None:
        return failure_response("User does not exist")
    body = json.loads(request.data)
    new_clothes = Clothes(
        name = body.get('name'),
        warmth = body.get('warmth'),
        typeOfClothes = body.get('typeOfClothes'),
        user_id = userid
    )
    if not new_clothes.name:
        return failure_response("Name of clothing not provided", 400)
    if not new_clothes.warmth:
        return failure_response("Warmth level of clothing not provided", 400)
    if not new_clothes.typeOfClothes:
        return failure_response("Type of clothing not provided", 400)
    if new_clothes.warmth < 0 or new_clothes.warmth > 10:
        return failure_response("Warmth level must be within the range of 1-10", 400)
    if new_clothes.typeOfClothes != "top" and new_clothes.typeOfClothes != "bottom" and new_clothes.typeOfClothes != "shoes" and new_clothes.typeOfClothes != "jacket":
        return failure_response("Not a valid entry for type of clothing", 400)
    db.session.add(new_clothes)
    db.session.commit()
    return success_response(new_clothes.serialize(), 201)

@app.route("/<int:clothingid>/picture/", methods=['POST'])
def upload_clothing_picture(clothingid):
    clothes = Clothes.query.filter_by(id=clothingid).first()
    if clothes is None:
        return failure_response("Clothing does not exist")
    body = json.loads(request.data)
    image_data = body.get('image_data')
    if image_data is None:
        return failure_response("Image not provided", 400)
    clothing_image = Clothing_Image(image_data = image_data, description_id=clothingid)
    db.session.add(clothing_image)
    db.session.commit()
    return success_response(clothing_image.serialize(), 201)

@app.route("/<int:userid>/clothing/")
def get_clothes(userid):
    user = User.query.filter_by(id=userid).first()
    if user is None:
        return failure_response("User does not exist")
    clothes = {"clothes": [t.serialize() for t in Clothes.query.filter_by(user_id=userid)]}
    return success_response(clothes)

@app.route("/<int:userid>/weather/")
def get_weather(userid):
    user = User.query.filter_by(id=userid).first()
    if user is None:
        return failure_response("User does not exist")
    response = requests.get("http://api.openweathermap.org/data/2.5/weather?zip={},us&appid=de52b0de5733de9964224287de84c5e6&units=metric".format(user.location))
    return success_response(response.json())

@app.route("/<int:userid>/<string:type>/select/")
def select_clothes(userid, type):
    user = User.query.filter_by(id=userid).first()
    if user is None:
        return failure_response("User does not exist")
    if type != "top" and type != "bottom" and type != "shoes" and type != "jacket":
        return failure_response("Not a valid entry for type of clothing", 400)
    response = requests.get("http://api.openweathermap.org/data/2.5/weather?zip={},us&appid=de52b0de5733de9964224287de84c5e6&units=metric".format(user.location))
    response = json.loads(json.dumps(response.json()))
    temp = response.get('main')
    temperature = int(temp.get('temp'))
    if temperature > 30:
        clothing = Clothes.query.filter_by(user_id=userid).filter(Clothes.warmth<3, Clothes.typeOfClothes == type).first()
        if clothing is None:
            clothing = Clothes.query.filter_by(user_id=userid).filter(Clothes.typeOfClothes == type).order_by(Clothes.warmth.asc).first()
    elif temperature > 20:
        clothing = Clothes.query.filter_by(user_id=userid).filter(Clothes.warmth>=3, Clothes.warmth<5, Clothes.typeOfClothes == type).first()
        if clothing is None:
            clothing = Clothes.query.filter_by(user_id=userid).filter(Clothes.typeOfClothes == type).first()
    elif temperature > 10:
        clothing = Clothes.query.filter_by(user_id=userid).filter(Clothes.warmth>=5, Clothes.warmth<8, Clothes.typeOfClothes == type).first()
        if clothing is None:
            clothing = Clothes.query.filter_by(user_id=userid).filter(Clothes.typeOfClothes == type).first()
    else:
        clothing = Clothes.query.filter_by(user_id=userid).filter(Clothes.warmth>=8, Clothes.typeOfClothes == type).first()
        if clothing is None:
            clothing = Clothes.query.filter_by(user_id=userid).filter(Clothes.typeOfClothes == type).order_by(Clothes.warmth.desc).first()
    if clothing is None:
        return failure_response("No clothes of the clothing type", 400)
    return success_response(clothing.serialize())

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host="0.0.0.0", port=port)


from torchvision import models
import torch.nn as nn
import torch.utils.model_zoo as model_zoo

model_urls = {
    'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}

# let us customize a bit our alexnet

class CustomAlexNet(models.AlexNet):

    def __init__(self, pretrained = True):
        super(CustomAlexNet, self).__init__()
        if pretrained:
            self.load_state_dict(model_zoo.load_url(model_urls['alexnet']))

        # disable training for feature detection (be carefull not to give every parameteres to optimize to the optimizer)
        for parameter in self.features.parameters():
            parameter.requires_grad = False

        # custom classifier
        self.classifier = nn.Sequential(
                    nn.Dropout(),
                    nn.Linear(256 * 3 * 3, 4096),
                    nn.ReLU(inplace=True),
                    nn.Dropout(),
                    nn.Linear(4096, 1024),
                    nn.ReLU(inplace=True),
                    nn.Linear(1024, 1), # output is just true or false
                    nn.Sigmoid()
                )

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), 256 * 3 * 3)
        x = self.classifier(x)
        return x.squeeze()

    # parameters to tune (excluding features here)
    def to_tune(self):
        return self.classifier


from logic.count_polinomic_words import count_polinoms
from string_func.split import split

def main():
    string = input("Enter a string: ")
    print('Number of polinomic words in string:', count_polinoms(split(string, ' ')))

if __name__ == '__main__':
    main()


from random import randint
import pdb

def limits(n, min, max):
    n_min = n - 1
    n_max = n + 2
    if n_min < min:
        n_min = n
    if n_max > max:
        n_max = n + 1
    return n_min, n_max

def show(table):
    print()
    for line in table:
        for item in line:
            print(item.proximidade, item.bomba, item.reveal, end=" ")
        print()
    print()

class Tabuleiro():

    class Celula():

        def __init__(self, linha, coluna):
            self.linha = linha
            self.coluna = coluna
            self.bomba = False
            self.proximidade = 0
            self.reveal = False
            self.marked = False

    def __init__(self, linha=0, coluna=0, num_bombs=5, txt=None):
        if txt is None:
            self.linha = linha
            self.coluna = coluna
            self.blank = linha*coluna
            self.num_bombs = num_bombs
            self.num_marks = 0
            self.right_marks = 0
            self.objetive = num_bombs
            self._create_tabuleiro()
        else:
            try:
                with open(txt, mode="r") as teste:
                    pass
            except Exception:
                txt = '/home/peter03/PythonWebPage/' + txt
            with open(txt, mode='r') as jogo:
                file = jogo.read().splitlines()
                self.linha = int(file.pop(0))
                self.coluna = int(file.pop(0))
                self.blank = int(file.pop(0))
                self.num_bombs = int(file.pop(0))
                self.num_marks = int(file.pop(0))
                self.right_marks = int(file.pop(0))
                self.objetive = int(file.pop(0))
                self.tabuleiro = []
                file.remove("")
                for idx_linha, linha in enumerate(file):
                    content = linha.split(";")
                    content.remove("")
                    lin = []
                    for idx_coluna, celula in enumerate(content):
                        cel = self.Celula(idx_linha, idx_coluna)
                        item = celula.split(',')
                        cel.bomba = True if item[0] == 'True' else False
                        cel.proximidade = int(item[1])
                        cel.reveal = True if item[2] == 'True' else False
                        cel.marked = True if item[3] == 'True' else False
                        lin.append(cel)
                    self.tabuleiro.append(lin)

    def _create_tabuleiro(self):
        self.tabuleiro = []
        for lin in range(self.linha):
            tab = [self.Celula(lin, n) for n in range(self.coluna)]
            self.tabuleiro.append(tab)

    def _count_mines(self):
        for j in range(self.linha):
            for k in range(self.coluna):
                if not self.tabuleiro[j][k].bomba:
                    j_min, j_max = limits(j, 0, self.linha)
                    k_min, k_max = limits(k, 0, self.coluna)
                    for line in range(j_min, j_max):
                        for col in range(k_min, k_max):
                            if self.tabuleiro[line][col].bomba:
                                self.tabuleiro[j][k].proximidade += 1

    def reveal(self, line, col):
        if self.num_bombs > 0:
            self.first_bomb(line, col)
            return False, False

        celula = self.tabuleiro[line][col]

        if celula.bomba:
            self.tabuleiro[line][col].reveal = True
            for idx_l, l in enumerate(self.tabuleiro):
                for idx_j,  j in enumerate(l):
                    if j.bomba:
                        self.tabuleiro[idx_l][idx_j].reveal = True
            return False, True

        elif not celula.reveal:
            if celula.marked:
                self.mark(line, col)
            self.tabuleiro[line][col].reveal = True
            if celula.proximidade == 0:
                j_min, j_max = limits(line, 0, self.linha)
                k_min, k_max = limits(col, 0, self.coluna)
                for j in range(j_min, j_max):
                    for k in range(k_min, k_max):
                        if celula is not self.tabuleiro[j][k]:
                            if not self.tabuleiro[j][k].reveal:
                                self.reveal(j, k)

        self.blank -= 1
        if self.blank == self.objetive:
            return True, False
        else:
            return False, False

    def mark(self, line, col):
        celula = self.tabuleiro[line][col]
        if celula.marked:
            self.tabuleiro[line][col].marked = False
            self.num_marks -= 1
            if celula.bomba:
                self.right_marks -= 1
        else:
            self.tabuleiro[line][col].marked = True
            self.num_marks += 1
            if celula.bomba:
                self.right_marks += 1

        if self.right_marks == self.objetive == self.num_marks:
            return True, False
        else:
            return False, False

    def first_bomb(self, lin, col):
        while True:
            for jay in range(self.linha):
                for k in range(self.coluna):
                    rand = randint(1, (self.linha*self.coluna))
                    if rand == (self.linha*self.coluna):
                        j_min, j_max = limits(lin, 0, self.linha)
                        k_min, k_max = limits(col, 0, self.coluna)
                        if not j_min <= jay < j_max or not k_min <= k < k_max:
                            if not self.tabuleiro[jay][k].bomba:
                                self.tabuleiro[jay][k].bomba = True
                                self.num_bombs -= 1
                                if self.num_bombs == 0:
                                    self._count_mines()
                                    self.reveal(lin, col)
                                    return

    def register_game(self, txt):
        try:
            with open(txt, mode="w") as teste:
                pass
        except Exception:
            txt = '/home/peter03/PythonWebPage/' + txt
        with open(txt, mode="w") as jogo:
            jogo.write(f'{self.linha}\n')
            jogo.write(f'{self.coluna}\n')
            jogo.write(f'{self.blank}\n')
            jogo.write(f'{self.num_bombs}\n')
            jogo.write(f'{self.num_marks}\n')
            jogo.write(f'{self.right_marks}\n')
            jogo.write(f'{self.objetive}\n')

            for l in self.tabuleiro:
                jogo.write('\n')
                for num in l:
                    jogo.write(
                        f'{num.bomba},{num.proximidade},{num.reveal}\
,{num.marked};')

if __name__ == "__main__":
    # jogo = Tabuleiro(txt='database.txt')
    jogo = Tabuleiro(6, 6, 4)
    jogo.first_bomb(2, 2)
    jogo.mark(3, 4)
    # show(jogo.tabuleiro)
    jogo.register_game('database.txt')

    # while True:
    #     x = int(input('x: '))
    #     y = int(input('y: '))
    #     win = jogo.reveal(x, y)
    #     show(jogo.table)
    #     if not win:
    #         print("You lost")
    #         break


import sys
import os
import cv2
# import tools.demo as deploy
import copy
import time
# from cv2 import VideoWriter
import gi
# import share_memory_read as sm

from threading import Thread, Lock
from time import sleep
# import numpy as np

# from utils.plots import Annotator, colors
# from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
#                            increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)

# sys.path.append(os.path.abspath(os.path.join(__file__, "..","..")))
# from Yolov5_StrongSORT_OSNet.track import track as yolov5_track

gi.require_version('Gst', '1.0')

from gi.repository import Gst, GObject, GLib
from numpy import size

file_name = 'output.mp4'
output_dir = './'
# predictor = deploy.build()

#pipe_time = PipeTimer()
warmup_frame = 50

"""
gst-launch-1.0  -v udpsrc port=5001 blocksize=512000 buffer-size=5120000 mtu=51200
 ! 'application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96'
 ! rtph264depay ! 'video/x-h264,stream-format=byte-stream'
 ! h264parse ! avdec_h264 ! videoconvert ! xvimagesink
~
"""

def gstreamer_pipeline_v4l2(
    udp_port=5001,
    display_width=1280,
    display_height=800,
    framerate=15,
    flip_method=0,
):
    return (
        "udpsrc port=%d ! "
        "application/x-rtp,media=video,"
        "clock-rate=90000,encoding-name=H264,payload=96 ! "
        "rtph264depay ! "
        #"video/x-h264,stream-format=byte-stream ! "
        "h264parse ! "
        "nvv4l2decoder ! "
        "nvvidconv ! "
        "video/x-raw, width=%d, height=%d, format=BGRx ! "
        "videoconvert ! appsink"
        % (
            udp_port,
            display_width,
            display_height,
        )
    )

def gstreamer_pipeline(
    udp_port=5000,
    display_width=1280,
    display_height=800,
    framerate=21,
    flip_method=0,
):
    return (
        "udpsrc port=%d blocksize=512000 buffer-size=5120000 mtu=51200 ! "
        "application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96 ! "
        "rtph264depay ! "
        "video/x-h264,stream-format=byte-stream ! "
        "h264parse ! "
        "avdec_h264 ! videoconvert ! xvimagesink "
        # "nvv4l2decoder ! "
        # "nvstreammux batch-size=1 width=1280 height=800 batched-push-timeout=40000 ! "
        # "nvvidconv ! "
        # "video/x-raw, width=%d, height=%d, format=BGRx ! "
        # "videoconvert ! appsink blocksize=51200 "
        % (
            udp_port,
            # display_width,
            # display_height,
        )
    )

def udp_push(image):

    pipeline = 'appsrc ! queue ! h264parse ! nvv4l2decoder ! nvvidconv \
        ! video/x-raw, width=640, height=480 ! nvv4l2h264enc ! rtph264depay \
            ! udpsink host=127.0.0.1 port=6000 sync=false'

    videoOut = VideoWriter()
    videoOut.open(pipeline, 0, 10, size(640,480), True)

    #write = cv2.VideoWriter(pipeline, cv2.CAP_GSTREAMER, 0, 30, 640*480, True)
    #write.write(image)

image_push_state = 0
def predict_video(video_file):

    # video_uri = gstreamer_pipeline(udp_port=5001)

    video_uri = gstreamer_pipeline_v4l2()

    print(video_uri)

    capture = cv2.VideoCapture(video_uri, cv2.CAP_GSTREAMER)

    #capture = cv2.VideoCapture(video_file)
    video_out_name = 'output.mp4' if file_name is None else file_name

    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = int(capture.get(cv2.CAP_PROP_FPS))
    frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))

    print("video fps:%d, frame_count:%d, video_width:%d, video_height:%d"
           % (fps, frame_count, width, height))

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    out_path = os.path.join(output_dir, video_out_name)

    fourcc = cv2.VideoWriter_fourcc(* 'mp4v') #
    writer = cv2.VideoWriter(out_path, fourcc, 30, (width, height))
    #writer = cv2.VideoWriter(out_path, fps, (width, height))

    global frame_id
    frame_id = 0

    total_time = 0

    global udp_pipline
    #udp_pipline = RtpPipeline()

    framecount = 0

    ######################recevie from kcf_ptz##############
    #video_uri_kcf = gstreamer_pipeline_v4l2()

    #capture_kcf = cv2.VideoCapture(video_uri_kcf, cv2.CAP_GSTREAMER)
    ########################################################

    # cmd = sm.receive_cmd()
    # print("starting ------------------->>>>>{},cmd----->>>>{}".format(video_source, cmd))

    lock_push.acquire()
    lock_push_end.acquire()
    # push_thread = Thread(target=push_image_thread, name='push_image', args=(3,))
    # push_thread.start()

    global image_push
    global image_push_state
    global infer_out
    image_push_state = 0

    while(1):
        #old_time = time.time()

        ##########kcf video######
        #video_source = sm.get_video_source()
        # if(video_source == '1'):
        #     ret, frame = capture_kcf.read()
        #     udp_pipline.pip_push(frame)
        #     continue

        #if frame_id % 10 == 0:
        #    print('frame id: ', frame_id)
        ret, frame = capture.read()

        # udp_pipline.pip_push(frame)
        # continue

        if not ret:
            print('capture failed , id: ', frame_id)
            break

        # if(video_source == '1'):
        #     udp_pipline.pip_push(frame)
        #     frame_id += 1
        #     continue

        framecount += 1

        if(framecount == 2):
            framecount = 0
            #continue

        #print("frame count:{}", framecount)

        old_time = time.time()

        #print("cmd is ------------------->>>>>{}".format(cmd))

        cv2.imshow("TTA_DET", frame)

        frame_id += 1

        current_time = time.time()
        fps_time = current_time - old_time
        total_time += fps_time
        print("fps time: " + str(fps_time))

        keyCode = cv2.waitKey(10) & 0xFF
        # Stop the program on the ESC key
        if keyCode == 27:
            break

        time.sleep(0.01)

    print("total time is {}".format(total_time))

class RtpPipeline(object):
    def __init__(self):
        self.number_frames = 0
        self.fps = 30
        #self.cap = cv2.VideoCapture(0)             '! queue ! videoconvert ' \
        self.duration = 1 / self.fps * Gst.SECOND  # duration of a frame in nanoseconds
#! video/x-raw,width=640,height=480
        self.launch_string = 'appsrc name=source is-live=true blocksize=51200 max-bytes=2000000 ' \
            'caps=video/x-raw,format=BGR,width=1280,height=800 ' \
            '! videoconvert ' \
            '! queue ' \
            '! nvvidconv ! video/x-raw(memory:NVMM),width=1080,height=720,format=NV12' \
            '! nvv4l2h264enc preset-level=2 iframeinterval=10 control-rate=1 bitrate=3000000 ' \
            'profile=0 insert-sps-pps=true ! video/x-h264, stream-format=byte-stream ! rtph264pay name=pay0 pt=96 ' \
            '! queue ' \
            '! udpsink host=192.168.10.255 port=6000 sync=false blocksize=51200 buffer-size=512000'

        #'! nvvidconv ! video/x-raw(memory:NVMM),width=1280,height=800,format=NV12,framerate=1/30' \
        #'! nvv4l2h264enc ! video/x-h264,preset-level=0,control-rate=2,bitrate=1000000,' \
        #    'profile=baseline,stream-format=byte-stream ! h264parse ! rtph264pay name=pay0 pt=96 ' \

        #'! nvv4l2h264enc ! rtph264pay name=pay0 pt=96 ' \

        #    '! nvv4l2h264enc profile=4 iframeinterval=30 bitrate=2000000 ! rtph264pay name=pay0 pt=96 ' \
        # self.launch_string = 'appsrc name=source is-live=true ' \
        #     'caps=video/x-raw,format=BGR,width=640,height=480 ' \
        #     '! videoconvert ! video/x-raw,width=640,height=480 ' \
        #     '! x264enc speed-preset=ultrafast tune=zerolatency ! rtph264pay name=pay0 pt=96 ' \
        #     '! udpsink host=192.168.10.255 port=5500 sync=false'
        Gst.init(None)

        Gst.debug_set_default_threshold(2)

        pipeline = Gst.parse_launch(self.launch_string)
        self.appsrc = pipeline.get_child_by_name('source')
        pipeline.set_state(Gst.State.PLAYING)

    def pip_push(self, frame):
        try:
            #ret, frame = self.cap.read()
            start = time.time()
            data = frame.tobytes()
            length = len(data)
            buf = Gst.Buffer.new_allocate(None, length, None)
            buf.fill(0, data)
            buf.duration = self.duration
            timestamp = self.number_frames * self.duration
            buf.pts = buf.dts = int(timestamp)
            buf.offset = timestamp
            self.number_frames += 1
            retval = self.appsrc.emit('push-buffer', buf)
            if retval != Gst.FlowReturn.OK:
                print(retval)
        except Exception as e:
            print("error message----->>{}".format(e))
            return

lock_push = Lock()
lock_push_end = Lock()
infer_out=[]
def push_image_thread(n):
    global image_push
    global udp_pipline
    global frame_id
    global image_push_state
    global infer_out

    while(True):
        push_count = 0
        #if lock_push.acquire():

        if image_push_state == 1:

            outputs, result_image = deploy.predict(predictor, image_push, frame_id)
            print("push image thread image ---------------------{}".format(outputs))
            # if len(outputs) != 0:
            #     print("push infer image!!!!!!!!!!!!!!")
                #udp_pipline.pip_push(result_image)

            infer_out = outputs
            image_push_state = 0

            outputs, result_image=yolov5_track(image_push, outputs)

        time.sleep(0.01)

            #lock_push_end.release()
        #print("push count------------------------------------------------->>>{}".format(push_count))

if __name__ == "__main__":

    predict_video("vtl_output.mp4")


import logging
import numpy as np
import pandas as pd
from patsy import dmatrix

from ..utils import asfactor

def make_design_matrix(counts, batch, group, covar_mod, full_mod, ref_batch):
    """Make design matrix for batch effect correction. Handles covariates as
    well as reference batch.

    Arguments
    ---------
    counts : matrix
        raw count matrix from genomic studies (dimensions gene x sample)
    batch : array or list or :obj:`inmoose.utils.factor.Factor`
        batch indices
    group : array or list or :obj:`inmoose.utils.factor.Factor`
        vector/factor for biological condition of interest
    covar_mod : matrix
        model matrix for multiple covariates to include in linear model (signal
        from these variables are kept in data after adjustment)
    full_mod : bool
        if True, include condition of interest in model
    ref_batch : any
        batch id of the batch to use as reference. Must be one of the element of
        `batch`

    Returns
    -------
    matrix
        the design matrix
    matrix
        the batch-only design matrix (i.e. without covariates)
    matrix
        the covariate-only design matrix (i.e. without batches)
    list of list of int
        for each batch, the indices of the samples of this batch
    list of int
        the size of each batch (in number of samples)
    int
        the number of batches
    int
        the number of samples
    int or None
        the index of the reference batch if any, otherwise None
    """

    # preparation
    batch = asfactor(batch)

    # number of batches
    n_batch = batch.nlevels()
    # list of samples in each batch
    batches_ind = [(batch == batch.categories[i]).nonzero()[0]
                   for i in range(n_batch)]
    n_batches = [len(i) for i in batches_ind]
    n_sample = np.sum(n_batches)
    logging.info(f"Found {n_batch} batches")

    if 1 in n_batches:
        logging.warnings.warn("Single-sample batch detected!")

    # batch
    batchmod = dmatrix("~0 + C(batch)")
    # reference batch
    if ref_batch is not None:
        if ref_batch not in batch.categories:
            raise ValueError("Reference batch must identify one of the batches")
        logging.info(f"Using batch {ref_batch} as reference batch")
        # ref_batch_idx is the index of the reference batch in batch.categories
        ref_batch_idx = np.where(batch.categories == ref_batch)[0][0]
        # update batchmod with reference
        batchmod[:,ref_batch_idx] = 1
    else:
        ref_batch_idx = None

    # covariate
    group = asfactor([] if group is None else group)
    # handle missing covariates, by creating a distinct covariate per batch
    # where a missing covariate appears
    nan_group = group.isna()
    if nan_group.any():
        logging.warnings.warn(f"{nan_group.sum()} missing covariates in group. Creating a distinct covariate per batch for the missing values. You may want to double check your covariates.")
        nan_batch_group = [f"nan_batch_{batch[i]}"
                           for i in range(len(group))
                           if nan_group[i]]
        group = group.add_categories(np.unique(nan_batch_group))
        for i,j in enumerate(np.where(nan_group)[0]):
            group[j] = nan_batch_group[i]

    if full_mod and group.nlevels() > 1:
        logging.info("Using full model")
        mod = dmatrix("~group")
    else:
        logging.info("Using null model")
        mod = dmatrix("~1", pd.DataFrame(counts.T))
    # drop intercept in covariate model
    if covar_mod is not None:
        check = [(covar_mod[:,i] == 1).all() for i in range(covar_mod.shape[1])]
        covar_mod = covar_mod[:, np.logical_not(check)]
        # bind with biological condition of interest
        mod = np.concatenate((mod, covar_mod), axis=1)
    # combine
    design = dmatrix("~ 0 + batchmod + mod")

    # Check for intercept in covariates, and drop if present
    check = [(design[:,i] == 1).all() for i in range(design.shape[1])]
    if ref_batch_idx is not None:
        # the reference batch is not considered as a covariate
        check[ref_batch_idx] = False
    design = design[:, np.logical_not(check)]

    logging.info(f"Adjusting for {design.shape[1] - batchmod.shape[1]} covariate(s) or covariate level(s)")

    # Check if the desigin is confounded
    check_confounded_covariates(design, n_batch)

    return design, batchmod, mod, batches_ind, n_batches, n_batch, n_sample, ref_batch_idx

class ConfoundingVariablesError(Exception):
    """Exception raised when confounding variables are detected.

    Arguments
    ---------
    message : str
        explanation of the error
    """

    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

def check_confounded_covariates(design, n_batch):
    """Detect confounded covariates.
    This function returns nothing, but raises exception if confounded covariates are detected.

    Arguments
    ---------
    design : matrix
        the design matrix
    n_batch : int
        the number of batches
    """

    # if matrix is not invertible, different cases
    if np.linalg.matrix_rank(design) < design.shape[1]:
        if design.shape[1] == n_batch+1: # case 1: covariate confounded with a batch
            raise ConfoundingVariablesError("Covariate is confounded with batch. Try removing the covariates.")
        if design.shape[1] > n_batch+1: # case 2: multiple covariates confounded with a batch
            if np.linalg.matrix_rank(design.T[:n_batch]) < design.shape[1]:
                raise ConfoundingVariablesError("Confounded design. Try removing one or more covariates.")
            else: # case 3: at least one covariate confounded with a batch
                raise ConfoundingVariablesError("At least one covariate is confounded with batch. Try removing confounded covariates.")


import datasets
from itertools import chain
from dataclasses import dataclass

from transformers import LlamaTokenizer

def get_llama_dataset(train_config):
    model_path = train_config.data_dir + "/" + train_config.model_name

    tokenizer = LlamaTokenizer.from_pretrained(model_path)
    tokenizer.add_special_tokens({
        "pad_token": "<PAD>",
    })
    dataset_config = generate_dataset_config()
    path = train_config.data_dir + train_config.dataset_dir
    dataset_train = get_preprocessed_dataset(
        train_config,
        path,
        tokenizer,
        dataset_config,
        split="train",
    )

    dataset_val = get_preprocessed_dataset(
        train_config,
        path,
        tokenizer,
        dataset_config,
        split="test",
    )

    return dataset_train, dataset_val, tokenizer

class Concatenator(object):

    def __init__(self, chunk_size=512):
        self.chunk_size = chunk_size
        self.residual = {"input_ids": [], "attention_mask": []}

    def __call__(self, batch):
        concatenated_samples = {
            k: v + list(chain(*batch[k]))
            for k, v in self.residual.items()
        }

        total_length = len(concatenated_samples[list(
            concatenated_samples.keys())[0]])

        if total_length >= self.chunk_size:
            chunk_num = total_length // self.chunk_size
            result = {
                k: [
                    v[i:i + self.chunk_size]
                    for i in range(0, chunk_num *
                                   self.chunk_size, self.chunk_size)
                ]
                for k, v in concatenated_samples.items()
            }
            self.residual = {
                k: v[(chunk_num * self.chunk_size):]
                for k, v in concatenated_samples.items()
            }
        else:
            result = concatenated_samples
            self.residual = {k: [] for k in concatenated_samples.keys()}

        result["labels"] = result["input_ids"].copy()

        return result

def get_preprocessed_samsum(train_config, path, tokenizer, split):
    # dataset = datasets.load_dataset("samsum", split=split)
    dataset = datasets.load_dataset(path=path, split=split)
    prompt = (
        f"Summarize this dialog:\n{{dialog}}\n---\nSummary:\n{{summary}}{{eos_token}}"
    )

    def apply_prompt_template(sample):
        return {
            "text":
            prompt.format(
                dialog=sample["dialogue"],
                summary=sample["summary"],
                eos_token=tokenizer.eos_token,
            )
        }

    dataset = dataset.map(apply_prompt_template,
                          remove_columns=list(dataset.features))

    dataset = dataset.map(
        lambda sample: tokenizer(sample["text"]),
        batched=True,
        remove_columns=list(dataset.features),
    ).map(Concatenator(chunk_size=train_config.seq_length), batched=True)
    return dataset

@dataclass
class samsum_dataset:
    dataset: str = "samsum_dataset"
    train_split: str = "train"
    test_split: str = "validation"
    input_length: int = 512

def generate_dataset_config():
    dataset_config = samsum_dataset()
    return dataset_config

def get_preprocessed_dataset(
                             train_config,
                             path,
                             tokenizer,
                             dataset_config,
                             split: str = "train"):

    def get_split():
        return (dataset_config.train_split
                if split == "train" else dataset_config.test_split)

    return get_preprocessed_samsum(
        train_config,
        path,
        tokenizer,
        get_split(),
    )


import pandas as pd

# Read in the CSV files
toi = pd.read_csv('https://raw.githubusercontent.com/josephnelson93/dekegeek/master/boshac16/assets/data/20152016_02_total_gp_toi.csv')
cf = pd.read_csv('https://raw.githubusercontent.com/josephnelson93/dekegeek/master/boshac16/assets/data/20152016_02_total_cf.csv')
blocks = pd.read_csv('https://raw.githubusercontent.com/josephnelson93/dekegeek/master/boshac16/assets/data/20152016_02_total_blocks.csv')
hits = pd.read_csv('https://raw.githubusercontent.com/josephnelson93/dekegeek/master/boshac16/assets/data/20152016_02_total_hits.csv')

# Select the columns we want
cf = cf[['comb','corsi_for_5v5','corsi_against_5v5','corsi_5v5','corsi_for',
         'corsi_against','corsi','fenwick_for_5v5','fenwick_against_5v5',
         'fenwick_5v5','fenwick_for','fenwick_against','fenwick']]

blocks = blocks[['comb','blocks','5v5_block','g_block_5_5v5','b_block_5_5v5',
                 'g_block_10_5v5','b_block_10_5v5','g_block_5_ev',
                 'b_block_5_ev','g_block_10_ev','b_block_10_ev',
                 'g_block_5_pp','b_block_5_pp','g_block_10_pp',
                 'b_block_10_pp','g_block_5_sh','b_block_5_sh',
                 'g_block_10_sh','b_block_10_sh']]

hits = hits[['comb','hits','5v5_hits','g_hit_5_5v5','b_hit_5_5v5',
             'g_hit_10_5v5','b_hit_10_5v5','g_hit_5_ev','b_hit_5_ev',
             'g_hit_10_ev','b_hit_10_ev','g_hit_5_pp','b_hit_5_pp',
             'g_hit_10_pp','b_hit_10_pp','g_hit_5_sh','b_hit_5_sh',
             'g_hit_10_sh','b_hit_10_sh']]

# Merge our DataFrames
combined = toi.merge(cf,on='comb',how='outer')
combined = combined.merge(blocks,on='comb',how='outer')
combined = combined.merge(hits,on='comb',how='outer')
# Save the combined DataFrame to CSV
combined.to_csv('/Users/Brian/dekegeek/boshac16/assets/data/20152016_02_total_merged.csv',index=False)

combined
combined = combined.ix[combined.pos != 'G']

def convert_to_60(time):
    mins = int(time.split(':')[0])
    secs = int(time.split(':')[1])
    secs = secs/60.0
    converted_mins = mins + secs
    return converted_mins/60.0

# Convert our TOI columns to number of 60 minutes intervals
combined['TOI'] = combined['TOI'].apply(convert_to_60)
combined['TOI_5v5'] = combined['TOI_5v5'].apply(convert_to_60)

# Create a new DataFrame for our stats per 60 mins of TOI
stats_60 = pd.DataFrame()
# Copy over the player information and their TOI info
for col in ['last','first','pos','num','GP','TOI','TOI_5v5']:
    stats_60[col] = combined[col]

stat_5v5_cols = ['corsi_for_5v5','corsi_against_5v5','corsi_5v5',
                 'fenwick_for_5v5','fenwick_against_5v5','fenwick_5v5',
                 '5v5_block','g_block_5_5v5','b_block_5_5v5','g_block_10_5v5',
                 'b_block_10_5v5','g_block_5_ev','5v5_hits','g_hit_5_5v5',
                 'b_hit_5_5v5','g_hit_10_5v5','b_hit_10_5v5']
for col in stat_5v5_cols:
    stats_60[col+'/60'] = combined[col]/stats_60['TOI_5v5']

stat_all_cols = ['corsi_for','corsi_against','corsi','fenwick_for',
                 'fenwick_against','fenwick','blocks','hits','5v5_hits']
for col in stat_all_cols:
    stats_60[col+'/60'] = combined[col]/stats_60['TOI']

g_block_5_all = combined['g_block_5_ev'] + combined['g_block_5_pp'] + combined['g_block_5_sh']
b_block_5_all = combined['b_block_5_ev'] + combined['b_block_5_pp'] + combined['b_block_5_sh']
g_block_10_all = combined['g_block_10_ev'] + combined['g_block_10_pp'] + combined['g_block_10_sh']
b_block_10_all = combined['b_block_10_ev'] + combined['b_block_10_pp'] + combined['b_block_10_sh']
g_hit_5_all = combined['g_hit_5_ev'] + combined['g_hit_5_pp'] + combined['g_hit_5_sh']
b_hit_5_all = combined['g_hit_5_ev'] + combined['g_hit_5_pp'] + combined['g_hit_5_sh']
g_hit_10_all = combined['g_hit_10_ev'] + combined['g_hit_10_pp'] + combined['g_hit_10_sh']
b_hit_10_all = combined['g_hit_10_ev'] + combined['g_hit_10_pp'] + combined['g_hit_10_sh']

# Create a temporary DataFrame to calculate the good/bad hits and blocks for
# all situations
calc_df = pd.DataFrame()
cols = [g_block_5_all,b_block_5_all,g_block_10_all,b_block_10_all,g_hit_5_all,b_hit_5_all,g_hit_10_all,b_hit_10_all]
col_names = ['g_block_5_all','b_block_5_all','g_block_10_all','b_block_10_all','g_hit_5_all','b_hit_5_all','g_hit_10_all','b_hit_10_all']
for col_name,col in zip(col_names,cols):
    calc_df[col_name] = col

# Calculate the stat/60 for each of these
calc_df['TOI'] = combined['TOI']
for col in col_names:
    calc_df[col+'/60'] = calc_df[col]/calc_df['TOI']
# Add only the stat/60 columns to our stats_60 DataFrame
for col in col_names:
    stats_60[col+'/60'] = calc_df[col+'/60']


import os
import time

import dbus

from . import const, utils

class SleepInhibitor:
    __instances = {}

    _name = None
    _proxy = None

    __inhibitor = None
    _fd = None

    def __init__(self, name):
        self._name = name

        bus = dbus.SystemBus()
        self._proxy = bus.get_object('org.freedesktop.login1',
                                     '/org/freedesktop/login1')

    @classmethod
    def get(cls, name):
        if name not in cls.__instances:
            cls.__instances[name] = cls(name)
        return cls.__instances[name]

    @property
    def _inhibitor(self):
        if not self._fd:
            self.__inhibitor = self._proxy.Inhibit(
                'sleep', self._name, self._name, 'delay',
                dbus_interface='org.freedesktop.login1.Manager')
        return self.__inhibitor

    def list(self):
        return self._proxy.ListInhibitors(
            dbus_interface='org.freedesktop.login1.Manager')

    def take(self):
        try:
            self._fd = self._inhibitor.take()
        except ValueError:
            self._fd = None
            raise

    def release(self):
        if not self._fd:
            return

        os.close(self._fd)
        self._fd = None

def register(config):
    inhibitor = SleepInhibitor.get(const.APP_NAME)

    cmd = utils.get_action(config, 'Sleep', 'sleep_action')
    delay = int(config['Sleep']['sleep_delay'])

    def _on_sleep(start):
        if not start:
            inhibitor.take()
            return

        utils.Action.get(cmd).run()
        time.sleep(delay)

        inhibitor.release()

    bus = dbus.SystemBus()
    bus.add_signal_receiver(_on_sleep, 'PrepareForSleep',
                            'org.freedesktop.login1.Manager')

    # Initial inhibit (important)
    inhibitor.take()


import functools

f = open("input.txt", "r")
data = f.read()

bits = []
for ch in data:
	xxx = bin(int(ch, 16))[2:].zfill(4)
	bits.append(xxx)
bits = "".join(bits)

pointer = 0

def eof():
	return bits[pointer:-1] == '' or int(bits[pointer:-1], 2) == 0

def peek(n, offset = 0):
	return bits[pointer+offset:pointer+offset+n]

def get_bits(n):
	global pointer
	text = bits[pointer:pointer+n]
	pointer += n
	return text

def parse_literal():
	pointer_start = pointer
	version = get_bits(3)
	type = get_bits(3)

	value = ''
	while True:
		val = get_bits(5)
		value += val[1:]
		if val[0] == '0':
			break

	return {
		'node_type': 'literal',
		'version': version,
		'length': pointer - pointer_start,
		'type': type,
		'value': int(value, 2),
	}

def get_length(nodes):
	length = 0
	for n in nodes:
		length += n['length']
	return length

def parse_operator():
	pointer_start = pointer
	version = get_bits(3)
	type = int(get_bits(3), 2)
	length_type = get_bits(1)
	length_bits = 11 if length_type == '1' else 15
	length = int(get_bits(length_bits), 2)

	end_of_packet = None
	if length_type == '0':
		end_of_packet = pointer + length

	inner_nodes = []
	while True:
		inner_nodes.append(parse_unknown())
		if length_type == '0' and get_length(inner_nodes) >= length:
			break
		if length_type == '1' and len(inner_nodes) >= length:
			break

	calculated_value = 0
	if (type == 0):
		calculated_value = functools.reduce(lambda a, b: a+b['value'], inner_nodes, 0)
	if (type == 1):
		calculated_value = functools.reduce(lambda a, b: a*b['value'], inner_nodes, 1)
	if (type == 2):
		calculated_value = min(map(lambda a: a['value'], inner_nodes))
	if (type == 3):
		calculated_value = max(map(lambda a: a['value'], inner_nodes))
	if (type == 5):
		calculated_value = 1 if inner_nodes[0]['value'] > inner_nodes[1]['value'] else 0
	if (type == 6):
		calculated_value = 1 if inner_nodes[0]['value'] < inner_nodes[1]['value'] else 0
	if (type == 7):
		calculated_value = 1 if inner_nodes[0]['value'] == inner_nodes[1]['value'] else 0

	return {
		'node_type': 'operator',
		'version': version,
		'length': pointer - pointer_start,
		'type': type,
		'inner_nodes': inner_nodes,
		'value': calculated_value
	}

def parse_unknown():
	packet_type = int(peek(3, 3), 2)
	if (packet_type == 4):
		return parse_literal()
	return parse_operator()

tree = []
while not eof():
	tree.append(parse_unknown())

def get_version_cumul(node):
	return node['value']

print(get_version_cumul(tree[0]))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import TemplateView
from panampath.models import PathSegment
from pprint import pprint
from forms import EmailForm
from django.conf import settings
from django.shortcuts import render_to_response, render
from django.core.mail.message import EmailMessage

# Create your views here.
class IndexView(TemplateView):
    template_name = 'main.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        segments = PathSegment.objects.all()

        coords = []
        for segment in segments:
            if segment.geom:
                coords.append(segment.geom['coordinates'])
            # for member in segment.geom['coordinates']:
            #     for item in member:
            #         coords.append(item[::-1])

        context["segments"] = segments
        context["coordinates"] = coords

        return context

def send_email(request):

    if request.method != 'POST':
        form = EmailForm()
        return render(request, 'submit_event.html', {'email_form': form})

    form = EmailForm(request.POST, request.FILES)

    if form.is_valid():
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        email = form.cleaned_data['email']
        attach = request.FILES['attach']
        try:
            mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email])
            mail.attach(attach.name, attach.read(), attach.content_type)
            response = mail.send()
            return render(request, 'submit_event.html', {'message': 'Sent email to %s' % (email)})
        except Exception as e:
            return render(request, 'submit_event.html', {'message': e.message})
    else:
        try:
            return render(request, 'submit_event.html', {'message': form.message})

        except AttributeError:
            return render(request, 'submit_event.html', {'message': "Please fill out all fields on the form.", "email_form":form})

    #return render(request, 'submit_event.html', {'message': 'Unable to send email. Please try again later'})


import argparse
import sys
from functools import partial
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
import yaml
from yaml.parser import ParserError
from yaml.loader import SafeLoader
from bluepy import btle

def init_argparse() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        usage="%(prog)s [OPTION]",
        description="Prometheus exporter for Xiaomi sensors"
    )
    parser.add_argument(
        "-c", "--config", help="path to config file")

    return parser

class MyDelegate(btle.DefaultDelegate):
    def __init__(self):
        btle.DefaultDelegate.__init__(self)
        self.data = {}

    def handleNotification(self, cHandle, data):
        databytes = bytearray(data)
        temperature = int.from_bytes(databytes[0:2],"little") / 100
        humidity = int.from_bytes(databytes[2:3],"little")
        battery = int.from_bytes(databytes[3:5],"little") / 1000
        print(f"Temperature: {temperature}, humidity: {humidity}, battery: {battery}")
        self.data = {"temperature": temperature, "humidity": humidity, "battery": battery, "success": True}

def read_values(mac):
    print(f"Connecting to {mac}")
    connected = False
    try:
        # Timeout not released: https://github.com/IanHarvey/bluepy/pull/374
        dev = btle.Peripheral(mac)
        connected = True
        print("Connection done...")
        delegate = MyDelegate()
        dev.setDelegate(delegate)
        print("Waiting for data...")
        dev.waitForNotifications(15.0)
        return delegate.data
    except btle.BTLEDisconnectError as error:
        print(error)
        return {"success": False}
    finally:
        if connected:
            dev.disconnect()

def to_measures(device):
    response = f"""#HELP xiaomi_sensor_exporter_temperature_celsius Temperature
#TYPE xiaomi_sensor_exporter_temperature_celsius gauge
xiaomi_sensor_exporter_temperature_celsius{{name="{device["name"]}",address="{device["address"]}"}} {device["data"]["temperature"]}
#HELP xiaomi_sensor_exporter_humidity_percent Humidity
#TYPE xiaomi_sensor_exporter_humidity_percent gauge
xiaomi_sensor_exporter_humidity_percent{{name="{device["name"]}",address="{device["address"]}"}} {device["data"]["humidity"]}
#HELP xiaomi_sensor_exporter_battery_volt Battery
#TYPE xiaomi_sensor_exporter_battery_volt Volt
xiaomi_sensor_exporter_battery_volt{{name="{device["name"]}",address="{device["address"]}"}} {device["data"]["battery"]}
"""
    return response

class WebRequestHandler(BaseHTTPRequestHandler):

    # https://stackoverflow.com/a/52046062
    def __init__(self, devices, *args, **kwargs):
        self.devices = devices
        # BaseHTTPRequestHandler calls do_GET **inside** __init__ !!!
        # So we have to call super().__init__ after setting attributes.
        super().__init__(*args, **kwargs)

    def do_GET(self):
        if self.path == "/":
            return self.get_index()
        elif self.path == "/metrics":
            return self.get_metrics()
        else:
            return self.get_not_found()

    def get_index(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain; version=0.0.1; charset=utf-8")
        self.end_headers()
        self.wfile.write(str(self.devices).encode("utf-8"))

    def get_metrics(self):
        response = f"""#HELP xiaomi_sensor_exporter_number_of_sensors Number of sensors
#TYPE xiaomi_sensor_exporter_number_of_sensors gauge
xiaomi_sensor_exporter_number_of_sensors {len(devices)}
"""

        for device in devices:
            device["data"] = read_values(device["address"])
            if device["data"]["success"] is True:
                response += to_measures(device)

        self.send_response(200)
        self.send_header("Content-Type", "text/plain; version=0.0.1; charset=utf-8")
        self.end_headers()
        self.wfile.write(response.encode("utf-8"))

    def get_not_found(self):
        self.send_response(404)
        self.send_header("Content-Type", "text/plain; version=0.0.1; charset=utf-8")
        self.end_headers()
        self.wfile.write("Not found".encode("utf-8"))

if __name__ == "__main__":
    devices = []
    port = 9093

    parser = init_argparse()
    args = parser.parse_args()

    devices_config_file = args.config

    if devices_config_file:
        try:
            with open(devices_config_file, encoding="utf-8") as f:
                data = yaml.load(f, SafeLoader)
                if "port" in data:
                    port = data["port"]
                if "devices" in data:
                    devices = data["devices"]
        except FileNotFoundError:
            print(f"Configuration file not found: {devices_config_file}")
            sys.exit(-1)
        except ParserError:
            print(f"Invalid configuration file: {devices_config_file}")
            sys.exit(-1)

    print(f"Creating xiaomi_sensor_exporter server on port {port}")
    handler = partial(WebRequestHandler, devices)
    server = HTTPServer(("0.0.0.0", port), handler)
    server.serve_forever()


import sys
input = sys.stdin.readline
dic = {"Poblano":1500, "Mirasol":6000, "Serrano":15500, "Cayenne":40000, "Thai":75000, "Habanero":125000}
sum = 0
for i in range(int(input())):
    word = input().rstrip()
    sum += dic[word]
print(sum)

# https://www.acmicpc.net/problem/28249


def common_elements(list1, list2):
    return [element for element in list1 if element in list2]

def palindrome_strings(string_list):
    return [string for string in string_list if string == string[::-1]]

def sieve_of_eratosthenes(number_list):
    primes = []
    for num in number_list:
        if num > 1:
            for i in range(2, num):
                if num % i == 0:
                    break
            else:
                primes.append(num)
    return primes

def anagrams(word, word_list):
    sorted_word = sorted(word.lower())
    anagram_list = []
    for word_candidate in word_list:
        if sorted(word_candidate.lower()) == sorted_word:
            anagram_list.append(word_candidate)
    return anagram_list


"""
Created on 18.2.2020

@author: Erik Altermann, Fernando Moya Rueda, Arthur Matei
@email: erik.altermann@tu-dortmund.de, 	fernando.moya@tu-dortmund.de, arthur.matei@tu-dortmund.de
"""

import sys
from PyQt5 import QtWidgets
from gui import GUI

# from sensors import SensorThread
def except_hook(cls, exception, traceback):
    sys.__excepthook__(cls, exception, traceback)

if __name__ == '__main__':
    sys.excepthook = except_hook
    # Create the Qt Application
    app = QtWidgets.QApplication(sys.argv)
    main_window = GUI()
    app.exec_()
    sys.exit(0)


import numpy as np
from sklearn.utils.random import sample_without_replacement
from sklearn.metrics import auc, precision_recall_curve, roc_curve
from sklearn.svm import OneClassSVM
import argparse
import load_data
import networkx as nx
from GCN_embedding import GcnEncoderGraph_teacher, GcnEncoderGraph_student
import torch
import torch.nn as nn
import time
import GCN_embedding
from torch.autograd import Variable
from graph_sampler import GraphSampler
from numpy.random import seed
import random
import matplotlib.pyplot as plt
import copy
import torch.nn.functional as F
from sklearn.manifold import TSNE
from matplotlib import cm
from tdc.utils import retrieve_label_name_list
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedKFold
import mlflow
from util import sce_loss

def arg_parse():
    parser = argparse.ArgumentParser(description='GLocalKD Arguments.')
    parser.add_argument('--datadir', dest='datadir', default ='dataset', help='Directory where benchmark is located')
    parser.add_argument('--DS', dest='DS', default ='AIDS', help='dataset name')
    parser.add_argument('--max-nodes', dest='max_nodes', type=int, default=0, help='Maximum number of nodes (ignore graghs with nodes exceeding the number.')
    parser.add_argument('--clip', dest='clip', default=0.1, type=float, help='Gradient clipping.')
    parser.add_argument('--num_epochs', dest='num_epochs', default=150, type=int, help='total epoch number')
    parser.add_argument('--batch-size', dest='batch_size', default=300, type=int, help='Batch size.')
    parser.add_argument('--hidden-dim', dest='hidden_dim', default=512, type=int, help='Hidden dimension')
    parser.add_argument('--output-dim', dest='output_dim', default=256, type=int, help='Output dimension')
    parser.add_argument('--num-gc-layers', dest='num_gc_layers', default=3, type=int, help='Number of graph convolution layers before each pooling')
    parser.add_argument('--nobn', dest='bn', action='store_const', const=False, default=True, help='Whether batch normalization is used')
    parser.add_argument('--dropout', dest='dropout', default=0.3, type=float, help='Dropout rate.')
    parser.add_argument('--nobias', dest='bias', action='store_const', const=False, default=True, help='Whether to add bias. Default to True.')
    parser.add_argument('--feature', dest='feature', default='default', help='use what node feature')
    parser.add_argument('--seed', dest='seed', type=int, default=1, help='seed')
    return parser.parse_args()

def setup_seed(seed):
     torch.manual_seed(seed)
     torch.cuda.manual_seed_all(seed)
     np.random.seed(seed)
     random.seed(seed)
     torch.backends.cudnn.deterministic = True

def test(data_test_loader, model_teacher, model_student, args):

    auroc_final = 0
    model_student.eval()
    loss = []
    y=[]
    emb=[]

    for batch_idx, data in enumerate(data_test_loader):
        adj = Variable(data['adj'].float(), requires_grad=False).to(device)
        h0 = Variable(data['feats'].float(), requires_grad=False).to(device)

        embed_node, embed = model_student(h0, adj)
        embed_teacher_node, embed_teacher = model_teacher(h0, adj)
    #    loss_node = torch.mean(sce_loss(embed_node, embed_teacher_node), dim=-1).mean(dim=-1)
    #    loss_graph = sce_loss(embed, embed_teacher).mean(dim=-1)
        loss_node = torch.mean(F.mse_loss(embed_node, embed_teacher_node, reduction='none'), dim=2).mean(dim=1).mean(dim=0)
        loss_graph = F.mse_loss(embed, embed_teacher, reduction='none').mean(dim=1).mean(dim=0)
        loss_ = loss_graph + loss_node
        loss_ = np.array(loss_.cpu().detach())
        loss.append(loss_)
        if data['label'] == 0:
            y.append(1)
        else:
            y.append(0)
        emb.append(embed.cpu().detach().numpy())

    label_test = []
    for loss_ in loss:
        label_test.append(loss_)
    label_test = np.array(label_test)

    fpr_ab, tpr_ab, _ = roc_curve(y, label_test)
    print(list(zip(y, label_test)))
    test_roc_ab = auc(fpr_ab, tpr_ab)
    print('semi-supervised abnormal detection: auroc_ab: {}'.format(test_roc_ab))
    return auroc_final

if __name__ == '__main__':

    mlflow.set_experiment("GraphAD")
    experiment = mlflow.get_experiment_by_name("GraphAD")

    import mlflow.pytorch

    device = 'cuda' if torch.cuda.is_available() else 'cpu'

    args = arg_parse()
    DS = f'{args.DS}'

    print(f'DS: {DS}')
    setup_seed(args.seed)

    graphs = load_data.read_graphfile(args.datadir, args.DS, max_nodes=args.max_nodes)
    datanum = len(graphs)
    if args.max_nodes == 0:
        max_nodes_num = max([G.number_of_nodes() for G in graphs])
    else:
        max_nodes_num = args.max_nodes
    print(f'Total graphs: {datanum}')
    graphs_label = [graph.graph['label'] for graph in graphs]

    model_name = "student_model_registered"
    model_version = 1

    model_student = mlflow.pytorch.load_model(
        model_uri=f"models:/{model_name}/{model_version}"
    )

    model_name_t = "teacher_model_registered"
    model_version_t = 1

    model_teacher = mlflow.pytorch.load_model(
        model_uri=f"models:/{model_name_t}/{model_version_t}"
    )

    kfd=StratifiedKFold(n_splits=5, random_state=args.seed, shuffle = True)
    result_auc=[]
    for k, (train_index,test_index) in enumerate(kfd.split(graphs, graphs_label)):
        graphs_train_ = [graphs[i] for i in train_index]
        graphs_test = [graphs[i] for i in test_index]

        graphs_train = []
        for graph in graphs_train_:
            if graph.graph['label'] != 0:
                graphs_train.append(graph)

        num_train = len(graphs_train)
        num_test = len(graphs_test)
        print(num_train, num_test)

        dataset_sampler_test = GraphSampler(graphs_test, features=args.feature, normalize=False, max_num_nodes=max_nodes_num)
        data_test_loader = torch.utils.data.DataLoader(dataset_sampler_test,
                                                        shuffle=False,
                                                        batch_size=1)
        result = test(data_test_loader, model_teacher, model_student, args)
        result_auc.append(result)

    result_auc = np.array(result_auc)
    auc_avg = np.mean(result_auc)
    auc_std = np.std(result_auc)
    print('auroc{}, average: {}, std: {}'.format(result_auc, auc_avg, auc_std))


import matplotlib.pyplot as plt
plt.ion()
import matplotlib.dates as mdates
import numpy as np
import data_handler
import gpr_wrapper

class Plotter:
    company_name = None
    company_handler = None
    quarters = None
    years = None
    gpr = None
    extreme = []

    def __init__(self, company_name: str):
        self.company_name = company_name
        self.company_handler = data_handler.CsvHandler(company_name)
        self.quarters = self.company_handler.quarters
        self.years = self.company_handler.years
        self.gpr = gpr_wrapper.Wrapper(company_name)

    def show_gpr(self, train_start: int, train_end: int):
        self.validate_dates(start_year=train_start, end_year=train_end)

        prices = self.company_handler.get_whole_prices(train_start, train_end)
        prices = prices[prices.iloc[:].notnull()]

        fig = plt.figure(num=self.company_name + ' prediction')
        ax = plt.gca()
        fig.set_size_inches(12, 6)
        x_obs = np.linspace(0, prices.shape[0] - 1, prices.shape[0])

        x, y_mean, y_cov = self.gpr.get_eval_model(train_start, train_end, prices)

        y_lower = y_mean - np.sqrt(np.diag(y_cov))
        y_upper = y_mean + np.sqrt(np.diag(y_cov))
        y_max = max(y_upper) * 1.1
        ax.set_ylim(bottom=0, top=y_max)

        x_min, x_max = x_obs[0], x_obs[-1]
        ax.set_xlim(left=x_min, right=x_max)

        plt.plot(x_obs, prices.loc[:, 'Adj Close'], color='#006699', alpha=.95, label=u'Observations ', zorder=10)
        plt.plot(x, y_mean, color='#ff0066', linestyle='--', label=u'Prediction')
        plt.fill_between(x, y_lower, y_upper, alpha=.25, label='95% confidence', color='#ff0066')

        handles, labels = plt.gca().get_legend_handles_labels()
        new_labels, new_handles = [], []
        for handle, label in zip(handles, labels):
            if label not in new_labels:
                new_labels.append(label)
                new_handles.append(handle)
        plt.legend(new_handles, new_labels, bbox_to_anchor=(0.01, 0.02), loc='lower left', borderaxespad=0.)

        plt.grid(True, alpha=.25)
        plt.title(self.company_name)
        plt.xlabel('Days\n')
        plt.ylabel('Price')

        plt.tight_layout()

        fname = '{}_{}__{}prediction.png'.format(self.company_name, train_start, train_end)
        fig.savefig(fname, dpi=fig.dpi)
        plt.clf()
        return x, y_mean

    def show_whole_time_series(self, intermediate: bool = False):
        self.show_time_series(start_year=self.years[0], end_year=self.years[-1], intermediate=intermediate)

    def show_time_series(self, start_year: int, end_year: int):
        self.validate_dates(start_year=start_year, end_year=end_year)

        prices_data = self.company_handler.get_whole_prices(start_year=start_year, end_year=end_year)

        fig = plt.figure(num=self.company_name + ' prices')
        fig.set_size_inches(12, 6)
        plt.plot(prices_data.iloc[:, 0], prices_data.iloc[:, 1], color='#006699', alpha=.95,
                 label=u'Observations ' + str(start_year) + '-' + str(end_year), zorder=10)
        ax = plt.gca()

        x_ticks = []
        for year in range(start_year, end_year + 2):
            if year == end_year + 1:
                current_date = prices_data[prices_data['Date'].dt.year == end_year].iloc[-1, 0]
            else:
                current_date = prices_data[prices_data['Date'].dt.year == year].iloc[0, 0]
            x_ticks.append(current_date)
        x_formatter = mdates.DateFormatter('%Y-%m-%d')
        ax.xaxis.set_major_formatter(x_formatter)
        ax.set_xticks(x_ticks)
        plt.xticks(rotation=20)
        y_min, y_max = ax.get_ylim()
        x_min, x_max = ax.get_xlim()
        ax.set_ylim(bottom=y_min, top=y_max)
        ax.set_xlim(left=x_min, right=x_max)

        for i in range(0, len(x_ticks)):
            plt.vlines(x=x_ticks[i], ymin=y_min, ymax=y_max, color='black', linestyles='--', alpha=.6,
                       zorder=-1)

        plt.grid(True, alpha=0.25)
        plt.legend()
        plt.title(self.company_name)
        plt.ylabel('Price')

        plt.tight_layout()

        fname = '{}_{}_{}_prices.png'.format(self.company_name, start_year, end_year)
        fig.savefig(fname, dpi=fig.dpi)
        plt.clf()

    def validate_dates(self, start_year: int, end_year: int):
        if start_year < self.years[0] or end_year > self.years[-1]:
            raise ValueError('\n' +
                             'Input years out of available range! \n' +
                             'Max range available: {}-{}\n'.format(self.__years[0], self.__years[-1]) +
                             'Was: {}-{}'.format(start_year, end_year))

    def update(self, X, Y):
        self.extreme = []
        if X.shape[0] != Y.shape[0]:
            raise ValueError('\n' +
                             'The shape of X and Y is not equal }' + '\n')
        if(X.shape[0] == 0):
            return
        self.extreme.append([X[0], Y[0]])
        for i in range(1,X.shape[0]-1):
            if Y[i] >= Y[i-1] and Y[i] >= Y[i+1] or Y[i] <= Y[i-1] and Y[i] <= Y[i+1]:
                self.extreme.append([X[i], Y[i]])
        self.extreme.append([X[-1], Y[-1]])


from api.filters import IngredientFilter, RecipeFilter
from api.pagination import CustomPageNumberPagination
from api.permissions import AuthorAdminPermission, IsAdminOrReadOnly
from api.serializers import (IngredientSerializer, RecipeCreateSerializer,
                             RecipeReadSerializer, RecipeShortSerializer,
                             SubscriptionsSerializer, TagSerializer,
                             UserSerializer)
from api.utils import download_shopping_list
from django_filters.rest_framework import DjangoFilterBackend
from djoser.views import UserViewSet
from recipe.models import Favorite, Ingredient, Recipe, ShoppingCart, Tag
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from users.models import Subscriptions, User

class CustomUserViewSet(UserViewSet):
    """Кастомный вьюсет для работы с пользователями."""

    queryset = User.objects.all()
    serializer_class = UserSerializer
    pagination_class = CustomPageNumberPagination

    @action(
            methods=['get'],
            permission_classes=(IsAuthenticated, ),
            detail=False,
            url_path='subscriptions',

        )
    def subscriptions(self, request):
        """Получение списка подписок."""
        queryset = User.objects.filter(
            subscriptions__user=request.user
        )
        page = self.paginate_queryset(queryset)
        serializer = SubscriptionsSerializer(
                page,
                many=True,
                context={'request': request}
        )
        return self.get_paginated_response(serializer.data)

    @action(
        methods=['post', 'delete'],
        permission_classes=(IsAuthenticated, ),
        detail=True
    )
    def subscribe(self, request, id):
        """Создание или отмена подписки."""
        user = request.user
        author = get_object_or_404(User, id=id)

        if request.method == 'POST':
            if user.id == author.id:
                return Response(
                    {'error_message': 'Нельзя подписаться на самого себя'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            if Subscriptions.objects.filter(
                user=user, author=author
            ).exists():
                return Response(
                    {'error_message': f'Вы уже подписаны на {author}'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            Subscriptions.objects.create(user=user, author=author)
            serializer = SubscriptionsSerializer(author,
                                                 context={'request': request})
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        if request.method == 'DELETE':
            subscription = get_object_or_404(Subscriptions,
                                             user=user,
                                             author=author)
            subscription.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)

class TagViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = TagSerializer
    queryset = Tag.objects.all()
    permission_classes = (IsAdminOrReadOnly, )

class IngredientViewSet(viewsets.ReadOnlyModelViewSet):
    """Вывод игредиентов."""

    serializer_class = IngredientSerializer
    queryset = Ingredient.objects.all()
    permission_classes = (IsAdminOrReadOnly, )
    filterset_class = IngredientFilter

class RecipeViewSet(viewsets.ModelViewSet):
    """Рецепты."""

    serializer_class = RecipeCreateSerializer
    queryset = Recipe.objects.all()
    permission_classes = (AuthorAdminPermission, )
    filter_backends = (DjangoFilterBackend,)
    filterset_class = RecipeFilter
    pagination_class = CustomPageNumberPagination

    def get_serializer_class(self):
        """Определение класса сериализатора в зависимости от запроса."""
        if self.request.method == 'GET':
            return RecipeReadSerializer
        return RecipeCreateSerializer

    def add_recipe(self, model, request, recipe_id):
        """Метод добавления рецепта."""
        user = request.user
        recipe = get_object_or_404(Recipe, id=recipe_id)
        obj = model.objects.filter(user=user, recipe=recipe)
        if obj.exists():
            return Response(
                {'error_message': 'Этот рецепт уже добавлен'},
                status=status.HTTP_400_BAD_REQUEST
            )
        model.objects.create(user=user, recipe=recipe)
        serializer = RecipeShortSerializer(recipe)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def delete_recipe(self, model, request, recipe_id):
        """Метод удаления рецепта."""
        user = request.user
        recipe = get_object_or_404(Recipe, id=recipe_id)
        obj = model.objects.filter(user=user, recipe=recipe)
        if obj.exists():
            obj.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        return Response(
            {'errors': 'Рецепт уже удалён'},
            status=status.HTTP_400_BAD_REQUEST
        )

    @action(detail=True,
            methods=['post', 'delete'],
            permission_classes=(IsAuthenticated, ))
    def favorite(self, request, pk=None):
        """Добавление и удаление рецептов из избранного."""
        if request.method == 'POST':
            return self.add_recipe(Favorite, request, pk)
        return self.delete_recipe(Favorite, request, pk)

    @action(detail=True,
            methods=['post', 'delete'],
            permission_classes=(IsAuthenticated, ))
    def shopping_cart(self, request, pk=None):
        """Добавление и удаление рецептов из корзины."""
        if request.method == 'POST':
            return self.add_recipe(ShoppingCart, request, pk)
        return self.delete_recipe(ShoppingCart, request, pk)

    @action(detail=False,
            methods=['get'],
            permission_classes=(IsAuthenticated, ))
    def download_shopping_cart(self, request):
        return download_shopping_list(request)


from django.conf.urls import url
from rest_framework import routers
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^get_mileages/(?P<car_id>[0-9]+)$', views.get_mileages),
    url(r'^update_mileages/(?P<car_id>[0-9]+)$', views.update_mileages),
    url(r'^add$', views.input_new_refueling),
    url(r'^add_refueling$', views.add_refueling),
]

router = routers.DefaultRouter()
router.register(r'mileages', views.MileagesViewSet)
router.register(r'car', views.CarViewSet)
urlpatterns += router.urls


import logging

mylogger = logging.getLogger("TRADE")

def logInit():
    mylogger = logging.getLogger("TRADE")
    mylogger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    stream_hander = logging.StreamHandler()
    stream_hander.setFormatter(formatter)
    mylogger.addHandler(stream_hander)

    file_handler = logging.FileHandler('trade.log')
    file_handler.setFormatter(formatter)
    mylogger.addHandler(file_handler)

def logPrint(message):
    mylogger.info(message)


#!/usr/bin/env python3
# import libraries
import os
import time
import ast
import read_directory
import datetime as dt
from os import stat
from pwd import getpwuid
from pathlib import Path

# get file creation date
def get_file_creation_date(file_path):
        c = time.strftime('%d/%m/%Y', time.gmtime(os.path.getctime(file_path)))
        print('Creation Date '+ c)
        return c

# get file modification date
def get_modification_date(file_path):
        m = time.strftime('%d/%m/%Y', time.gmtime(os.path.getmtime(file_path)))
        print('Modification Date '+ m)
        return m

# get last accessed
def get_last_accessed_date(file_path):
        a = time.strftime('%d/%m/%Y', time.gmtime(os.path.getatime(file_path)))
        print('Accessed Date '+ a)
        return a

# get file size, this returns in bytes
def get_file_size(file_path):
        s = os.path.getsize(file_path)
        print(s)
        return s

# get file owner/creator
def get_file_owner(file_path):
        o = getpwuid(stat(file_path).st_uid).pw_name
        print('Owner '+ o)
        return o

# get the name of the file
def get_filename(file_path):
        f = os.path.basename(file_path)
        print('Filename '+ f)
        return f

# get the file extension
def get_file_extension(file_path):
        e = os.path.basename(file_path)
        e = e.split('.')[-1]
        print(e)
        return e

# print out the directory, and then get the absolute path for every item in the directory if it meets the extension requirements
file_paths = []
def get_file_path(directory):
        directory_len = read_directory.list_directory(directory)
        #length = len(directory_len)
        for file in sorted(directory.rglob('**/*py')):
                # for each file in the directory, return the full path for passing into information gathering functions. store in character string
                file_path = os.path.abspath(file)
                file_paths.append(file_path)
        print("\n".join(file_paths))
        print(file_paths)
        return file_paths

# pull together the file information using the get functions and then call the dictionary creation
def gather_file_info(file_paths):
        #print(file_paths)
        n = range(len(file_paths))
        print(n)
        for file in range(len(file_paths)):
                fil = get_filename(str(file_paths[file]))
                own = get_file_owner(file_paths[file])
                siz = get_file_size(file_paths[file])
                cre = get_file_creation_date(file_paths[file])
                mod = get_modification_date(file_paths[file])
                acc = get_last_accessed_date(file_paths[file])
                ext = get_file_extension(file_paths[file])
                create_dictionary(fil, own, siz, cre, mod, acc, ext)

# create a dictionary with key value pairs
def create_dictionary(filename,owner,size,modification,creation,accessed,extension):
        keys = ["filename","owner", "size", "creation_date", "modification_date", "accessed_date", "extension"]
        values = [filename, owner, size, creation, modification, accessed, extension]
        mydict = dict(zip(keys, values))
        create_sql_statement(mydict)

# auto generate the SQL statement which will be used inserting the record into the DB
def create_sql_statement(mydict):
        for dict in mydict:
                placeholders = ', '.join(['%s'] * len(dict))
                columns = ', '.join("" + str(x).replace('/', '_') + "" for x in mydict.keys())
                values = ', '.join("'" + str(x).replace('/', '_') + "'" for x in mydict.values())
                sql = "INSERT INTO %s  (%s)  VALUES  (%s) ;" % ('test_table', columns, values)

                print(sql)
                f = open("./test.sql", "a")
                f.write(sql + '\n')
                return sql

if __name__ == '__main__':
    get_file_path(Path.cwd())
    gather_file_info(file_paths)


from __future__ import print_function

import chess
import chess.uci
import chess.variant
import time
import textwrap
import argparse
import itertools
import logging
import sys

def test_epd(engine, epd, VariantBoard, movetime):
    position = VariantBoard()
    epd_info = position.set_epd(epd)
    epd_string = "%s" % epd_info.get("id", position.fen())
    if "am" in epd_info:
        epd_string = "%s (avoid %s)" % (epd_string, " and ".join(position.san(am) for am in epd_info["am"]))
    if "bm" in epd_info:
        epd_string = "%s (expect %s)" % (epd_string, " or ".join(position.san(bm) for bm in epd_info["bm"]))

    engine.ucinewgame()
    engine.setoption({"UCI_Variant": VariantBoard.uci_variant})
    engine.position(position)

    enginemove, pondermove = engine.go(movetime=movetime)

    if "am" in epd_info and enginemove in epd_info["am"]:
        print("%s: %s | +0" % (epd_string, position.san(enginemove)))
        return 0.0
    elif "bm" in epd_info and not enginemove in epd_info["bm"]:
        print("%s: %s | +0" % (epd_string, position.san(enginemove)))
        return 0.0
    else:
        print("%s: %s | +1" % (epd_string, position.san(enginemove)))
        return 1.0

def test_epd_with_fractional_scores(engine, epd, VariantBoard, movetime):
    info_handler = chess.uci.InfoHandler()
    engine.info_handlers.append(info_handler)

    position = VariantBoard()
    epd_info = position.set_epd(epd)
    epd_string = "%s" % epd_info.get("id", position.fen())
    if "am" in epd_info:
        epd_string = "%s (avoid %s)" % (epd_string, " and ".join(position.san(am) for am in epd_info["am"]))
    if "bm" in epd_info:
        epd_string = "%s (expect %s)" % (epd_string, " or ".join(position.san(bm) for bm in epd_info["bm"]))

    engine.ucinewgame()
    engine.setoption({"UCI_Variant": VariantBoard.uci_variant})
    engine.position(position)

    # Search in background
    search = engine.go(infinite=True, async_callback=True)

    score = 0.0

    print("%s:" % epd_string, end=" ")
    sys.stdout.flush()

    for step in range(0, 3):
        time.sleep(movetime / 4000.0)

        # Assess the current principal variation.
        with info_handler as info:
            if 1 in info["pv"] and len(info["pv"][1]) >= 1:
                move = info["pv"][1][0]
                print("(%s)" % position.san(move), end=" ")
                sys.stdout.flush()
                if "am" in epd_info and move in epd_info["am"]:
                    continue #fail
                elif "bm" in epd_info and not move in epd_info["bm"]:
                    continue #fail
                else:
                     score = 1.0 / (4 - step)
            else:
                print("(no pv)", end=" ")
                sys.stdout.flush()

    # Assess the final best move by the engine.
    time.sleep(movetime / 4000.0)
    engine.stop()
    enginemove, pondermove = search.result()
    if "am" in epd_info and enginemove in epd_info["am"]:
        pass #fail
    elif "bm" in epd_info and not enginemove in epd_info["bm"]:
        pass #fail
    else:
         score = 1.0

    print("%s | +%g" % (position.san(enginemove), score))

    engine.info_handlers.remove(info_handler)
    return score

if __name__ == "__main__":
    # Parse command line arguments.
    parser = argparse.ArgumentParser(description="Run an EPD test suite with an UCI engine.")
    parser.add_argument("-e", "--engine", required=True,
        help="The UCI engine under test.")
    parser.add_argument("epd", nargs="+", type=argparse.FileType("r"),
        help="EPD test suite(s).")
    parser.add_argument("-v", "--variant", default="standard",
        help="Use a non-standard chess variant.")
    parser.add_argument("-t", "--movetime", default=1000, type=int,
        help="Time to move in milliseconds.")
    parser.add_argument("-s", "--simple", dest="test_epd", action="store_const",
        default=test_epd_with_fractional_scores,
        const=test_epd,
        help="Run in simple mode without fractional scores.")
    parser.add_argument("-d", "--debug", action="store_true",
        help="Show debug logs.")
    args = parser.parse_args()

    # Configure logger.
    logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)

    # Find variant.
    VariantBoard = chess.variant.find_variant(args.variant)

    # Open engine.
    engine = chess.uci.popen_engine(args.engine)
    engine.uci()

    # Run each test line.
    score = 0.0
    count = 0

    for epd in itertools.chain(*args.epd):
        # Skip comments and empty lines.
        epd = epd.strip()
        if not epd or epd.startswith("#") or epd.startswith("%"):
            print(epd.rstrip())
            continue

        # Run the actual test.
        score += args.test_epd(engine, epd, VariantBoard, args.movetime)
        count += 1

    engine.quit()

    print("-------------------------------")
    print("%g / %d" % (score, count))


from collections import deque

n, k = map(int, input().split())

MAX = 100000
MIN = 0

distances = [-1 for _ in range(100001)]
distances[n] = 0

to_go = deque()
to_go.append(n)

while to_go:
    now = to_go.popleft()

    mult = now*2
    if MIN <= mult <= MAX and distances[mult] == -1:
        to_go.appendleft(mult)
        distances[mult] = distances[now]

    a_second_later = [now-1, now+1]
    for _next in a_second_later:
        if MIN <= _next <= MAX and distances[_next] == -1:
            to_go.append(_next)
            distances[_next] = distances[now]+1

print(distances[k])


# Main function
def magic(arr):
    sizes = []
    visited = [[False for x in row] for row in arr]
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            if visited[i][j]:
                continue
            explore_node(i, j, arr, visited, sizes)
    return sorted(sizes)

# traverse all valid nodes and their neighbors, keep track of visited nodes and the currently explored river size
def explore_node(i, j, matrix, visited, sizes):
    current_size = 0
    nodes_to_explore = [[i, j]]
    while len(nodes_to_explore):
        i, j = nodes_to_explore.pop()
        if visited[i][j]:
            continue
        visited[i][j] = True
        if matrix[i][j] == 0:
            continue
        current_size += 1
        unvisited_neighbors = get_unvisited(i, j, matrix, visited)
        for neighbor in unvisited_neighbors:
            nodes_to_explore.append(neighbor)
    if current_size > 0:
        sizes.append(current_size)

# Helper function for retrieving a specific node unvisited neighbors
def get_unvisited(i, j, matrix, visited):
    unvisited_nodes = []
    if i > 0 and not visited[i - 1][j]:
        unvisited_nodes.append([i - 1, j])
    if i < len(matrix) - 1 and not visited[i + 1][j]:
        unvisited_nodes.append([i + 1, j])
    if j > 0 and not visited[i][j-1]:
        unvisited_nodes.append([i, j - 1])
    if j < len(matrix[0]) - 1 and not visited[i][j + 1]:
        unvisited_nodes.append([i, j + 1])
    return unvisited_nodes

# drivers code
arr1 = [[1, 0, 0, 1],
        [0, 0, 1, 0],
        [1, 0, 1, 0],
        [1, 0, 1, 0]]

arr2 = [[0, 0, 0, 1, 0, 0, 0, 1],
        [1, 1, 0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 1, 1, 0, 1],
        [1, 1, 1, 0, 0, 0, 0, 0]]

arr3 = [[0, 0, 0, 0, 1],
        [0, 1, 1, 1, 0],
        [0, 1, 0, 1, 0],
        [0, 1, 1, 1, 0],
        [1, 0, 0, 0, 0]]

print(magic(arr1))
print(magic(arr2))
print(magic(arr3))


import cv2
import numpy as np

"""
https://www.wolai.com/zeros/6RttqgH83Ww9WwB7S6LE93?theme=light
"""

img = cv2.imread('image/pic_0012.jpg', cv2.IMREAD_GRAYSCALE)

# 这里所用的内核为5*5的平均
blur = cv2.blur(img, (5, 5))  # 均值滤波
cv2.putText(blur, "blur", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 0), 2)
# kernel = np.ones((5, 5), np.float32) / 25
# dst_1 = cv2.filter2D(img, -1, kernel)  # 均值滤波，只是使用2D卷积的函数来进行操作

# 方框滤波
boxFilter = cv2.boxFilter(img, -1, (5, 5), normalize=True)
cv2.putText(boxFilter, "box", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 0), 2)
# 这里可以看normalize置为True和False各有什么效果
# boxFilter_1 = cv2.boxFilter(img, -1, (5, 5), normalize=True)
# boxFilter_2 = cv2.boxFilter(img, -1, (5, 5), normalize=False)
# cv2.putText(boxFilter_1, "normalize=True", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 0), 2)
# cv2.putText(boxFilter_2, "normalize=False", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 0), 2)

# 高斯滤波
gaussian = cv2.GaussianBlur(img, (5, 5), 1)
cv2.putText(gaussian, "gaussian", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 0), 2)

# 中值滤波
median = cv2.medianBlur(img, 5)
cv2.putText(median, "median", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 0), 2)

# 双边滤波
bilateral = cv2.bilateralFilter(img, 9, 75, 75)
cv2.putText(bilateral, "bilateral", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 0), 2)

# 该函数用于数组的拼接，0表示纵向，1表示横向，hstack和vstack有同样的效果
cv2.putText(img, "origin", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 0), 2)
white_column_split = np.zeros((img.shape[0], 1), np.uint8)  # 1列的白色分隔符
result_1 = np.concatenate((img, white_column_split, blur, white_column_split, boxFilter), axis=1)
result_2 = np.concatenate((gaussian, white_column_split, median, white_column_split, bilateral), axis=1)
white_row_split = np.zeros((1, result_1.shape[1]), np.uint8)  # 1行的白色分隔符
result = np.concatenate((result_1, white_row_split, result_2), axis=0)

cv2.imshow('图像平滑对比', result)
cv2.waitKey(0)
cv2.destroyAllWindows()


import requests

def net_xy(street):
    """
    A function that returns the X,Y of the given street
    :param street: a street name in hebrew in format street,city
    :return: a tuple of X,Y cords
    """

    # api-endpoint
    URL = "https://ags.govmap.gov.il/Search/FreeSearch"
    # headers
    headers = {"Content-Type": "application/json", "charset": "utf-8"}
    # location given here
    try:
        p = "{\"keyword\": \"" + street + "\",\"LstResult\": null}"
        PARAMS = p.encode("utf-8")

        # sending get request and saving the response as response object
        r = requests.post(url=URL, data=PARAMS, headers=headers)

        # extracting data in json format
        data = r.json()

        # extracting latitude, longitude and formatted address
        # of the first matching location

        X = data['data']['Result'][0]['X']
        Y = data['data']['Result'][0]['Y']
    except Exception as e:
        print(e)
        # print('exception ddamammnnnnn')
        print(street)
        return 0,0
    return X,Y

def net_xy_to_cords(x,y):
    default_x = 35.0743
    default_y = 32.93016

    if x > 100 and y > 100:
        URL = "https://epsg.io/trans?x=" + str(x) + "&y=" + str(y) + "&s_srs=2039&t_srs=4326"
        r = requests.get(url=URL)
        data = r.json()

        try:
            x = data['x']
            y = data['y']
        except:
            x = default_x
            y = default_y

    elif x < 30 and y < 30:
        x = default_x
        y = default_y
    return x, y