array = list(map(int,input().split()))

def quicksort(array,start,end):
    pivot = start
    left = start+1
    right = end

    while(left<=right):
        while(left<=pivot and array[left]<=array[pivot]):
            left+=1
        while(right>pivot and array[right]> array[pivot]):
            right-=1
        if(left>right):
            array[right],array[pivot] = array[pivot],array[left]
        else:
            array[right],array[left] = array[left],array[right]
    quicksort(array,0,right-1)
    quicksort(array, right - 1,end)
quicksort(array,0,len(array)-1)
print(array)


#!/usr/bin/env python
# _*_ coding:utf8 _*_
'''Created on 2016-12-10 @Author:Guolikai'''
import socket
#应用程序
'''WSGI（Web Server Gateway Interface）是一种规范，
它定义了使用python编写的web app与web server之间接口格式，实现web app与web server间的解耦。
python标准库提供的独立WSGI服务器称为wsgiref。'''
def handle_request(client):
    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n")
    client.send("Hello, Seven")

#服务程序
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 8000))
    sock.listen(5)

    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 17:26:21 2021

@author: Adity
"""

class Quiz:
    def __init__(self, sporsmaal, svar_liste, korrekt_svar):
        self.sporsmaal = sporsmaal
        self.svar_liste = svar_liste
        self.korrektsvar = korrekt_svar
# the lines above are the functions that are needed for the assignment to work

    def __str__(self):
        return f"{self.sporsmaal} \n {self.svar_liste}"

    def sjekk_svar(self):
        input_user = int(input("hva er svaret ditt? "))
        if self.korrektsvar == input_user:
            print("riktig \n")

        else:
            print("feil")

# these line from __str__ to sjekk_svar are used to produce when the result i correct or false

if __name__=="__main__":
    hovedstad_liste = ("stavenger trykk (0) \n oslo trykk (1) \n trondheim trykk (2) \n bergen trykk (3)")
    sporsmaal= ("hva er hovedstaden i Norge ?")

    hovedstad_i_norge = Quiz(sporsmaal, hovedstad_liste, 1)

    print(hovedstad_i_norge)

    hovedstad_i_norge.sjekk_svar()

########

    number_liste = ("1 trykk (0) \n 2 trykk (1) \n 3 trykk (2) \n 4 trykk (3)")
    sporsmaal = ("hva er 1 + 2")

    number = Quiz(sporsmaal, number_liste, 2)

    print(number)

    number.sjekk_svar()


#!flask/bin/python
from flask import Flask, request, jsonify, abort
from keras.models import load_model
import numpy as np
from keras.preprocessing import image

app = Flask(__name__)

@app.route('/')
def index():
    return "Hello, World!"

@app.route('/predict', methods=['POST'])
def create_task():
#    image_path = 'img_dataset/prediction_img/pipeorhome17.jpg'
    image_path =  request.files['file']
    Prediction_output = []

    product_model = load_model('product.h5')
    test_image = image.load_img(image_path,
                                target_size = (64, 64))

    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis = 0)
    product_output = product_model.predict(test_image)
    print(product_output)

    if product_output[0][0] == 1 :
        Prediction_output.append("Door")
    elif product_output[0][1] == 1:
         Prediction_output.append("Pipe")

    test_image = image.load_img(image_path,
                                target_size = (64, 64))
    model = load_model('material.h5')
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis = 0)
    output = model.predict(test_image)
    print(output)

    if output[0][0] == 1 :
        Prediction_output.append("Glass")
    elif output[0][1] == 1:
         Prediction_output.append("Plastic")
    elif output[0][2] == 1:
         Prediction_output.append("Steel")
    elif output[0][3] == 1:
         Prediction_output.append("Wood")

    test_image = image.load_img(image_path,
                                target_size = (64, 64))
    damage_model = load_model('damageOrNot.h5')
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis = 0)
    damage_output = damage_model.predict(test_image)
    print(damage_output)

    if damage_output[0][0] == 1 :
        Prediction_output.append("Damage")
    elif damage_output[0][1] == 1:
         Prediction_output.append("Not Damage")
    return jsonify({"data" : {
                              "Product":Prediction_output[0],
                              "Meterial":Prediction_output[1],
                              "Condition":Prediction_output[2]
                              }})

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


# FYS3150 - Project 4, 2020.
# Simple program for the 2x2 lattice.
# Calculating average values and thermodynamic quantities
# using analytical expressions.

import numpy as np

J = 1            # Magnetic material constant.
k = 1            # Boltzmann constant.
T = 1            # Temperature.
B = 1/(k*T)      # Beta.

# Partition function Z.
Z = 4*np.cosh(8*B*J) + 12

# Mean energy <E>.
E = 32*J/Z * np.sinh(-8*B*J)

# Mean square energy <E^2>.
E2 = 256*J**2/Z * np.cosh(8*B*J)

# Energy variance sigma_E^2.
E_var = E2 - E**2

# Heat capacity Cv.
Cv = E_var/(k*T**2)

# Mean magnetization <M>.
M = 0

# Mean abs magnetization <|M|>.
M_abs = 8/Z * (np.exp(8*B*J) + 2)

# Mean square magnetization <M^2>.
M2 = 32/Z * (np.exp(8*B*J) + 1)

# Magnetization variance sigma_M^2.
M_var = M2 - M**2

# Magnetic susceptibility X.
X = M_var/(k*T)

# Alternative way, magnetic susceptibility:
M_var_alt = M2 - M_abs*M_abs
X_alt = M_var_alt/(k*T)

print("Z = {:.3g}".format(Z))
print("E = {:.3g}".format(E))
print("E2 = {:.3g}".format(E2))
print("E_var = {:.3g}".format(E_var))
print("Cv = {:.3g}".format(Cv))
print("M = {:.3g}".format(M))
print("M_abs = {:.3g}".format(M_abs))
print("M2 = {:.3g}".format(M2))
print("M_var = {:.3g}".format(M_var))
print("X = {:.3g}".format(X))
print("X_alt = {:.3g}".format(X_alt))


import numpy as np

class NeuralNetwork:
    def __init__(self, layers, alpha=0.1):
        self.W = [] # List of weights matrices
        self.layers = layers # Network architecture, eg [2,2,1]
        self.alpha = alpha # Learning rate

        # Initialize the list of weights matrices
        # Loop from the first layer but not the last two layers
        # For each layer, add an extra node for the bias
        for i in np.arange(0, len(layers) - 2):
            w = np.random.randn(layers[i] + 1, layers[i + 1] + 1)
            # Scale w to normalize the variance of each neuron’s output
            self.W.append(w / np.sqrt(layers[i]))
        # For the last two layers, the inputs need a bias term but the output does not
        w = np.random.randn(layers[-2] + 1, layers[-1])
        # Scale w to normalize the variance of each neuron’s output
        self.W.append(w / np.sqrt(layers[-2]))

    def __repr__(self):
        # Return a string that represents the network architecture
        return "NeuralNetwork: {}".format("-".join(str(l) for l in self.layers))

    def sigmoid(self, x):
        # Sigmoid activation function
        return 1.0 / (1 + np.exp(-x))

    def sigmoid_deriv(self, x):
        # Derivative of the sigmoid function
        # Assume that x has already been passed through the sigmoid function
        return x * (1 - x)

    def fit(self, X, y, epochs=1000, displayUpdate=100):
        # Insert a column of 1's as the last entry in the feature matrix (bias)
        X = np.c_[X, np.ones((X.shape[0]))]

        # Loop over the epochs
        for epoch in np.arange(0, epochs):
            # Loop over the data points and train the network
            for (x, target) in zip(X, y):
                self.fit_partial(x, target)

            # Display a training update occasionally
            if epoch == 0 or (epoch + 1) % displayUpdate == 0:
                loss = self.calculate_loss(X, y)
                print("epoch={}, loss={:.7f}".format(epoch + 1, loss))

    def fit_partial(self, x, y):
        # Construct the list of output activations for each layer
        # The first activation is just the input feature vector itself
        A = [np.atleast_2d(x)]

        # FEEDFORWARD
        for layer in np.arange(0, len(self.W)):
            # Compute the net input to the current layer
            net = A[layer].dot(self.W[layer]) # The 'net input'
            out = self.sigmoid(net) # The 'net output'
            A.append(out) # Add the net output to the list of activations

        # BACKPROPAGATION
        # Compute the difference between the predicted label and the ground-truth label
        error = A[-1] - y
        # Apply the chain rule to build the list of deltas
        D = [error * self.sigmoid_deriv(A[-1])]
        for layer in np.arange(len(A) - 2, 0, -1):
            delta = D[-1].dot(self.W[layer].T)
            delta = delta * self.sigmoid_deriv(A[layer])
            D.append(delta)
        # Reverse the deltas since we looped in reverse
        D = D[::-1]

        # WEIGHT UPDATE PHASE
        for layer in np.arange(0, len(self.W)):
            # This is where the actual "learning" takes place
            self.W[layer] += -self.alpha * A[layer].T.dot(D[layer])

    def predict(self, X, addBias=True):
        # Initialize the output prediction as the input features
        p = np.atleast_2d(X)

        # Check to see if the bias column should be added
        if addBias:
            # Insert a column of 1's as the last entry in the feature matrix (bias)
            p = np.c_[p, np.ones((p.shape[0]))]

        # Loop over the network layers to compute the output prediction
        for layer in np.arange(0, len(self.W)):
            p = self.sigmoid(np.dot(p, self.W[layer]))

        # Return the predicted value
        return p

    def calculate_loss(self, X, targets):
        # Make predictions for the input data points then compute the loss
        targets = np.atleast_2d(targets)
        predictions = self.predict(X, addBias=False)
        loss = 0.5 * np.sum((predictions - targets) ** 2)
        return loss


from typing import List
import subprocess
import os
import random

from .IngestorInterface import IngestorInterface
from .Quote import Quote

class PdfIngestor(IngestorInterface):
    allowed_extensions = ['pdf']

    @classmethod
    def parse(cls, path: str) -> List[Quote]:
        if not cls.can_ingest(path):
            raise Exception('cannot ingest exception')

        tmp = f'.{random.randint(0,100000000)}.txt'
        call = subprocess.call(['pdftotext', path, tmp])

        file_ref = open(tmp, "r")
        quotes = []

        for line in file_ref.readlines():
            line = line.strip('\n\r').strip()
            if len(line) > 0:
                parse = line.split('-')
                new_quote = Quote(parse[0], parse[1])
                quotes.append(new_quote)

        file_ref.close()
        os.remove(tmp)
        return quotes


# import ipdb
# import os
# from glob import glob
# import pandas as pd
# import numpy as np
# import cv2
import datetime
from model import *
from util import *
from data.stl10_input import read_all_images, get_file

sys.stdout = Logger(filename=os.path.join(os.getcwd(), "stl-10_%s.log" % datetime.datetime.now().strftime("%Y-%m-%d_%H%M")))

n_epochs = 10000
learning_rate_val = 0.002
weight_decay_rate = 0.00001
momentum = 0.9
batch_size = 100
lambda_recon = 0.999
lambda_adv = 0.001

overlap_size = 7
hiding_size = 64
image_size = 128

result_path = '../results/stl-10/'
model_path = '../models/stl-10/'
pretrained_model_path = None

if not os.path.exists(model_path):
    os.makedirs(model_path)

if not os.path.exists(result_path):
    os.makedirs(result_path)

GRAYSCALE = False
# print "Loading Pretraining data..."
# X_pretrain = get_unlabeled_data(gray=GRAYSCALE)
print("Loading labeled data...")
# X_train, Y_train = get_training_data(gray=GRAYSCALE)
# X_test, Y_test = get_test_data(gray=GRAYSCALE)
# X_train = read_all_images(path_to_data=get_file("stl10_binary/stl_Xunlabeled_128px.bin"), img_size=image_size)
X_train = read_all_images(path_to_data=get_file("stl10_binary/stl_Xtrain_128px.bin"), img_size=image_size)
X_test = read_all_images(path_to_data=get_file("stl10_binary/stl_Xtest_128px.bin"), img_size=image_size)
# X_train = np.rollaxis(X_train, 3, 1)
# X_test = np.rollaxis(X_test, 3, 1)
# convert class vectors to binary class matrices, index from file starts at 1
# Y_train = np_utils.to_categorical(Y_train - 1, nb_classes)
# Y_test = np_utils.to_categorical(Y_test - 1, nb_classes)
print(X_train.shape)

is_train = tf.placeholder(tf.bool)

learning_rate = tf.placeholder(tf.float32, [])
images_tf = tf.placeholder(tf.float32, [batch_size, image_size, image_size, 3], name="images")

labels_D = tf.concat(0, [tf.ones([batch_size]), tf.zeros([batch_size])])
labels_G = tf.ones([batch_size])
images_hiding = tf.placeholder(tf.float32, [batch_size, hiding_size, hiding_size, 3], name='images_hiding')

model = Model()

bn1, bn2, bn3, bn4, bn5, bn6, debn4, debn3, debn2, debn1, reconstruction_ori, reconstruction = model.build_reconstruction(
    images_tf, is_train)
adversarial_pos = model.build_adversarial(images_hiding, is_train)
adversarial_neg = model.build_adversarial(reconstruction, is_train, reuse=True)
adversarial_all = tf.concat(0, [adversarial_pos, adversarial_neg])

# Applying bigger loss for overlapping region
mask_recon = tf.pad(tf.ones([hiding_size - 2 * overlap_size, hiding_size - 2 * overlap_size]),
                    [[overlap_size, overlap_size], [overlap_size, overlap_size]])
mask_recon = tf.reshape(mask_recon, [hiding_size, hiding_size, 1])
mask_recon = tf.concat(2, [mask_recon] * 3)
mask_overlap = 1 - mask_recon

# TODO plug in GCS loss here
loss_recon_ori = tf.square(images_hiding - reconstruction)
loss_recon_center = tf.reduce_mean(
    tf.sqrt(1e-5 + tf.reduce_sum(loss_recon_ori * mask_recon, [1, 2, 3])))  # Loss for non-overlapping region
loss_recon_overlap = tf.reduce_mean(
    tf.sqrt(1e-5 + tf.reduce_sum(loss_recon_ori * mask_overlap, [1, 2, 3]))) * 10.  # Loss for overlapping region
loss_recon = loss_recon_center + loss_recon_overlap

loss_adv_D = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(adversarial_all, labels_D))
loss_adv_G = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(adversarial_neg, labels_G))

loss_G = loss_adv_G * lambda_adv + loss_recon * lambda_recon
loss_D = loss_adv_D  # * lambda_adv

var_G = filter(lambda x: x.name.startswith('GEN'), tf.trainable_variables())
var_D = filter(lambda x: x.name.startswith('DIS'), tf.trainable_variables())

W_G = filter(lambda x: x.name.endswith('W:0'), var_G)
W_D = filter(lambda x: x.name.endswith('W:0'), var_D)

loss_G += weight_decay_rate * tf.reduce_mean(tf.pack(map(lambda x: tf.nn.l2_loss(x), W_G)))
loss_D += weight_decay_rate * tf.reduce_mean(tf.pack(map(lambda x: tf.nn.l2_loss(x), W_D)))

gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.4)
sess = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options))

optimizer_G = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=0.5)
grads_vars_G = optimizer_G.compute_gradients(loss_G, var_list=var_G)
# grads_vars_G = map(lambda gv: [tf.clip_by_value(gv[0], -10., 10.), gv[1]], grads_vars_G)
train_op_G = optimizer_G.apply_gradients(grads_vars_G)

optimizer_D = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=0.5)
grads_vars_D = optimizer_D.compute_gradients(loss_D, var_list=var_D)
# grads_vars_D = map(lambda gv: [tf.clip_by_value(gv[0], -10., 10.), gv[1]], grads_vars_D)
train_op_D = optimizer_D.apply_gradients(grads_vars_D)

saver = tf.train.Saver(max_to_keep=100)

tf.initialize_all_variables().run()

if pretrained_model_path is not None and os.path.exists(pretrained_model_path):
    saver.restore(sess, pretrained_model_path)

iters = 0

loss_D_val = 0.
loss_G_val = 0.

for epoch in range(n_epochs):
    # trainset.index = range(len(trainset))
    # trainset = trainset.ix[np.random.permutation(len(trainset))]

    for start, end in zip(
            range(0, len(X_train), batch_size),
            range(batch_size, len(X_train), batch_size)):

        images_ori = X_test[start:end]

        if iters % 2 == 0:
            images_ori = map(lambda img: img[:, ::-1, :], images_ori)

        is_none = np.sum(map(lambda x: x is None, images_ori))
        if is_none > 0: continue

        images_crops = map(lambda x: crop_random(x, x=32, y=32), images_ori)
        images, crops, _, _ = zip(*images_crops)

        # Printing activations every 10 iterations
        if iters % 100 == 0:
            test_images_ori = X_test[:batch_size]

            test_images_crop = map(lambda x: crop_random(x, x=32, y=32), test_images_ori)
            test_images, test_crops, xs, ys = zip(*test_images_crop)

            reconstruction_vals, recon_ori_vals, bn1_val, bn2_val, bn3_val, bn4_val, bn5_val, bn6_val, debn4_val, debn3_val, debn2_val, debn1_val, loss_G_val, loss_D_val = sess.run(
                [reconstruction, reconstruction_ori, bn1, bn2, bn3, bn4, bn5, bn6, debn4, debn3, debn2, debn1, loss_G,
                 loss_D],
                feed_dict={
                    images_tf: test_images,
                    images_hiding: test_crops,
                    is_train: False
                })

            # Generate result every 1000 iterations
            if iters % 100 == 0:
                ii = 0
                for rec_val, img, x, y in zip(reconstruction_vals, test_images, xs, ys):
                    rec_hid = (255. * (rec_val + 1) / 2.).astype(int)
                    rec_con = (255. * (img + 1) / 2.).astype(int)

                    rec_con[y:y + 64, x:x + 64] = rec_hid
                    # cv2.imwrite(os.path.join(result_path, 'img_' + str(ii) + '.' + str(int(iters / 100)) + '.jpg'),
                    #             rec_con)
                    ii += 1

                if iters == 0:
                    for test_image in test_images_ori:
                        test_image = (255. * (test_image + 1) / 2.).astype(int)
                        test_image[32:32 + 64, 32:32 + 64] = 0
                        # cv2.imwrite(os.path.join(result_path, 'img_' + str(ii) + '.ori.jpg'), test_image)

            print("========================================================================")
            print(bn1_val.max(), bn1_val.min())
            print(bn2_val.max(), bn2_val.min())
            print(bn3_val.max(), bn3_val.min())
            print(bn4_val.max(), bn4_val.min())
            print(bn5_val.max(), bn5_val.min())
            print(bn6_val.max(), bn6_val.min())
            print(debn4_val.max(), debn4_val.min())
            print(debn3_val.max(), debn3_val.min())
            print(debn2_val.max(), debn2_val.min())
            print(debn1_val.max(), debn1_val.min())
            print(recon_ori_vals.max(), recon_ori_vals.min())
            print(reconstruction_vals.max(), reconstruction_vals.min())
            print(loss_G_val, loss_D_val)
            print("=========================================================================")

            if np.isnan(reconstruction_vals.min()) or np.isnan(reconstruction_vals.max()):
                print("NaN detected!!")
                ipdb.set_trace()

        # Generative Part is updated every iteration
        _, loss_G_val, adv_pos_val, adv_neg_val, loss_recon_val, loss_adv_G_val, reconstruction_vals, recon_ori_vals, bn1_val, bn2_val, bn3_val, bn4_val, bn5_val, bn6_val, debn4_val, debn3_val, debn2_val, debn1_val = sess.run(
            [train_op_G, loss_G, adversarial_pos, adversarial_neg, loss_recon, loss_adv_G, reconstruction,
             reconstruction_ori, bn1, bn2, bn3, bn4, bn5, bn6, debn4, debn3, debn2, debn1],
            feed_dict={
                images_tf: images,
                images_hiding: crops,
                learning_rate: learning_rate_val,
                is_train: True
            })

        _, loss_D_val, adv_pos_val, adv_neg_val = sess.run(
            [train_op_D, loss_D, adversarial_pos, adversarial_neg],
            feed_dict={
                images_tf: images,
                images_hiding: crops,
                learning_rate: learning_rate_val / 10.,
                is_train: True
            })

        print("Iter:", iters, "Gen Loss:", loss_G_val, "Recon Loss:", loss_recon_val, "Gen ADV Loss:", loss_adv_G_val, "Dis Loss:", loss_D_val, "||||", adv_pos_val.mean(), adv_neg_val.min(), adv_neg_val.max())

        iters += 1

    saver.save(sess, model_path + 'model', global_step=epoch)
    learning_rate_val *= 0.99


import urllib.request,json
from .models import NewsSource, NewsArticle
import datetime#wanted to implement search article:later though

# Getting api key
api_key = None
# Getting the movie base url
base_url = None

def configure_request(app):
    global api_key,base_url
    api_key = app.config['API_KEY']
    base_url = app.config['API_BASE_URL']
def get_sources():
    '''
    Function gets the json response to url request
    '''
    get_sources_url = base_url.format(api_key)

    with urllib.request.urlopen(get_sources_url) as url:
        get_sources_data = url.read()
        get_sources_response = json.loads(get_sources_data)

        sources_results = None

        if get_sources_response['sources']:
            sources_results_list = get_sources_response['sources']
            sources_results = process_sources_results(sources_results_list)

    return sources_results

def process_sources_results(sources_list):
    '''
    Function  processes  sources result and transform them to a list of Objects
    Args:
        sources_list: A list of dictionaries that contain sources details
    Returns :
        sources_results: A list of newssources objects
    '''
    sources_results = []
    for source_item in sources_list:
        id = source_item.get('id')
        name = source_item.get('name')
        description = source_item.get('description')
        url = source_item.get('url')

        sources_object = NewsSource(id,name,description,url)
        sources_results.append(sources_object)

    return sources_results

def get_articles(source_name):
    search_movie_url = 'https://newsapi.org/v2/top-headlines?sources={}&apiKey={}'.format(source_name,api_key)
    with urllib.request.urlopen(search_movie_url) as url:
        search_articles_data = url.read()
        search_articles_response = json.loads(search_articles_data)

        search_articles_results = None

        if search_articles_response['articles']:
            search_articles_list = search_articles_response['articles']
            search_articles_results = process_articles_results(search_articles_list)

    return search_articles_results

def process_articles_results(articles_list):
    '''
    Function  processes  articles result and transform them to a list of Objects
    Args:
        articles_list: A list of dictionaries that contain articles details
    Returns :
        articles_results: A list of newssources objects
    '''
    articles_results = []
    for item in articles_list:
        name = item.get('source')
        author=item.get("author")
        title=item.get("title")
        description = item.get('description')
        url = item.get('url')
        urlToImage = item.get('urlToImage')
        publishedAt= item.get("publishedAt")

        articles_object = NewsArticle(name,author,title, description, url, urlToImage, publishedAt)
        articles_results.append(articles_object)

    return articles_results


import os, time, glob, shutil
from pytube import YouTube
import moviepy.editor as mp

def downloadYouTube(videourl, path):
    try:
        yt = YouTube(videourl)
        yt = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
        if not os.path.exists(path):
            os.makedirs(path)
        yt.download(path, filename=str(round(time.time() * 1000)))
    except Exception as e:
        print("Erro ao baixar link: {}".format(videourl))
        print("[Error]: {}".format(e))

def convertMp3(video):
    try:
        clip = mp.VideoFileClip(video)
        clip.audio.write_audiofile("{}.{}".format(str(round(time.time() * 1000)), "mp3"))
    except Exception as e:
        print("Erro ao converter: {}".format(video))
        print("[Error]: {}".format(e))

def moveToDirectory():
    dst = "./songs_{}".format(str(round(time.time())))
    songs = glob.glob("./*.mp3")

    if(len(songs) == 0):
         return False

    try:
        os.makedirs(dst)
    except:
        print("Erro ao criar pasta")

    for s in songs:
        shutil.move(s, dst)

# Pega lista de vídeos e quebra em arrays
videos = input("Cole os links separado por vírgula: ")
videos = videos.split(",")

path_video = "./videos_{}".format(str(round(time.time())))
for video in videos:
    downloadYouTube(video, path_video)

videos = glob.glob(path_video + "/*.mp4")

# percorre vídeos e converte em música
for video in videos:
    print(video)
    convertMp3(video)

# Move músicas para um diretorio gerado
moveToDirectory()


__version__ = '1.1.0'

##########################################################################
########################## MASTIFF Defaults ##############################
##########################################################################
# Radial functional forms f(r); see Stone's book for more details.
# Options are 'slater', 'stone', 'born-mayer-ip', 'born-mayer-sisa', or 'lennard-jones'
functional_form           =    'slater'

# Combination rule settings: Select combination rules for each A prefactors, B
# exponents, and C dispersion coefficients. Options are as follows:
#   aij: 'saptff', 'waldman-hagler5', 'geometric'
#   bij: 'saptff', 'waldman-hagler5', 'geometric_mean', 'arithmetic_mean'
#   cij: 'geometric'
aij_combination_rule      =    'geometric'
bij_combination_rule      =    'geometric_mean'
cij_combination_rule      =    'geometric'

# Weighting function settings
scale_weighting_temperature         =  5.0
weighted_rmse_cutoff                =  0.0

# Atomtype defaults
lone_pair_flags                     =  ['Du' , 'lp']
constrained_atomtypes               =  []
ignorecase                          =  False
##########################################################################
##########################################################################

##########################################################################
##################### Component-Specific Settings ########################
##########################################################################
# Electrostatic Settings: choose which multipole files the program should use,
# and specify whether or not each of the monomer configurations from the .sapt
# file have the same internal coordinates as the monomers in each .mom file
multipoles_suffix          =   '_ISA_L2.mom'
rigid_monomers             =    True
electrostatic_damping_type          =  'None'
include_slater_charge_penetration   =  False
include_rackers_radial_correction   =  False

# Exchange Settings: fit_bii selects whether or not to treat the ISA
# short-range exponents are soft- (fit_bii=True) or hard-constraints
# (fit_bii=False)
fit_bii                    =    False
exact_radial_correction             =  False

# Induction Settings: Choose the type and parameters for the polarization
# damping functions. Options for thole_damping_type are 'thole_tinker' and
# 'thole_linear', and good defaults for thole_param are the 0.33 and 2.0 with
# respect to the two different damping types
# respectively
thole_damping_type         =   'thole_tinker'
thole_param                =    0.36
springcon                           =  0.1
separate_induction_exponents        =  False
induction_damping_type              =  'Thole'
drude_method                        =  'multipole-gradient'

# Dispersion Settings: Choose which parameters to fit to the dispersion energies. Fit options
# include 'none' (to fit no parameters), 'anisotropic' (to just fit
# anisotropic dispersion parameters, but to leave isotropic dispersion
# coefficients unscaled), and 'all' (to fit both anisotropic and isotropic
# dispersion coefficients)
fit_dispersion             =    'anisotropic'

# Residual error Settings: If set to true, fits a final A parameter to errors in the total
# energy in an effort to reduce systematic errors in the total energy
fit_residuals              =    False
##########################################################################
##########################################################################

##########################################################################
######################### I/O Settings ###################################
##########################################################################
# Input Settings
inputdir = 'input/'

##########################################################################
##########################################################################


try:
	random_color_PATH = 'randomcolor.js'
	end_js_PATH = 'end.js'
	end_html_PATH = 'end.html'
	js_for = 'for(var i=0;i<50;i++)\n{'
	with open(random_color_PATH, 'r') as f:
		randomcolor_func = f.read()
	js_program = randomcolor_func
	alltext = []
	text = input('Enter the text you would like to rainbow-ify\n')
	while text!='':
		alltext.append(text)
		text = input()
	for text in alltext:
		js_program += "\nrainbowword(\"{}\");".format(text)
	with open(end_js_PATH, 'w')  as f:
		f.write(js_program)
	htmldoc = '<script type=\"text/javascript\">\n{}\n</script>'.format(js_program)
	with open(end_html_PATH, 'w')  as f:
		f.write(htmldoc)

except Exception as e:
	print(type(e), e)
	input()


# -*- coding: utf-8 -*-
# Copyright © IBM Corporation 2010, 2020
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use
"""Function implementation"""
import json
import logging
import re

from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError
from resilient_lib import validate_fields, ResultPayload

from fn_guardium_insights_integration.lib.insights_services import InsightsServices
from fn_guardium_insights_integration.lib.resilient_incident_operations import ResilientIncidentHelper
from fn_guardium_insights_integration.lib.time_conversions import compute_start_stop_times

class FunctionComponent(ResilientComponent):
    """Component that implements Resilient function 'function_guardium_insights_populate_breach_data_types"""

    def __init__(self, opts):
        """constructor provides access to the configuration options"""
        super(FunctionComponent, self).__init__(opts)
        self.options = opts.get("fn_guardium_insights_integration", {})

    @handler("reload")
    def _reload(self, event, opts):
        """Configuration options have changed, save new values"""
        self.options = opts.get("fn_guardium_insights_integration", {})

    @function("function_guardium_insights_populate_breach_data_types")
    def _function_guardium_insights_populate_breach_data_types_function(self, event, *args, **kwargs):
        """Function: A function to populate the incident breach data types."""
        try:
            # Get the function parameters:
            incident_id = kwargs.get("incident_id")  # number
            input_field_guardium_insights_who = kwargs.get("input_field_guardium_insights_who")  # text
            input_field_guardium_insights_what = kwargs.get("input_field_guardium_insights_what")  # text

            log = logging.getLogger(__name__)
            log.info("incident_id: %s", incident_id)
            log.info("input_field_guardium_insights_who: %s", input_field_guardium_insights_who)
            log.info("input_field_guardium_insights_what: %s", input_field_guardium_insights_what)

            yield StatusMessage("populating breach data types on incident: {}".format(incident_id))

            # Validating app.config settings
            validate_fields(["report_period", "report_fetch_size"], self.options)

            # Reading app.config settings
            report_period = self.options.get("report_period")
            report_fetch_size = self.options.get("report_fetch_size")

            # Initialize GI service
            gi_services = InsightsServices(self.options, log)

            # Initialize resilient service
            res_service = ResilientIncidentHelper(self.rest_client(), log)

            # Initialize Result payload.
            res_pay = ResultPayload("fn_guardium_insights_integration", **kwargs)
            res_status = False
            reason = ""

            _from_date, _to_date = compute_start_stop_times(report_period)

            # Converting string json to json object
            try:
                input_field_guardium_insights_what = json.loads(input_field_guardium_insights_what)
            except json.decoder.JSONDecodeError as err_msg:
                log.info("error converting what information to json object: {}".format(err_msg))
                input_field_guardium_insights_what = dict()

            _datasourceip = _port = None
            if input_field_guardium_insights_what:
                _datasourceip = input_field_guardium_insights_what.get("server_ip")
                _port = input_field_guardium_insights_what.get("server_port")
            if _datasourceip or _port:
                report_payload = gi_services.generate_report_payload(_from_date, _to_date, report_fetch_size,
                                                                     _datasourceip, _port)
                gi_list_reports = gi_services.list_all_reports()
                report_id = gi_services.get_report_id(gi_list_reports, "Classification")
                if report_id:
                    # Run classification report.
                    report_data = gi_services.run_report(report_payload)

                    # Correcting received response, if its not correct.
                    if isinstance(report_data, str):
                        report_data = re.sub(r"{.result.*\{.total_number_of_rows.*\}", "", report_data)
                        report_data = json.loads(report_data)

                    # Populating breach data types
                    res_service.populate_breach_data_types(incident_id, report_data)

                    reason = "populating breach data types completed: incident ID{}".format(incident_id)
                else:
                    reason = "--------Classification report not found in Guardium Insight system---------"
                    log.info(reason)
            else:
                reason = "--------Data SourceIP and Port Information is not available in the incident---------"
                log.info(reason)
            yield StatusMessage("populating breach data types completed: incident ID{}".format(incident_id))

            fun_result = res_pay.done(res_status, {}, reason)
            # Produce a FunctionResult with the results
            yield FunctionResult(fun_result)
        except Exception as fn_err:
            yield FunctionError(fn_err)


from optproblems.cec2005 import F6
import math
from random import uniform, randrange, gauss
from copy import deepcopy

class Subject:
    def __init__(self, dimension, parameters):
        self.dim = dimension
        if len(parameters) != dimension:
            print("Wrong dimension")
            raise Exception
        self.param = parameters
        self.rank = math.inf  # ponieważ minimalizuję - nim mniejsze tym lepiej

# Pseudokod algorytmu ewolucyjnego
# incjalizacja_parametrow
# t=0
# P0 = i n i c j a c j a ( )
# ocena ( P0 )
# while ( ! k o n i e c )
# Tt = s e l e k c j a ( Pt )
# Ot = o p e r a t o r y _ g e n e t y c z n e ( Tt )
# ocena ( Ot )
# Pt+1 = s u k c e s j a ( Ot , Pt )
# t = t+1

def init(dim, populationSize):
    # inicjalizuje obiekty na parametry z przediału [-100, 100]
    population = []
    for i in range(populationSize):
        population.append(Subject(dim, [uniform(-100, 100) for _ in range(dim)]))

    return population
    # return [
    #     Subject(dim, [1, 10, 100]),
    #     Subject(dim, [-100, -100, -100]),
    #     Subject(dim, [-20, 5, 70]),
    #     Subject(dim, [7, -77, -22]),
    #     Subject(dim, [5, 25, 97])
    #     ]

def evaluate(pop, dim):
    # obliczam ocenę obiektu
    f = F6(dim)
    for sub in pop:
        sub.rank = f(sub.param)

def select(pop, n):     # n ozn. ile osobników należy wybrać
    new_pop = []
    for _ in range(n):
        s1 = pop[randrange(len(pop))]
        s2 = pop[randrange(len(pop))]
        new_pop.append(deepcopy(s1) if s1.rank <= s2.rank else deepcopy(s2))

    return new_pop

def geneticOperators(pop):
    # Mutacje obiektów
    sigma = 0.3
    for subject in pop:
        for i in range(len(subject.param)):
            param = subject.param[i]
            param = gauss(param, sigma)
            while param < -100 or param > 100:
                param = gauss(param, sigma)

            subject.param[i] = param

    return pop

def succession(new_pop, old_pop, k):
    return new_pop[:k] + old_pop[:len(old_pop)-k]

def evolutionaryAlgorithm(dim, populationSize, B):
    P = init(dim, populationSize)
    evaluate(P, dim)
    P.sort(key=lambda x: x.rank)

    for t in range(int(B/populationSize)):
        T = select(P, populationSize*2//3)

        O = geneticOperators(T)
        evaluate(O, dim)
        O.sort(key=lambda x: x.rank)

        P = succession(O, P, len(O)//2)
        P.sort(key=lambda x: x.rank)

    return P


"""Support for Verisure Smartplugs."""
from __future__ import annotations

from time import monotonic
from typing import Callable, Iterable

from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN
from .coordinator import VerisureDataUpdateCoordinator

async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: Callable[[Iterable[Entity]], None],
) -> None:
    """Set up Verisure alarm control panel from a config entry."""
    coordinator: VerisureDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
    async_add_entities(
        VerisureSmartplug(coordinator, serial_number)
        for serial_number in coordinator.data["smart_plugs"]
    )

class VerisureSmartplug(CoordinatorEntity, SwitchEntity):
    """Representation of a Verisure smartplug."""

    coordinator: VerisureDataUpdateCoordinator

    def __init__(
        self, coordinator: VerisureDataUpdateCoordinator, serial_number: str
    ) -> None:
        """Initialize the Verisure device."""
        super().__init__(coordinator)
        self.serial_number = serial_number
        self._change_timestamp = 0
        self._state = False

    @property
    def name(self) -> str:
        """Return the name or location of the smartplug."""
        return self.coordinator.data["smart_plugs"][self.serial_number]["area"]

    @property
    def unique_id(self) -> str:
        """Return the unique ID for this alarm control panel."""
        return self.serial_number

    @property
    def is_on(self) -> bool:
        """Return true if on."""
        if monotonic() - self._change_timestamp < 10:
            return self._state
        self._state = (
            self.coordinator.data["smart_plugs"][self.serial_number]["currentState"]
            == "ON"
        )
        return self._state

    @property
    def available(self) -> bool:
        """Return True if entity is available."""
        return (
            super().available
            and self.serial_number in self.coordinator.data["smart_plugs"]
        )

    def turn_on(self, **kwargs) -> None:
        """Set smartplug status on."""
        self.coordinator.verisure.set_smartplug_state(self.serial_number, True)
        self._state = True
        self._change_timestamp = monotonic()

    def turn_off(self, **kwargs) -> None:
        """Set smartplug status off."""
        self.coordinator.verisure.set_smartplug_state(self.serial_number, False)
        self._state = False
        self._change_timestamp = monotonic()


import tensorflow as tf
import tensorflow.contrib.layers as layers
from tensorflow.python.framework import tensor_shape
# import tensorflow.math_ops as math_ops
import numpy as np
#parameters for training
GRAD_CLIP              = 500.0
RNN_SIZE               = 512
ACTION_REPR_SIZE       = 50
MSG_REPR_SIZE          = 100
num_agents             = 2
msg_length             = 10

#Used to initialize weights for policy and value output layers (Do we need to use that? Maybe not now)
def normalized_columns_initializer(std=1.0):
    def _initializer(shape, dtype=None, partition_info=None):
        out = np.random.randn(*shape).astype(np.float32)
        out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True))
        return tf.constant(out)
    return _initializer

class ACNet:
    '''
    Define actor and critic network
    '''
    def __init__(self, scope, a_size, num_agents, trainer_A,trainer_C,TRAINING,GRID_SIZE,GLOBAL_NET_SCOPE):

        with tf.variable_scope(scope):

            self.num_agents = num_agents
            self.actor_inputs = tf.placeholder(shape=[None,self.num_agents,2,GRID_SIZE,GRID_SIZE], dtype=tf.float32)
            self.my_actor_input = tf.transpose(self.actor_inputs, perm=[0,1,3,4,2])

            self.critic_inputs = tf.placeholder(shape=[None,self.num_agents,4,GRID_SIZE,GRID_SIZE], dtype=tf.float32)
            self.my_critic_input = tf.transpose(self.critic_inputs, perm=[0,1,3,4,2])

            self.reconstruction_error = tf.placeholder(shape=[None,self.num_agents,msg_length], dtype=tf.float32)

            self.actions             = tf.placeholder(shape=[None, self.num_agents], dtype=tf.int32)
            self.actions_onehot      = tf.one_hot(self.actions, a_size, dtype=tf.float32)

            actions_other             = tf.reverse(self.actions,[1])
            actions_other_onehot      = tf.one_hot(actions_other, a_size, dtype=tf.float32)

            self.msgs_init = np.zeros((self.num_agents,msg_length))

            self.policies, self.msgs_out, self.values = self._build_net(self.my_actor_input,
                                                                    self.my_critic_input,
                                                                    actions_other_onehot,
                                                                    self.reconstruction_error,
                                                                    GRID_SIZE,
                                                                    RNN_SIZE,
                                                                    TRAINING,
                                                                    a_size)

            if TRAINING:

                self.target_v            = tf.placeholder(tf.float32, [None,self.num_agents], 'Vtarget')
                self.advantages          = tf.placeholder(shape=[None,self.num_agents], dtype=tf.float32)

                self.responsible_outputs = tf.reduce_sum(self.policies * self.actions_onehot, [2])

                # Loss Functions
                with tf.name_scope('c_loss'):
                    self.c_loss    = tf.reduce_sum(tf.square(self.target_v - self.values))

                # something to encourage exploration
                self.entropy       = - tf.reduce_sum(self.policies * tf.log(tf.clip_by_value(self.policies,1e-10,1.0)))/self.num_agents
                self.policy_loss   = - tf.reduce_sum(tf.log(tf.clip_by_value(self.responsible_outputs,1e-15,1.0)) * self.advantages)

                with tf.name_scope('a_loss'):
                    self.a_loss          = self.policy_loss - self.entropy * 0.01 #+ 0.25*self.blocking_loss #+ self.msg_loss

                # Get gradients from local network using local losses and
                # normalize the gradients using clipping
                local_a_vars         = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope+'/actor')
                local_c_vars         = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope+'/critic')
                self.a_grads         = tf.gradients(self.a_loss, local_a_vars)
                self.c_grads         = tf.gradients(self.c_loss, local_c_vars)
                self.a_var_norms     = tf.global_norm(local_a_vars)
                self.c_var_norms     = tf.global_norm(local_c_vars)
                a_grads, self.a_grad_norms = tf.clip_by_global_norm(self.a_grads, GRAD_CLIP)
                c_grads, self.c_grad_norms = tf.clip_by_global_norm(self.c_grads, GRAD_CLIP)

                # Apply local gradients to global network
                global_actor_vars        = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, GLOBAL_NET_SCOPE+'/actor')
                global_critic_vars       = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, GLOBAL_NET_SCOPE+'/critic')
                self.apply_a_grads       = trainer_A.apply_gradients(zip(a_grads, global_actor_vars))
                self.apply_c_grads       = trainer_C.apply_gradients(zip(c_grads, global_critic_vars))

#             self.homogenize_weights = update_target_graph(str(scope)+'/qvaluesB', str(scope)+'/qvalues')
        print("Hello World... From  "+str(scope))     # :)

    def _build_net(self,actor_inputs,critic_inputs,actions_other,recon_error,GRID_SIZE,RNN_SIZE,TRAINING,a_size):
        w_init   = layers.variance_scaling_initializer()

        with tf.variable_scope('actor'):

            # Reshape so that instead of [T,#agents,...] it's [T*#agents,...]
            actor_inputs_reshaped = tf.reshape(actor_inputs, [-1,GRID_SIZE,GRID_SIZE,2])
            conv1_actor    =  layers.conv2d(inputs=actor_inputs_reshaped,   padding="SAME", num_outputs=RNN_SIZE//4,  kernel_size=[3, 3],   stride=1, data_format="NHWC", weights_initializer=w_init,activation_fn=tf.nn.relu)
            conv1a_actor   =  layers.conv2d(inputs=conv1_actor,   padding="SAME", num_outputs=RNN_SIZE//4,  kernel_size=[3, 3],   stride=1, data_format="NHWC", weights_initializer=w_init,activation_fn=tf.nn.relu)
            conv1a_actor_reshaped = tf.reshape(conv1a_actor, [-1,self.num_agents,conv1a_actor.shape[1]*conv1a_actor.shape[2]*conv1a_actor.shape[3]])

            # We need to concatenate them along axis=2
            rnn_in_actor   = tf.concat([conv1a_actor_reshaped, recon_error], axis=2)

            routing_cell = RoutingRNN(RNN_SIZE, MSG_REPR_SIZE, self.num_agents, a_size, msg_length)
            seq_length = tf.shape(actor_inputs)[:1]

            self.msgs_in = tf.placeholder(shape = [self.num_agents,msg_length], dtype = tf.float32)

            rnn_output, msgs_out = tf.nn.dynamic_rnn(routing_cell, rnn_in_actor, initial_state=self.msgs_in, dtype = tf.float32,time_major=True)
            policies = tf.squeeze(rnn_output)

        with tf.variable_scope('critic'):

            critic_inputs_reshaped = tf.reshape(critic_inputs, [-1,4,GRID_SIZE,GRID_SIZE])
            conv1_critic    =  layers.conv2d(inputs=critic_inputs_reshaped,   padding="SAME", num_outputs=RNN_SIZE//4,  kernel_size=[3, 3],   stride=1, data_format="NHWC", weights_initializer=w_init,activation_fn=tf.nn.relu)
            conv1a_critic   =  layers.conv2d(inputs=conv1_critic,   padding="SAME", num_outputs=RNN_SIZE//4,  kernel_size=[3, 3],   stride=1, data_format="NHWC", weights_initializer=w_init,activation_fn=tf.nn.relu)

            h1_critic = tf.reshape(conv1a_critic, [-1,self.num_agents,conv1a_critic.shape[1]*conv1a_critic.shape[2]*conv1a_critic.shape[3]])

            # flat_critic = layers.flatten(conv1a_critic)
            # h1_critic = tf.reshape(tf.nn.relu(flat_critic),[critic_inputs.shape[0],self.num_agents,-1])

            # msg_action = tf.concat([msg_input,actions_other],1)
            action_layer = layers.fully_connected(inputs=actions_other, num_outputs=ACTION_REPR_SIZE)
            hidden_input_critic = tf.concat([h1_critic, action_layer],2)

            h1_critic = layers.fully_connected(inputs=hidden_input_critic,  num_outputs=RNN_SIZE)

            values        = tf.squeeze(layers.fully_connected(inputs=h1_critic, num_outputs=1, weights_initializer=normalized_columns_initializer(1.0), biases_initializer=None, activation_fn=None))

        return policies, msgs_out, values

class RoutingRNN(tf.nn.rnn_cell.RNNCell):

    """
    RNN cell to be used for diff comms learning.

    One time-step evaluation of this RNN takes the as "input" the processed observations for each agent, and takes as "state" the messages TO each agent from last time step
    Returns as "output": policy
    Returns as "state": messages TO each agent from current time step (to be recieved at next time step, when state is fed back into this RNN cell)
    """

    def __init__(self, num_units, msg_repr_size, num_agents, a_size, msg_length, reuse=None):
        super(RoutingRNN, self).__init__(_reuse=reuse)
        self._num_units  = num_units
        self._msg_length = msg_length
        self._msg_repr_size = msg_repr_size
        self._a_size     = a_size

    @property
    def state_size(self):
        # return (1,self._num_agents, self._msg_length) #the leading 1 is because tf wants RNN inputs to be in shape (batch_size, time, etc...)
        return self._msg_length

    @property
    def output_size(self):

        return self._a_size

    def call(self, inputs_and_recon_error, state):
        """
        inputs_and_recon_error = observations for each agent after being processed by conv layers, concatenated with message reconstruction error
        state = messages TO each agent, generated at previous time step

        """
        # seperate back out original inputs and reconstruction error
        inputs = inputs_and_recon_error[:,:-self.state_size]
        recon_error = inputs_and_recon_error[:,-self.state_size:]

        # add reconstruction error to msg
        msg = state
        #begin processing messages into message representation
        msg_repr = layers.fully_connected(inputs=msg, num_outputs=self._msg_repr_size)

        # concatenate inputs and message representation
        hidden_input=tf.concat([inputs,msg_repr],1, name="hidden_input")

        # compute policy and pre_msg
        h1 = layers.fully_connected(inputs=hidden_input,  num_outputs=self._num_units, activation_fn=tf.nn.relu)
        policy_layer = layers.fully_connected(inputs=h1,  num_outputs=self._a_size, weights_initializer=normalized_columns_initializer(1./float(self._a_size)), biases_initializer=None, activation_fn=None)
        policy       = tf.nn.softmax(policy_layer,name="policy")
        msg_layer    = layers.fully_connected(inputs=h1, num_outputs=self._msg_length, weights_initializer=normalized_columns_initializer(1./float(self._a_size)), biases_initializer=None, activation_fn=None)
        pre_msg          = tf.nn.sigmoid(msg_layer) # these are messages FROM each agent (i.e. pre_msg[:,i]= message from agent i)

        # compute messages TO each agent (i.e. msg[:,i]=message that will become input to agent i at next time step)
        # Here we simply assume agent 1 sends to 2 and vise versa, so we simply reverse the messages along the agents dimension
        msg_out = tf.reverse(pre_msg, [0]) + recon_error #tf.matmul(recipient_mat,pre_msg)

        return policy, msg_out


from baseband import mark5b
import numpy as np
from scipy.stats.stats import pearsonr
import astropy.units as u
import matplotlib.pyplot as plt
from astropy.time import Time
from pulsar.predictor import Polyco

with open('starttimes.txt','r') as f:
	start_times = f.read()
	start_times = start_times.split('\n')[:-1]

filename = 'close_pairs.txt'
with open(filename,'r') as f:
	GP_times = f.read()
	GP_times = GP_times.split('\n')[:-1]
	GP_times_utc1 = [entry.split()[0] for entry in GP_times]
	GP_times_utc2 = [entry.split()[1] for entry in GP_times]
	GP_times_unix1 = np.array([Time(t).unix-Time(start_times[0]).unix for t in GP_times_utc1])
	GP_times_unix2 = np.array([Time(t).unix-Time(start_times[0]).unix for t in GP_times_utc2])
	scan_nos1 = [entry.split()[2] for entry in GP_times]
	scan_nos2 = [entry.split()[3] for entry in GP_times]
	#S_Ns = [entry.split()[2] for entry in GP_times]

'''
with open('close_pairs.txt','w') as f:
   for b in close_GP_pairs:
		f.write('{} {} {} {} {}'.format(b[0],b[1],b[2],b[3],b[4])

#Getting close pairs from time strings

close_GP_pairs = np.zeros(shape = (0,7))
#def get_time_lag():
for i,ts1 in enumerate(GP_times_utc):
	for j in range(len(GP_times_utc)-i):
		ts2 = GP_times_utc[i+j]
		t_gp1 = Time(ts1)
		t_gp2 = Time(ts2)
		dt = t_gp2-t_gp1
		if abs(dt.sec)<10 and abs(dt.sec)>0.01:
			close_GP_pairs = np.append(close_GP_pairs,np.array([[ts1,ts2,scan_nos[i],scan_nos[i+j],dt.sec]]),0)
			print i,j

print close_GP_pairs.shape
'''

def find_phase(t_GPs,scan_no):
	t0 = Time(start_times[scan_no-1])
	t_GP = Time(t_GPs)
	psr_polyco = Polyco('polyco_new.dat')
	phase_pol = psr_polyco.phasepol(t0)
	phase = np.remainder(phase_pol(t_GP.mjd), 1)
	return phase

phases1 = []
phases2 = []
#def plot_phase_time():
for i,t1 in enumerate(GP_times_utc1):
	phases1.append(find_phase(t1,int(scan_nos1[i])))
	phases2.append(find_phase(GP_times_utc2[i],int(scan_nos2[i])))
phases1 = [phase1%0.8 if phase1>=0.8 else phase1+0.2 for phase1 in phases1]
phases2 = [phase2%0.8 if phase2>=0.8 else phase2+0.2 for phase2 in phases2]
phases1 = np.array(phases1)
phases2 = np.array(phases2)
phases1 = (phases1-1.0/30010*GP_times_unix1)%1.0
phases2 = (phases2-1.0/30010*GP_times_unix2)%1.0
plt.figure()
plt.plot(phases1,GP_times_unix1,'o')
plt.plot(phases2,GP_times_unix2,'x')
plt.show()

#plot_phase_time()

'''
# The function below is for adding scan numbers to a txt file with times but no scan numbers

def write_scan_no():
	with open('starttimes.txt','r') as f:
		times = f.read()
		times = times.split('\n')[:-1]
		print len(times)
	text_name = 'all7_sorted.txt'
	with open(text_name, 'r') as f:
		text = f.read()
		text_lines = text.split('\n')[:-1]
		print len(text_lines)

	scan_nos = ['0']*len(text_lines)
	for line_no,line in enumerate(text_lines):
		strings = line.split()
		t_GP = Time(strings[0])
		for i,start_time in enumerate(times):
			ts = Time(start_time)
			ts_next = Time(times[i+1])
			if t_GP.mjd >ts.mjd and t_GP.mjd <ts_next.mjd:
				scan_nos[line_no] = format(i+1,'02d')
				print i
				break
	print scan_nos

with open('all7_sorted1.txt','w') as f:
	for i in range(len(text_lines)):
		f.write('{} {}\n'.format(scan_nos[i],text_lines[i]))
'''


# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *

class EntityCommon:
	"""
	服务端Cell实体的基础接口类
	"""
	def __init__(self):
		#定时器管理器
		self.timerMgr = {}

	def getCurrRoomBase(self):
		"""
		获得当前space的entity baseMailbox
		"""
		return KBEngine.globalData["Room_%i" % self.spaceID]

	def getCurrRoom(self):
		"""
		获得当前space的entity
		"""
		roomBase = self.getCurrRoomBase()
		if roomBase is None:
			return roomBase

		return KBEngine.entities.get(roomBase.id, None)

	def addTimerMgr(self, initialOffset, repeatOffset, userArg):

		tid = self.addTimer(initialOffset, repeatOffset, userArg)

		#先清理可能重复的定时器
		self.delTimerMgr(userArg)

		if repeatOffset > 0:
			self.timerMgr[userArg] = tid

	def delTimerMgr(self, userArg):

		if userArg == 0:
			DEBUG_MSG("%r clean all timers" % (self.className))

			for tt in self.timerMgr.values():
				self.delTimer(tt)

			self.timerMgr.clear()

		elif userArg in self.timerMgr:

			tid = self.timerMgr.pop(userArg)

			self.delTimer(tid)


import pygame
from pathfinder import Graph, AStar
from copy import copy
import player

# for position checking
MARGIN = 48

GRID_INCREMENT = player.GRID_INCREMENT
NODE_STEP = player.node_step

class AIHANDLER:
    def __init__(self, red_player, blue_player, health_pack, node_graph):
        self.red_player = red_player
        self.blue_player = blue_player
        self.health_pack = health_pack

        # the neural_net variable will test a primitive neural network, for now it is null
        self.neural_net = None
        self.score = 0

        # bits to determine what the player is doing
        self.CHASING = 2
        self.SHOOTING = 4
        self.FLEEING = 8
        self.RESTING = 16

        self.current_action = 2

        # bits to determine where player is located in regards to opponent
        self.red_is_left = 2
        self.red_is_right = 4
        self.red_is_up = 8
        self.red_is_down = 16

        self.current_position = 2

        self.node_graph = node_graph
        self.a_star = AStar(copy(self.node_graph))

        self.finding_path = False
        self.getting_coordinates = True

        self.subprogram = None

    def run_battle(self):

       if self.subprogram == "states":
            if self.current_action == self.RESTING:
                return
            # first we check if the agent is healthy, if not we run away
            if not self.red_player.is_player_healthy():
                self.current_action = self.FLEEING

            if self.current_action == self.CHASING:
                 self.determine_movement()
            # check the agent's current state and act accordingly
            elif self.current_action == self.SHOOTING:
                self.shoot_bullets()
                self.determine_movement()
            elif self.current_action == self.FLEEING:
                self.run_away()

                # print(self.current_action)
       elif self.subprogram == "pathfinding":
           self.determine_movement()

    def determine_movement(self):
        if self.subprogram == "pathfinding":
            # if our path list is currently empty do nothing
            if not self.a_star.final_path_list:
                self.finding_path = False
                return

            # find the next node in our path for the red_player to travel to
            next_node_coordinate = ((self.a_star.final_path_list[0].x), (self.a_star.final_path_list[0].y))
            # place the player's coordinates into variables for checking
            red_coordinate = ((self.red_player.rect.centerx), (self.red_player.rect.centery))

            # until we reach the node keep moving towards it
            if 2 <= abs(red_coordinate[0] - next_node_coordinate[0]) or 2 <= abs(red_coordinate[1] - next_node_coordinate[1]):
                self.red_player.move_to_next_node(next_node_coordinate)
            else:
                # then remove the current node so we can move toward the next node
                print("popping Node #: " + str(self.a_star.final_path_list[0].name))
                self.a_star.final_path_list.pop(0)

        if self.subprogram == "states":
            turning_around = False
            blue_coordinate = ((self.blue_player.rect.centerx), (self.blue_player.rect.centery))
            red_coordinate = ((self.red_player.rect.centerx), (self.red_player.rect.centery))

            # should we chase the player? if we are too far away then we will chase
            if (100 <= abs(blue_coordinate[0] - red_coordinate[0]) or 100 <= abs(blue_coordinate[0] - red_coordinate[0]))\
                and not self.finding_path:
                self.find_node(blue_coordinate[0], blue_coordinate[1])
                self.blue_player.previous_x = blue_coordinate[0]
                self.blue_player.previous_y = blue_coordinate[1]
                self.current_action = self.CHASING
            elif 300 <= abs(self.blue_player.previous_x - blue_coordinate[0]) or\
                100 <= abs(self.blue_player.previous_y - blue_coordinate[1]):
                self.change_course(blue_coordinate)
            elif 5 > abs(blue_coordinate[0] - red_coordinate[0]) or 5 > abs(blue_coordinate[1] - red_coordinate[1]):
                self.move_freely(blue_coordinate)
            else:
                self.current_action = self.SHOOTING

    def move_through_path(self):
        # if our path list is currently empty do nothing
        if not self.a_star.final_path_list:
            self.finding_path = False
            return

        # find the next node in our path for the red_player to travel to
        next_node_coordinate = ((self.a_star.final_path_list[0].x), (self.a_star.final_path_list[0].y))
        # place the player's coordinates into variables for checking
        red_coordinate = ((self.red_player.rect.centerx), (self.red_player.rect.centery))

        # until we reach the node keep moving towards it
        if 1 <= abs(red_coordinate[0] - next_node_coordinate[0]) or 1 <= abs(red_coordinate[1] - next_node_coordinate[1]):
            self.red_player.move_to_next_node(next_node_coordinate)
        else:
            # then remove the current node so we can move toward the next node
            if self.subprogram == "pathfinding":
                print("popping Node #: " + str(self.a_star.final_path_list[0].name))
            self.a_star.final_path_list.pop(0)

    def change_course(self, blue_coordinate):
        if self.a_star.final_path_list:
            self.a_star.start_node_index = self.find_node_index(self.a_star.final_path_list[0])
        del self.a_star.final_path_list
        self.find_node(blue_coordinate[0], blue_coordinate[1])
        self.blue_player.previous_x = blue_coordinate[0]
        self.blue_player.previous_y = blue_coordinate[1]

    def shoot_bullets(self):
        bullet_List = pygame.sprite.Group()

        red_coordinate = ((self.red_player.rect.centerx), (self.red_player.rect.centery))

        blue_coordinate = ((self.blue_player.rect.centerx), (self.blue_player.rect.centery))

        if red_coordinate[0] + MARGIN >= blue_coordinate[0] and red_coordinate[0] - MARGIN <= blue_coordinate[0]:
            # red player is above blue player
            if red_coordinate[1] < blue_coordinate[1] - MARGIN:
                self.current_position = self.red_is_up

            # red player is below blue player
            elif red_coordinate[1] > blue_coordinate[1] + MARGIN:
                self.current_position = self.red_is_down
        else:
            if red_coordinate[0] > blue_coordinate[0]:
                self.current_position = self.red_is_right
            elif red_coordinate[0] < blue_coordinate[0]:
                self.current_position = self.red_is_left

        if self.current_position == self.red_is_left:
            bullet_List.add(self.red_player.shoot_right())
        elif self.current_position == self.red_is_right:
            bullet_List.add(self.red_player.shoot_left())
        elif self.current_position == self.red_is_up:
            bullet_List.add(self.red_player.shoot_down())
        elif self.current_position == self.red_is_down:
            bullet_List.add(self.red_player.shoot_up())

        if self.finding_path:
            self.move_through_path()

        return bullet_List

    def run_away(self):

        health_pack_coordinate = (self.health_pack.rect.centerx, self.health_pack.rect.centery)
        red_coordinate = (self.red_player.rect.centerx, self.red_player.rect.centery)

        if not self.finding_path:
            self.find_node(health_pack_coordinate[0], health_pack_coordinate[1])

        if GRID_INCREMENT * NODE_STEP >= abs(red_coordinate[0] - health_pack_coordinate[0]) and \
           GRID_INCREMENT * NODE_STEP >= abs(red_coordinate[1] - health_pack_coordinate[1]):
            self.move_freely(health_pack_coordinate)
        elif self.finding_path:
            self.move_through_path()

        if self.red_player.rect.colliderect(self.health_pack):
            self.red_player.hit_points += 100
            self.red_player.set_healthy()
            print("picked up health pack")
            self.current_action = self.CHASING

    def move_freely(self, target):
        self.red_player.chase_object(target)

        return False

    def find_node(self, x_coordinate, y_coordinate):
        # we make a deep copy of our graph because we will be removing nodes when we run the A*
        # and we don't want it to change our original graph
        #self.a_star.unvisited = copy(self.node_graph)
        search_index = 0
        if x_coordinate > 550 and y_coordinate > 220:
            search_index = len(self.node_graph) / 2
        # for each node in our graph, we check the coordinates to see if it's "close enough" to our user coordinates
        for node in self.node_graph[search_index:]:
            if GRID_INCREMENT * NODE_STEP >= abs(node.x - x_coordinate) and GRID_INCREMENT * NODE_STEP >= abs(node.y - y_coordinate):
                print("matched coordinates with node# " + str(node.name))
                # use the matched node as the end node which we find the path to
                self.a_star.find_path(node)
                # our next start node will be our current end_node for the next time we find a path
                self.a_star.start_node_index = self.node_graph.index(node)
                self.finding_path = True
                self.getting_coordinates = False
                break

    def find_node_index(self, start_node):
        node_name = start_node.name
        for node in self.node_graph:
            if node.name == node_name:
                return self.node_graph.index(node)

    def getAction(self):
        new_action = input("ENTER COMMAND: ")

        if new_action.upper() == "CHASE":
            self.current_action = self.CHASING


"""Contains custom exceptions."""

class CommandCancel(Exception):
    """Cancel a command."""

    def __init__(self, status=None, ui=None, title=None, description=None):
        self.status = status
        self.ui = ui
        self.title = title
        self.description = description


from django import template
register = template.Library()

#$ def (value, arg):
# var|foo:"bar"    var is the variable/value, bar is the arg
@register.filter(name='streakBoo')
def streakBoo(value):
    if (value[0] == 'W'):
        return True
    else:
        return False

@register.filter(name='win')
def win(value, args):
    if (value > args):
        return True
    else:
        return False

@register.filter(name='getAddress')
def getAddress(value):
    dict  = {
    "ATL": '1 Philips Dr. Atlanta, GA 30303',
    "BKN": '620 Atlantic Ave, Brooklyn, NY 11217',
    "BOS": '100 Legends Way, Boston, MA 02114',
    "CHA": '333 E Trade St, Charlotte, NC 28202',
    "CHI": '1901 W Madison St, Chicago, IL 60612',
    "CLE": '1 Center Ct, Cleveland, OH 44115',
    "DAL": '2500 Victory Ave, Dallas, TX 75219',
    "DEN": '1000 Chopper Cir, Denver, CO 80204',
    "DET": '6 Championship Dr, Auburn Hills, MI 48326',
    "GS": '7000 Coliseum Way, Oakland, CA 94621',
    "HOU": '1510 Polk St, Houston, TX 77002',
    "IND": '125 S Pennsylvania St, Indianapolis, IN 46204',
    "LAC": '1111 S Figueroa St, Los Angeles, CA 90015',
    "LAL": '1111 S Figueroa St, Los Angeles, CA 90015',
    "MEM": '191 Beale St, Memphis, TN 38103',
    "MIA": '601 Biscayne Blvd, Miami, FL 33132',
    "MIL": '1001 N 4th St, Milwaukee, WI 53203',
    "MIN": '600 First Avenue North, Minneapolis, MN 55403',
    "NOP": '1501 Dave Dixon Dr, New Orleans, LA 70113',
    "NYK": '4 Pennsylvania Plaza, New York, NY 10001',
    "OKC": '100 W Reno Ave, Oklahoma City, OK 73102',
    "ORL": '400 W Church St #200, Orlando, FL 32801',
    "PHI": '3601 S Broad St, Philadelphia, PA 19148',
    "PHX": '201 E Jefferson St, Phoenix, AZ 85004',
    "POR": '1 N Center Ct St, Portland, OR 97227',
    "SAC": '1 Sports Pkwy, Sacramento, CA 95834',
    "SA": '1 AT&T Center, San Antonio, TX 78219',
    "TOR": '40 Bay Street Toronto, Ontario, Canada',
    "UTA": '301 W South Temple, Salt Lake City, UT 84101',
    "WAS": '601 F St Nw, Washington, DC 20004',
    }
    return dict[value]

@register.filter(name='teamName')
def teamName(value):
    dict = {
    "ATL": 'Atlanta Hawks',
    "BKN": 'Brooklyn Nets',
    "BOS": 'Boston Celtics',
    "CHA": 'Charlotte Hornets',
    "CHI": 'Chicago Bulls',
    "CLE": 'Cleveland Cavaliers',
    "DAL": 'Dallas Mavericks',
    "DEN": 'Denver Nuggets',
    "DET": 'Detriot Pistons',
    "GS": 'Golden State Warriors',
    "HOU": 'Houston Rockets',
    "IND": 'Indiana Pacers',
    "LAC": 'LA Clippers',
    "LAL": 'LA Lakers',
    "MEM": 'Memphis Grizzlies',
    "MIA": 'Miami Heat',
    "MIL": 'Milwaukee Bucks',
    "MIN": 'Minnesota Timberwolves',
    "NOP": 'New Orleans Pelicans',
    "NYK": 'New York Knicks',
    "OKC": 'Oklahoma City Thunder',
    "ORL": 'Orlando Magic',
    "PHI": 'Philadelphia 76ers',
    "PHX": 'Phoenix Suns',
    "POR": 'Portland TrailBlazers',
    "SAC": 'Sacramento Kings',
    "SA": 'San Antonio Spurs',
    "TOR": 'Toronto Raptors',
    "UTA": 'Utah Jazz',
    "WAS": 'Washington Wizards',
    }
    return dict[value]


import datetime

now = datetime.datetime.now()

# c)
msgNum = 0

def logg():
    navn = input("Oppgi navn : ")
# g    tid = input("Oppgi tid : ")
    tid = "{:02d}:{:02d}".format(now.hour, now.minute) #! [FIXED] Gir kun ett siffer. F.eks 17:3 for 17:03
    melding = input("Melding : ")
# g    print('Klokken {} sendte {} følgende melding: "{}"'.format(tid, navn, melding))

    # c) utvid programmet:
    global msgNum
    msgNum += 1
    print('Msg {}, {} sendte {} følgende melding: "{}"'.format(msgNum, tid, navn, melding))

def main ():
    while msgNum < 6:
        logg()

main()


"""initial database migration

Revision ID: d9781a6cf2e1
Revises:
Create Date: 2019-01-25 11:17:43.281258

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "d9781a6cf2e1"
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "blacklist_tokens",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("token", sa.String(length=500), nullable=False),
        sa.Column("blacklisted_on", sa.DateTime(), nullable=False),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("token"),
    )
    op.create_table(
        "category",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("name", sa.String(length=32), nullable=True),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_category_name"), "category", ["name"], unique=False)
    op.create_table(
        "option",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("title", sa.String(), nullable=True),
        sa.Column("question_id", sa.Integer(), nullable=True),
        sa.ForeignKeyConstraint(["question_id"], ["question.id"], use_alter=True),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_option_title"), "option", ["title"], unique=False)
    op.create_table(
        "user",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("email", sa.String(length=255), nullable=False),
        sa.Column("registered_on", sa.DateTime(), nullable=False),
        sa.Column("admin", sa.Boolean(), nullable=False),
        sa.Column("public_id", sa.String(length=100), nullable=True),
        sa.Column("username", sa.String(length=50), nullable=True),
        sa.Column("password_hash", sa.String(length=100), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("email"),
        sa.UniqueConstraint("public_id"),
        sa.UniqueConstraint("username"),
    )
    op.create_table(
        "vendor",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("name", sa.String(length=32), nullable=True),
        sa.Column("description", sa.String(), nullable=True),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_vendor_name"), "vendor", ["name"], unique=False)
    op.create_table(
        "exam",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("name", sa.String(length=32), nullable=True),
        sa.Column("category_id", sa.Integer(), nullable=True),
        sa.Column("vendor_id", sa.Integer(), nullable=True),
        sa.Column("timestamp", sa.DateTime(), nullable=False),
        sa.ForeignKeyConstraint(["category_id"], ["category.id"]),
        sa.ForeignKeyConstraint(["vendor_id"], ["vendor.id"]),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_exam_name"), "exam", ["name"], unique=False)
    op.create_table(
        "question",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("title", sa.String(), nullable=True),
        sa.Column("answer_id", sa.Integer(), nullable=True),
        sa.Column("exam_id", sa.Integer(), nullable=True),
        sa.Column("qtype", sa.Integer(), nullable=True),
        sa.Column("timestamp", sa.DateTime(), nullable=False),
        sa.ForeignKeyConstraint(["answer_id"], ["option.id"]),
        sa.ForeignKeyConstraint(["exam_id"], ["exam.id"]),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_question_title"), "question", ["title"], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f("ix_question_title"), table_name="question")
    op.drop_table("question")
    op.drop_index(op.f("ix_exam_name"), table_name="exam")
    op.drop_table("exam")
    op.drop_index(op.f("ix_vendor_name"), table_name="vendor")
    op.drop_table("vendor")
    op.drop_table("user")
    op.drop_index(op.f("ix_option_title"), table_name="option")
    op.drop_table("option")
    op.drop_index(op.f("ix_category_name"), table_name="category")
    op.drop_table("category")
    op.drop_table("blacklist_tokens")
    # ### end Alembic commands ###


#
# This file is part of pyasn1-alt-modules software.
#
# Created by Russ Housley with assistance from asn1ate v.0.6.0.
#
# Copyright (c) 2021, Vigil Security, LLC
# License: http://vigilsec.com/pyasn1-alt-modules-license.txt
#
# TimeStampedData
#
# ASN.1 source from:
# https://www.rfc-editor.org/rfc/rfc5544.txt
#

from pyasn1.type import char
from pyasn1.type import constraint
from pyasn1.type import namedtype
from pyasn1.type import namedval
from pyasn1.type import opentype
from pyasn1.type import tag
from pyasn1.type import univ

from pyasn1_alt_modules import rfc3161
from pyasn1_alt_modules import rfc4998
from pyasn1_alt_modules import rfc5280
from pyasn1_alt_modules import rfc5652

MAX = float('inf')

otherEvidenceMap = { }

# Imports from RFC 5652

Attribute = rfc5652.Attribute

# Imports from RFC 5280

CertificateList = rfc5280.CertificateList

# Imports from RFC 3161

TimeStampToken = rfc3161.TimeStampToken

# Imports from RFC 4998

EvidenceRecord = rfc4998.EvidenceRecord

# TimeStampedData

class Attributes(univ.SetOf):
    componentType = Attribute()
    subtypeSpec = constraint.ValueSizeConstraint(1, MAX)

class TimeStampAndCRL(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('timeStamp', TimeStampToken()),
        namedtype.OptionalNamedType('crl', CertificateList())
    )

class TimeStampTokenEvidence(univ.SequenceOf):
    componentType = TimeStampAndCRL()
    subtypeSpec = constraint.ValueSizeConstraint(1, MAX)

class OtherEvidence(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('oeType', univ.ObjectIdentifier()),
        namedtype.NamedType('oeValue', univ.Any(),
            openType=opentype.OpenType('oeType', otherEvidenceMap))
    )

class Evidence(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('tstEvidence',
            TimeStampTokenEvidence().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 0))),
        namedtype.NamedType('ersEvidence',
            EvidenceRecord().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 1))),
        namedtype.NamedType('otherEvidence',
            OtherEvidence().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 2)))
    )

class MetaData(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('hashProtected', univ.Boolean()),
        namedtype.OptionalNamedType('fileName', char.UTF8String()),
        namedtype.OptionalNamedType('mediaType', char.IA5String()),
        namedtype.OptionalNamedType('otherMetaData', Attributes())
    )

class TimeStampedData(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('version',
            univ.Integer(namedValues=namedval.NamedValues(('v1', 1)))),
        namedtype.OptionalNamedType('dataUri', char.IA5String()),
        namedtype.OptionalNamedType('metaData', MetaData()),
        namedtype.OptionalNamedType('content', univ.OctetString()),
        namedtype.NamedType('temporalEvidence', Evidence())
    )

id_ct_timestampedData = univ.ObjectIdentifier('1.2.840.113549.1.9.16.1.31')

# Update the CMS Content Type Map in rfc5652.py

_cmsContentTypesMapUpdate = {
    id_ct_timestampedData: TimeStampedData(),
}

rfc5652.cmsContentTypesMap.update(_cmsContentTypesMapUpdate)


def parse_and_validate_terms(request, default_value=None):
    """Extract search terms from request.

    Args:
        request: HTTP request.
        default_value:

    Returns:
        terms if given.
    Raises:
        ValueError: otherwise.
    """
    terms = request.rel_url.query.get("q", default_value)
    if terms:
        return terms.upper()
    return terms

def check_short_terms_and_no_param(search_params):
    """Prevent performance issues by refusing query terms less than 3 characters.
    Accept less than 3 characters if at least one parameter is filled.
    Except matching size, because this param always has a default value.

    Args:
        search_params: dict of query parameters

    Raises:
        ValueError.
    """
    min_chars_in_terms = 3
    if (
        search_params.terms is not None
        and len(search_params.terms) < min_chars_in_terms
        and all(
            val is None
            for val in [
                param_value
                for param, param_value in vars(search_params).items()
                if param not in ["terms", "page", "per_page", "matching_size"]
            ]
        )
    ):
        raise ValueError(
            "3 caractères minimum pour les termes de la requête "
            + "(ou utilisez au moins un filtre)"
        )


cat = 'tool'

# Import base
from base import *

# Magnet attributes
vendptn = 'siemens|philips|general%selectric|\Wge\W' % (delimptn)
scanptn = 'magnet|scan(?:ner)?|mri|field|system'
magptn = '(?:%s|%s)' % (vendptn, scanptn)

tesptn = '(?:tesla|t(?!\w|%s=|%s\d+|\())' % (delimptn, delimptn)
numptn = '[\s\(](\d{1,2}\.?\d{,2})(?!=\d)'

fieldptn = [
  numptn + delimptn + tesptn,
]

fieldptn = [re.compile(ptn, srcflags) for ptn in fieldptn]

sigptn = 'p%s[<=>]+%s\d?\.\d+' % delimrep(2)
sigptn = re.compile(sigptn, srcflags)

def estfield(txt):

  field = []
  gstrs = []

  for ptn in fieldptn:
    matches = re.finditer(ptn, txt)
    if matches:
      for match in matches:
        shortcon = getcontext(match=match, txt=txt, ncharpre=50, ncharpost=50)
        if not re.search(magptn, shortcon, re.I):
          continue
        postcon = getcontext(match=match, txt=txt, ncharpre=0, ncharpost=50)
        if re.search(sigptn, postcon):
          continue
        try:
          gfloat = float(match.groups()[0])
          gstr = str(gfloat)
          context = getcontext(match=match, txt=txt)
          context = UnicodeDammit(context).unicode
          if minfield <= gfloat <= maxfield and gstr not in gstrs:
            field.append((gstr, context))
            gstrs.append(gstr)
        except:
          pass

  return field

tags = {}

# Field strength
tags['field'] = [estfield]

# Vendors
tags['ge'] = [
  re.compile('\WGE\W'),
  'general%selectric' % (delimptn),
]

tags['siemens'] = [
  'siemens'
]

tags['philips'] = [
  'philips',
]

tags['bruker'] = [
  'bruker',
]

tags['varian'] = [
  'varian',
]

tags['shimadzu'] = [
  'shimadzu',
]

tags['marconi'] = [
    'marconi',
]


from rest_framework import serializers

from bank.models import BankUserAdministration
from core import models

class BankCustomersSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.BankCustomer
        fields = '__all__'
        read_only_fields = (
            'id',
            'user',
            'created_at',
            'updated_at',
        )

class BankTransferSerializer(serializers.ModelSerializer):
    iban_from_username = serializers.SerializerMethodField('get_iban_from_username')
    iban_to_username = serializers.SerializerMethodField('get_iban_to_username')

    def get_iban_to_username(self, obj):
        return str(obj.iban_to.account_owned_by)

    def get_iban_from_username(self, obj):
        return str(obj.iban_from.account_owned_by)

    class Meta:
        model = models.BankTransfer
        fields = (
            'id',
            'iban_from',
            'iban_from_username',
            'iban_to',
            'iban_to_username',
            'is_success',
            'is_open',
            'use_case',
            'executionlog',
            'execute_datetime',
            'amount',
            'created_at',
            'updated_at',
            'created_by',
        )

        # fields = '__all__'

        read_only_fields = (
            'id',
            'created_at',
            'updated_at',
            'executionlog',
            'is_open',
            'is_success',
            'created_by',
            # 'iban_from'
        )

    def create(self, validated_data):
        request = self.context.get('request', None)
        user = request.user
        adminstating_ibans = [x.iban for x in BankUserAdministration(user).adminstrating_accounts]
        if not validated_data['iban_from'].iban in adminstating_ibans:
            raise serializers.ValidationError({"detail": "Not an account from user"})
        validated_data['created_by'] = request.user.bank_customer
        return super(BankTransferSerializer, self).create(validated_data=validated_data)

class BankAccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.BankAccount
        fields = (
            "name",
            "iban",
            "account_owned_by",
            "balance",
            "updated_at",
            "created_at",
        )
        read_only_fields = (
            "id",
            "iban",
            "account_owned_by",
            "balance",
            'created_at',
            'updated_at',
        )


from django.urls import path

from . import views

urlpatterns = [
    path('', views.VeiculosList.as_view(), name='listar-veiculos'),
    path(r'novo/', views.VeiculosNew.as_view(), name='novo-veiculo'),
    path(r'<int:pk>/', views.VeiculosEdit.as_view(), name='editar-veiculo'),
    path(r'excluir/<int:pk>/', views.VeiculosDelete.as_view(), name='deletar-veiculo'),
]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Union

from neodroidagent.agents import PolicyGradientAgent
from neodroidagent.common import ParallelSession
from neodroidagent.common.architectures.distributional.categorical import CategoricalMLP
from neodroidagent.configs.test_reference.base_dicrete_test_config import *

__author__ = "Christian Heider Nielsen"

from neodroidagent.entry_points.session_factory import session_factory
from warg import GDKC

CONFIG_NAME = __name__

CONFIG_FILE_PATH = pathlib.Path(__file__)

RENDER_ENVIRONMENT = True

OPTIMISER_SPEC = GDKC(torch.optim.Adam, lr=3e-4)
SCHEDULER_SPEC = None

POLICY_ARCH_SPEC = GDKC(constructor=CategoricalMLP, hidden_layers=128)

# RENDER_FREQUENCY = 1

pg_config = globals()

def pg_run(
    skip_confirmation: bool = True,
    environment_type: Union[bool, str] = True,
    *,
    config=None,**kwargs

) -> None:
    if config is None:
        config = pg_config

    session_factory(
        PolicyGradientAgent,
        config,
        session=ParallelSession,
        skip_confirmation=skip_confirmation,
        environment=environment_type,**kwargs
    )

def pg_test(config=None,**kwargs) -> None:
    if config is None:
        config = pg_config
    pg_run(environment_type="gym", config=config,**kwargs)

if __name__ == "__main__":
    pg_test()


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: C:\repositorios\web\django-microsip-base\django_microsip_base\django_microsip_base\settings\dev_plus.py
# Compiled at: 2019-09-30 12:05:46
from common import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MODO_SERVIDOR = 'PRUEBAS'
MICROSIP_VERSION = '2017'
EXTRA_MODULES = ()
DJANGO_APPS += ('django_extensions', 'werkzeug_debugger_runserver')
from .common import get_microsip_extra_apps
MICROSIP_EXTRA_APPS, EXTRA_APPS = get_microsip_extra_apps(EXTRA_MODULES, is_dev=True)
INSTALLED_APPS = DJANGO_APPS + MICROSIP_MODULES + MICROSIP_EXTRA_APPS
ROOT_URLCONF = 'django_microsip_base.urls.dev'
STATICFILES_DIRS = (
 BASE_DIR + '/static/',)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-

"""The script for setting up sqlfluff."""

from __future__ import absolute_import
from __future__ import print_function

import io
import configparser
from os.path import dirname
from os.path import join

from setuptools import setup

# Get the global config info as currently stated
# (we use the config file to avoid actually loading any python here)
config = configparser.ConfigParser()
config.read(['src/sqlfluff/config.ini'])
version = config.get('sqlfluff', 'version')

def read(*names, **kwargs):
    """Read a file and return the contents as a string."""
    return io.open(
        join(dirname(__file__), *names),
        encoding=kwargs.get('encoding', 'utf8')
    ).read()

setup(
    name='sqlfluff',
    version=version,
    license='MIT License',
    description='Modular SQL Linting for Humans',
    long_description=read('README.md') + "\n\n---\n\n" + read('CHANGELOG.md'),
    # Make sure pypi is expecting markdown!
    long_description_content_type='text/markdown',
    author='Alan Cruickshank',
    author_email='alan@designingoverload.com',
    url='https://github.com/alanmcruickshank/sqlfluff',
    python_requires=">=3.5",
    keywords=['sqlfluff', 'sql', 'linter'],
    project_urls={
        # Homepage not ready yet.
        # 'Homepage': 'https://www.sqlfluff.com'
        'Documentation': 'https://docs.sqlfluff.com',
        'Source': 'https://github.com/alanmcruickshank/sqlfluff',
    },
    # Specify all the seperate packages, modules come automatically
    packages=['sqlfluff', 'sqlfluff.cli', 'sqlfluff.dialects', 'sqlfluff.parser', 'sqlfluff.rules'],
    package_dir={"": "src"},
    include_package_data=True,
    classifiers=[
        # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 3 - Alpha',
        # 'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: Unix',
        'Operating System :: POSIX',
        'Operating System :: Microsoft :: Windows',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Utilities',
        'Topic :: Software Development :: Quality Assurance'
    ],
    install_requires=[
        # Core
        'click>=2.0',
        "colorama>=0.3",
        'configparser',
        'oyaml',
        'Jinja2',
        # Used for diffcover plugin
        "diff-cover>=2.5.0,<3.0",
        # Used for performance profiling
        'bench-it',
        # Used for .sqlfluffignore
        "pathspec"
    ],
    extras_require={
        # eg:
        #   'rst': ['docutils>=0.11'],
        #   ':python_version=="2.6"': ['argparse'],
    },
    entry_points={
        'console_scripts': [
            'sqlfluff = sqlfluff.cli.commands:cli',
        ],
        'diff_cover': [
            'sqlfluff = sqlfluff.diff_quality_plugin'
        ],
    },
)


import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

a=int(input())
Ka=int(input())
Ki=int(input())
Ko=int(input())
for i in range(1,a,1):
    t=(float(i)/12)
    d=((np.log(50.0 / Ka) + (0.1 + (0.3 ** 2 / 2)) * (float(i) / 12)) / (0.3 * (float(i) / 12)**0.5))
    DeltaA= norm.cdf(d)
    di=((np.log(50.0 / Ki) + (0.1 + (0.3 ** 2 / 2)) * (float(i) / 12)) / (0.3 * (float(i) / 12)**0.5))
    DeltaI= norm.cdf(di)
    do=((np.log(50.0 / Ko) + (0.1 + (0.3 ** 2 / 2)) * (float(i) / 12)) / (0.3 * (float(i) / 12)**0.5))
    DeltaO= norm.cdf(do)
    x='3'
    plt.plot(0,0,x)
    plt.plot(0,0.5,x)
    plt.plot(0,1,x)
    plt.plot([t],[DeltaA],x)
    plt.plot([t],[DeltaI],x)
    plt.plot([t],[DeltaO],x)

plt.axis([0, 5, 0, 1])
plt.title('Graph of Delta Against Time to Maturity')
plt.ylabel('Delta')
plt.xlabel('Time to Maturity')
plt.ylabel('Delta')
plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# 定义默认参数一定要劳记一点： 必须指定不变对象
def enrool(name, gender, age=6, city='Beijing'):
    print(name)
    print(gender)
    print(age)
    print(city)

enrool('liuji', '男')
enrool('liuji', '男', 11, 'huanggang')
enrool('liuji', '男', city='--huanggang--')

def add_end(L=None):
    if L is None:
        L = []
    L.append('END')
    return L

print(add_end())
print(add_end())
print(add_end())

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

print(calc(1,2,3,4))
nums = [1,2,3]
print(calc(*nums))

def person(name, age, **kw):
    if 'city' in kw:
        print('city-------------------------------')
    print('name:', name, 'age:', age, 'other:', kw)

# 参数定义的顺序必须是：必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
# **表示遍历入参
person('liuji', 30)
person('liuji', 30, city='beigjing', gender='男')
person('liuji', 30, **{'city':'beigjing', 'gender':'男'})

# 必选参数, 必选参数 , 默认参数 , 可变参数, 关键字参数。
def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

# 必选参数, 必选参数 , 默认参数 , 命名关键字参数, 关键字参数。
def f2(a, b, c=0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)


__author__ = 'Shashank Kapadia'
__copyright__ = '2015 AIR Worldwide, Inc.. All rights reserved'
__version__ = '1.0'
__interpreter__ = 'Python 2.7.9'
__maintainer__ = 'Shashank kapadia'
__email__ = 'skapadia@air-worldwide.com'
__status__ = 'Production'

from ModelControl.main import *

if __name__ == "__main__":

    start = time.time()
    print('Comparing......')
    path_to_dir = ('G:/MC-IR11')
    models = listdir(path_to_dir)
    results_source = []
    results_test = []
    results_log = []
    for dirs in models:
        path_to_model = path_to_dir + '/' + dirs + '/Results'
        files = listdir(path_to_model)
        results_source.append([str(path_to_model + '/' + filename) for filename in files if filename.endswith('.csv')])
        results_test.append([str(path_to_model + '/56228/' + filename) for filename in files if filename.endswith('.csv')])
        results_log.append([str(path_to_model + '/56228/Log-' + filename) for filename in files if filename.endswith('.csv')])
    results_source = [item for sublist in results_source for item in sublist]
    results_test = [item for sublist in results_test for item in sublist]
    results_log = [item for sublist in results_log for item in sublist]

    processes = [mp.Process(target=modelControl, args=(results_source[i], results_test[i], results_log[i])) for i in range(len(results_source))]
    for p in processes:
        p.start()

    for p in processes:
        p.join()

    print('********** Process Complete: ' + str(time.time() - start) + ' Seconds **********')


import math
N, a, b = map(int,input().split())
Round = 1
rc = math.ceil(math.log2(N))
list1 = [ y for y in range(N)]
k = N
a = a -1
b = b -1
for i in range( rc - 1):
    list1 = []

    if a % 2 ==0:
        if a - b == -1:
            break
    if a % 2 ==1:
        if a - b == +1:
            break

    Round = Round + 1
    if ( k ) % 2 == 1: # 리스트 길이가 홀수
        for j in range( (k // 2) + 1 ):
            list1.append(j)
        a = a // 2
        b = b // 2
        k = len(list1)

    else:
        for j in range( k // 2 ):
            list1.append(j)
        k = len(list1)
        a = a // 2
        b = b // 2

    if a % 2 ==0:
        if a - b == -1:
            break
    if a % 2 ==1:
        if a - b == +1:
            break

if N == 2:
    print(1)
else:
    print(Round)


def election_donations_analysis(input, output1, output2):
    from pyspark.sql import SparkSession
    import pyspark.sql.functions as F
    spark = SparkSession.builder.getOrCreate()

    reader = spark.read
    reader.option("header",True).option("inferSchema",True)
    df = reader.csv(input)

    cand_info = ['cand_id', 'cand_nm']

    grouped_df = df.groupBy(cand_info)\
        .agg(
            F.count(F.when(F.col('contb_receipt_amt') >= '0', 1)).alias("NumDon"),
        F.sum('contb_receipt_amt').alias("Total_cntrb"),
        F.countDistinct(F.when(F.col('contb_receipt_amt') >= '0', F.array('contbr_nm', 'contbr_zip', 'contbr_employer', 'contbr_occupation'))).alias('UnqCtb'),
        F.mean("contb_receipt_amt").alias("Mean"),
        F.stddev("contb_receipt_amt").alias("SD"),
        F.count(F.when((F.col('contb_receipt_amt') < '50') & (F.col('contb_receipt_amt') >= '0'), 1)).alias("smCtb")
        ).withColumn("%", (F.col("smCtb") /  F.col("NumDon"))*100)

    grouped_df.sort(F.desc('cand_id')).show()
    grouped_df.write.format('csv').mode('overwrite').save(output1)

    required_cand_ids = ["P80001571", "P80000722"]
    df_6 = df.filter(df.cand_id.isin(required_cand_ids)).filter("contb_receipt_amt >= '0'").select('cand_nm','contb_receipt_amt')

    df_6.sort(F.desc('contb_receipt_amt')).show()
    df_6.coalesce(1).write.format('csv').mode('overwrite').save(output2)

def files_from_args():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input', metavar= "input")
    parser.add_argument('-o1', '--output1', metavar= "output1")
    parser.add_argument('-o2', '--output2', metavar= "output2")
    args = parser.parse_args()
    return (args.input, args.output1, args.output2)

if __name__ == "__main__":
    inputfile, outputfile1, outputfile2 = files_from_args()
    election_donations_analysis(inputfile, outputfile1, outputfile2)


__author__ = 'Nick'
import os
from flask import Flask, redirect, request, render_template, url_for, jsonify, Response
from forms import CampaignForm, AssetForm, PageForm, ContainerForm
from model import Page, Container, Campaign, Assets, ContainerAssets
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.secret_key = 'some_sekcret_hablah_bababooey1-023'

IMAGE_UPLOADS = 'static/upload/images/'
VIDEO_UPLOADS = 'static/upload/videos/'

app.config['VIDEOS'] = VIDEO_UPLOADS
app.config['IMAGES'] = IMAGE_UPLOADS

ALLOWED_IMAGES = set(['png', 'jpg', 'jpeg', 'gif'])
ALLOWED_VIDEOS = set(['mp4', 'webm'])

def allowed_image(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_IMAGES

def allowed_video(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_VIDEOS

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('base.html')

@app.route('/page/<id>', methods=['GET'])
def page(id):
    form = ContainerForm()
    pg = Page.get(Page.id == id)
    return render_template('page.html', form=form, page=pg)

@app.route('/pages', methods=['GET'])
def pages():
    form = PageForm()
    page = Page.select()
    return render_template('pages.html', pages=page, form=form)

@app.route('/campaigns', methods=['GET'])
def campaigns():
    asset_form = AssetForm()
    form = CampaignForm()
    camps = Campaign.select()
    return render_template('campaigns.html', form=form, asset_form=asset_form, camps=camps)

@app.route('/src/<id>', methods=['GET'])
def src(id):
    camp = Campaign.get(Campaign.id == id)
    js = render_template('test.js', file=("/"+app.config['IMAGES'] + camp.file))
    return Response(js, mimetype='text/javascript')

@app.route('/test/<id>')
def test(id):
    return render_template('test.html', id=id)

@app.route('/_container', methods=['POST'])
def _container():
    form = ContainerForm()
    pageid = request.form["page"]

    if form.validate_on_submit():
        container = Container.create(name=form.name.data, page=pageid)

        return redirect(url_for('page', id=pageid))

    pg = Page.get(Page.id == pageid)
    return render_template('pages.html', page=pg, form=form)

@app.route('/_page', methods=['POST'])
def _page():
    form = PageForm()

    if form.validate_on_submit():
        page = Page.create(name=form.name.data,
                           url=form.url.data)

        return redirect(url_for('pages'))

    page = Page.select()
    return render_template('pages.html', pages=page, form=form)

@app.route('/_asset', methods=['POST'])
def _asset():
    form = AssetForm()
    if form.validate_on_submit():
        file = request.files['file']
        if file and allowed_image(file.filename):
            filename = secure_filename(file.filename)
            directory = app.config['IMAGES']
            if not os.path.exists(directory):
                os.makedirs(directory)
            file.save(os.path.join(directory, filename))
            campaign = request.form["campaign"]

            asset = Assets.create(name=form.name.data,
                                  src=filename,
                                  campaign=campaign,
                                  type=1)

            return redirect(url_for('campaigns'))

    camps = Campaign.select()
    return render_template('campaigns.html', form=CampaignForm(), asset_form=form, camps=camps)

@app.route('/_campaign', methods=['POST', 'GET'])
def _campaign():
    form = CampaignForm()

    if form.validate_on_submit():
        camp = Campaign.create(name=form.name.data,
                               start=form.start.data,
                               end=form.end.data)

        return redirect(url_for('campaigns'))

    camps = Campaign.select()
    return render_template('campaigns.html', form=form, asset_form=AssetForm(), camps=camps)

# START
if __name__ == '__main__':
    app.run(debug=True, host="127.0.0.1")