# dense_vae.py: Variational autoencoder with fully-connected layers
#
# (C) 2019, Daniel Mouritzen

from typing import Dict, Optional, Sequence, Type, Union

import gin
import numpy as np
import tensorflow as tf

from project.util.tf import auto_shape
from project.util.tf.losses import kl_divergence, mse

from .basic import SequentialBlock, ShapedDense
from .wrappers import ExtraBatchDim

class DenseVAEEncoder(auto_shape.Layer):
    def __init__(self,
                 latent_shape: Sequence[int],
                 num_units: int = 100,
                 num_layers: int = 1,
                 activation: Union[None, str, Type[tf.keras.layers.Layer]] = auto_shape.ReLU,
                 batch_norm: bool = False,
                 name: str = 'vae_encoder',
                 ) -> None:
        super().__init__()
        self._encoder = SequentialBlock(num_units,
                                        num_layers,
                                        activation,
                                        batch_norm,
                                        initial_layers=[auto_shape.Flatten(name=f'{name}_flatten')],
                                        name=f'{name}_sequential')
        self._encoder.add(ShapedDense([2] + list(latent_shape), name=f'{name}_shaped_dense'))

    def call(self, input: tf.Tensor) -> Dict[str, tf.Tensor]:
        output = self._encoder(input)
        assert output.shape[1] == 2
        mean, log_var = output[:, 0], output[:, 1]
        sample = tf.random.normal(mean.shape) * tf.exp(log_var * .5) + mean
        return {'mean': mean, 'log_var': log_var, 'sample': sample}

class DenseVAEDecoder(auto_shape.Layer):
    def __init__(self,
                 output_shape: Sequence[int],
                 num_units: int = 100,
                 num_layers: int = 1,
                 activation: Union[None, str, Type[tf.keras.layers.Layer]] = auto_shape.ReLU,
                 batch_norm: bool = False,
                 name: str = 'vae_decoder',
                 ) -> None:
        super().__init__()
        self._decoder = SequentialBlock(num_units,
                                        num_layers,
                                        activation,
                                        batch_norm,
                                        initial_layers=[auto_shape.Flatten(name=f'{name}_flatten')],
                                        name=f'{name}_sequential')
        self._decoder.add(ShapedDense(output_shape, name=f'{name}_shaped_dense'))

    def call(self, input: tf.Tensor) -> tf.Tensor:
        return self._decoder(input)

@gin.configurable(whitelist=['num_units', 'num_layers', 'activation'])
class DenseVAE(auto_shape.Layer):
    def __init__(self,
                 input_shape: Sequence[int],
                 latent_shape: Sequence[int],
                 num_units: int = 100,
                 num_layers: int = 1,
                 activation: Union[None, str, Type[tf.keras.layers.Layer]] = auto_shape.ReLU,
                 batch_norm: bool = False,
                 name: str = 'vae',
                 ) -> None:
        self.encoder = ExtraBatchDim(DenseVAEEncoder(latent_shape,
                                                     num_units,
                                                     num_layers,
                                                     activation,
                                                     batch_norm,
                                                     name=f'{name}_encoder'))
        self.decoder = ExtraBatchDim(DenseVAEDecoder(input_shape,
                                                     num_units,
                                                     num_layers,
                                                     activation,
                                                     batch_norm,
                                                     name=f'{name}_decoder'))
        super().__init__(batch_dims=2, name=name)

    def call(self, input: tf.Tensor, mask: Optional[tf.Tensor] = None) -> tf.Tensor:
        z = self.encoder(input)
        input_recon = self.decoder(z['sample'])
        rec_loss = mse(input_recon, input, mask) * np.prod(input.shape[2:])
        kl_loss = kl_divergence(z['mean'], z['log_var'], mask)
        self.add_named_loss(rec_loss, name=f'{self.name}_recon', layer=self)
        self.add_named_loss(kl_loss, name=f'{self.name}_kl', layer=self)
        return z['sample']


import os
import webbrowser
from flask import Flask, flash, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'assets'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'mp4', 'mov', 'heic'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            url = f"{UPLOAD_FOLDER}/{filename}"
            print(url)
            webbrowser.open_new(f"file://{os.getcwd()}/{url}")
            return redirect(url_for('download_file', name=filename))

    html = '''
    <!doctype html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload new File</title>

Upload new File

    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
    return html

@app.route('/uploads/<name>')
def download_file(name):
    print(f"File received: {name}")
    return send_from_directory(app.config["UPLOAD_FOLDER"], name)


#!/usr/bin/env python3

import sys
import re

def main():
    regex_pattern = r'^(Mr|Mrs|Ms|Dr|Er)\.[a-zA-Z]+$'
    print(str(bool(re.search(regex_pattern, input()))).lower())

if __name__ == '__main__':
    main()


import importlib
import inspect
from typing import Any, List, Type

def get_subclass_types_from_module(module_path, type: Type) -> List:
    """Retrieve a list of types that are subclass of the other type parameter.

    Args:
        module_path (str): The absolute path to the module
        type (Type): The type that this class should be a subclass of.

    Returns:
        List: A list of types that derive from the subclass.
    """
    module_instance = importlib.import_module(module_path)
    return [obj for name, obj in inspect.getmembers(module_instance) if inspect.isclass(obj) and issubclass(obj, type)]

def create_type_from_module_path(module_type_path: str, **kwargs) -> Any:
    """Instantiate the exporter from the type definition as a string

    Args:
        module_type_path (str): The fully qualified definition for the exporter type.

    Raises:
        ValueError: If the exporter type was not defined.
        ValueError: If it's not a fully qualified type declaration.
        ValueError: If the module instane is invalid.
        ValueError: If the exporter interface type was not retrievable from the module instance.

    Returns:
        ExporterInterface: The instantiated exporter.
    """
    if module_type_path is None:
        raise ValueError("The exporter type is invalid or null")

    if "." not in module_type_path:
        raise ValueError(
            "Full type definition is required for the exporter in order to create.")

    module_path_expanded = module_type_path.split('.')
    type_module = module_path_expanded[:-1]
    type_class_name = module_path_expanded[-1]

    if module_path_expanded is None:
        raise ValueError("Failed to expand the exporter type definition")

    type_module: str = '.'.join(module_type_path.split('.')[-1])
    type_module_instance = importlib.import_module(type_module)

    if not type_module_instance:
        raise ValueError("The module was not found")

    module_type = getattr(type_module_instance, type_class_name)
    if not module_type:
        raise ValueError("Failed to retrieve the interface type")

    module_type_instance = module_type(**kwargs)
    if module_type_instance is None:
        raise ValueError("The exporter instance is invalid or null")

    return module_type_instance


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@time    : 2019/5/30 10:28
@file    : geneset_gmt.py
"""
import csv
import os
import re

from biocluster.iofile import File

class GenesetGmtFile(File):

    def check(self):
        super(GenesetGmtFile, self).check()
        with open(self.path) as in_handler:
            for line in in_handler:
                try:
                    name, _, gene_set = line.strip().split('\t', 2)
                    re.split('\s', gene_set)
                except:
                    self.set_error(
                        '基因集文件格式错误，文件应该三列: geneset_name<TAB>description<TAB>gene_list[空格或者tab分隔]')
                else:
                    return True

    def hard_link(self, new_path):
        if os.path.isdir(os.path.dirname(new_path)):
            cmd = 'ln {old} {new}'.format(old=self.path, new=new_path)
            return_code = os.system(cmd)
            if return_code not in (0, '0'):
                cmd = 'cp {old} {new}'.format(old=self.path, new=new_path)
                os.system(cmd)
        else:
            self.set_error('文件创建link失败，请确认文件路径是否正确', code="43703504")

    def basename(self):
        return os.path.basename(self.path)

    def csv_reader(self, remove_header=False):
        with self.get_reader() as in_handler:
            if remove_header:
                in_handler.readline()
            for item in csv.reader(in_handler, delimiter='\t'):
                yield item


import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
from torch_geometric.nn import GATConv
import torch.nn as nn

class GCN(torch.nn.Module):
    def __init__(self, num_features, num_classes):
        super(GCN, self).__init__()
        self.conv1 = GCNConv(num_features, 8)
        self.conv2 = GCNConv(8, num_classes)

    def forward(self, data):
        x, edge_index = data.x, data.edge_index

        x = F.relu(self.conv1(x, edge_index))
        x = F.dropout(x, training=self.training)
        x = self.conv2(x, edge_index)

        # print("Output shape:", x.shape)

        return F.log_softmax(x, dim=1)

class GAT(torch.nn.Module):
    def __init__(self, num_features, num_classes):
        super(GAT, self).__init__()
        self.conv1 = GATConv(num_features, 8, heads=8, dropout=0.6)
        # 如果您想要多层 GAT，可以在这里添加更多层
        self.conv2 = GATConv(8 * 8, num_classes, heads=1, concat=False, dropout=0.6)

    def forward(self, data):
        x, edge_index = data.x, data.edge_index

        x = F.dropout(x, p=0.6, training=self.training)
        x = F.elu(self.conv1(x, edge_index))
        x = F.dropout(x, p=0.6, training=self.training)
        x = self.conv2(x, edge_index)

        return F.log_softmax(x, dim=1)

class TextCNN(nn.Module):
    def __init__(self, vocab_size, embedding_dim, num_classes, filter_sizes, num_filters):
        super(TextCNN, self).__init__()
        self.embedding = nn.Embedding(vocab_size, embedding_dim)
        self.convs = nn.ModuleList(
            [nn.Conv2d(1, num_filters, (k, embedding_dim)) for k in filter_sizes]
        )
        self.dropout = nn.Dropout(0.5)
        self.fc = nn.Linear(len(filter_sizes) * num_filters, num_classes)

    def forward(self, x):
        x = self.embedding(x)  # [N, L, D]
        x = x.unsqueeze(1)  # [N, 1, L, D]
        x = [F.relu(conv(x)).squeeze(3) for conv in self.convs]  # [(N, Co, L), ...] * len(Ks)
        x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x]  # [(N, Co), ...] * len(Ks)
        x = torch.cat(x, 1)
        x = self.dropout(x)
        logit = self.fc(x)
        return logit

class TextLSTM(nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_dim, num_classes):
        super(TextLSTM, self).__init__()
        self.embedding = nn.Embedding(vocab_size, embedding_dim)
        self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=1, batch_first=True)
        self.fc = nn.Linear(hidden_dim, num_classes)

    def forward(self, x):
        x = self.embedding(x)  # [N, L, D]
        x, (h_n, c_n) = self.lstm(x)  # h_n is the hidden state
        x = h_n[-1, :, :]  # Take the last layer hidden state
        x = self.fc(x)
        return F.log_softmax(x, dim=1)


#Exercise 4: Download a copy of the file from www.py4e.com/code3/romeo.txt
#Write a program to open the file romeo.txt and read it line by line.
#For each line, split the line into a list of words using the split function.
#For each word, check to see if the word is already in a list.
#If the word is not in the list, add it to the list.
#When the program completes,
#sort and print the resulting words in alphabetical order.

wfile = input('Enter file: ')
alist = list()
try:
    ifile = open(wfile)
    for line in ifile:
        words = line.rstrip().split()
        for word in words:
            if word not in alist:
                alist.append(word)
except:
    print('File not found:',wfile)
    quit()
alist.sort()
print(alist)


from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required

from .models import HirePackage, HireRequest
from .forms import HireForm

from profiles.models import UserProfile

def get_packages(request):
    """
    View that returns all the packages
    """
    hire_packages = HirePackage.objects.all()

    template = 'hire/hire_packages.html'
    context = {
        'hire_packages': hire_packages,
    }

    return render(request, template, context)

def create_hire_request(request, hire_package_id):
    """
    View that handles the hire request
    """
    hire_package = get_object_or_404(HirePackage, pk=hire_package_id)
    initial_package = {
        'hire_package': hire_package,
    }

    if request.method == 'POST':
        hire_form = HireForm(request.POST, request.FILES)
        if hire_form.is_valid():
            hire_request = hire_form.save(commit=False)
            hire_request.hire_package = hire_package
            hire_request.save()
            messages.success(request, 'Successfully Sent request!')
            template = 'hire/hire_success.html'
            return render(request, template)
        else:
            messages.error(
                request,
                'Failed to send request. Please ensure the form is valid.'
                )
    else:
        if request.user.is_authenticated:
            profile = UserProfile.objects.get(user=request.user)
            hire_form = HireForm(initial={
                'email': profile.user.email,
                'hire_package': hire_package,
            })
        else:
            hire_form = HireForm(initial_package)

    template = 'hire/hire_request.html'
    context = {
        'hire_form': hire_form,
        'hire_package': hire_package,
    }
    return render(request, template, context)

@login_required
def hire_request_list(request):
    """
    View that returns all the package requests to admin
    """
    all_requests = HireRequest.objects.all()

    template = 'hire/hire_request_list.html'
    context = {
        'hire_requests': all_requests,
    }

    return render(request, template, context)


N = int(input())

count = 0

for i in range(1, N+1):
    str_10n = str(i)
    if '7' in str_10n:
        continue

    int_8n = oct(i)
    str_8n = str(int_8n)
    if '7' in str_8n:
        continue

    count += 1

print(count)


'''
Name: Orlando Companioni

Here I will tests the implementation of the the program
'''

#Import the classes
from StringFamily_Orlando import StringFamily,Violin,Harp
from PercussionFamily_Orlando import PercussionFamily,Drum,Xylophone
from WoodwindFamily_Orlando import WoodwindFamily,Flute
from Piano_Orlando import Piano
from OrderList_Orlando import Order

#Create objects
#These objects are global so that they are accessible for all functions
drum=Drum(0,20) #create a drum object with 0 keys and a diameter of 20 inches
flute=Flute()
harp=Harp(40)
piano=Piano(88,230)
violin=Violin(4)
xylophone=Xylophone(25)
instrument_to_print=[drum,flute,harp,piano,violin,xylophone] #List of all the instruments that we have

def main(): # This main function will act as the controller
    process()

def process(): # This is the process function that will call all the other functions
    inst_details()
    special_features()
    sorted()
    order_Created()
    custom_order()

def inst_details():
    #Test the methods
    # List of instruments to print in order of the assignment output
    # instrument_to_print=[drum,flute,harp,piano,violin,xylophone]

    for inst in instrument_to_print:
        if not isinstance(inst,Flute):
            print(f"\033[1;44m\n---------------Details of {inst.getName()}-----------------------\033[0;0m")
            print(f"Makes sound: {inst.make_sound()}")
            print(f"Play method: {inst.how_to_play()}")
            print(f"Repair method: {inst.how_to_repair()}")
            print(f"The price: {inst.get_price()}")
        else:
            print(f"\033[1;44m\n---------------Details of Flute-----------------------\033[0;0m")
            print(f"Makes sound: {inst.make_sound()}")
            print(f"Play method: {inst.how_to_play()}")
            print(f"The price: {inst.get_price()}")

def special_features():
    print("\033[1;44m\n-----------------SPECIAL FEATURES-----------------------\033[0;0m")

    # List of instruments to print in order of the assignment output
    # instrument_List=[xylophone,drum,harp,piano,flute,violin]
    for inst in instrument_to_print:
        if isinstance(inst,StringFamily) and not isinstance(inst,Piano): # This is to make sure not to double print piano
            print(inst.getString_num())
        elif isinstance(inst,PercussionFamily) and not isinstance(inst,Piano):
            if isinstance(inst,Drum):
                print(inst.getDiameter())
                print(inst.getKeys_num())
            else:
                print(inst.getKeys_num())
        elif isinstance(inst,WoodwindFamily):
            print(inst.getMadeOf())
        elif isinstance(inst,Piano):
            print(inst.getString_num())
            print(inst.getKeys_num())
    # # sorted(instrument_to_print)

def sorted():
    # List of instruments to print in order of the assignment output
    instrument_to_print.sort()
    print("\033[1;44m\n-----------------SORTED INSTRUMENTS-----------------------\033[0;0m")
    for inst in instrument_to_print:
        print(f"{inst.getName()} price: {inst.get_price()}")

def order_Created():
    #Create an order
    print("\033[1;44m\n---------------------ORDERS-------------------------\033[0;0m")
    order_Bob = Order(111, 'Bob')
    order_Alice = Order(222, 'Alice')
    # percussion_instruments=[drum,xylophone,piano]
    # stringINstruments=[violin,harp,piano]

    for instrument in instrument_to_print:
        if isinstance(instrument,PercussionFamily)and not isinstance(instrument,Piano):
            order_Bob.add_instrument(instrument)
        elif isinstance(instrument,StringFamily) and not isinstance(instrument,Piano):
            order_Alice.add_instrument(instrument)
        elif isinstance(instrument,Piano):
            order_Alice.add_instrument(instrument)
            order_Bob.add_instrument(instrument)

    # for intrument in percussion_instruments:
    #     order_Bob.add_instrument(intrument)

    # for instrument in stringINstruments:
    #     order_Alice.add_instrument(instrument)

    bob_total=order_Bob.getTotal_Price()
    # for item in order_Bob.getOrders():
    #     price=item.get_price().lstrip("$")
    #     bob_total=bob_total+float(price)
    print(f"Order Bob total: {bob_total}")

    alice_total=order_Alice.getTotal_Price()
    # for item in order_Alice.getOrders():
    #     price=item.get_price().lstrip("$")
    #     alice_total=alice_total+float(price)
    print(f"Order Alice total: {alice_total}")

def custom_order(): # This function has the custom order functionallity
    print(f"\033[1;44m\n-----------------CUSTOM ORDERS-----------------------\033[0;0m")
    order_Orlando=Order("087","Orlando") # it will not allow me to use 087 as an int so i used a string
    print("Please enter your order by typing the letter for each instrument without any spaces")
    print("\033[1;32md=Drum, f=Flute, h=Harp, p=Piano, v=Violin, x=Xylophone\033[0;0m")
    order=input("\033[1;34mEnter your order:  ").lower()
    for letter in order:
        if letter=="d":
            order_Orlando.add_instrument(drum)
        elif letter=="f":
            order_Orlando.add_instrument(flute)
        elif letter=="h":
            order_Orlando.add_instrument(harp)
        elif letter=="p":
            order_Orlando.add_instrument(piano)
        elif letter=="v":
            order_Orlando.add_instrument(violin)
        elif letter=="x":
            order_Orlando.add_instrument(xylophone)
        else:
            print("Invalid input")

    # orlando_total=0.0
    # for item in order_Orlando.getOrders():
    #     # orderlist.append(item.getName())
    #     price=item.get_price().lstrip("$") #This will remove the $ sign from the price
    #     orlando_total=orlando_total+float(price) #This will add the price to the total
    total = order_Orlando.getTotal_Price()
    if order_Orlando.getOrders()==[]:
        print("\033[1;34mNo instruments were ordered\033[0;0m")
        print(f"\033[1;34mOrder total for {order_Orlando.getName()}: 0\033[0;0m")
    else:
        print(f"\033[1;34mThe order of {order_Orlando.getName()} is: {[item.getName() for item in order_Orlando.getOrders()]}\033[0;0m")
        # print(f"\033[1;34mOrder total for {order_Orlando.getName()}: {orlando_total}\033[0;0m")
        print(f"\033[1;34mOrder total for {order_Orlando.getName()}: {total}\033[0;0m")

try:
    if __name__=="__main__":
        main()
except KeyboardInterrupt:
    print("Program terminated by user") #This will catch a keyboard interrupt and print a message


import sqlite3

conn = sqlite3.connect('C:/Users/User/Desktop/test1.db')
cursor = conn.cursor()

def table_creation():
    cursor.execute('''CREATE TABLE games(
        ID INT,
        name TEXT,
        genre TEXT,
        year INT,
        studio TEXT
        )
        ''')

table_creation()

conn.commit()

#cursor.execute('''SELECT * FROM students WHERE avg_score>9''')
'''
data = cursor.fetchall()

conn.commit()

print(data)'''


from transformers import BeitModel
from torch import nn
import torch

import matplotlib.pyplot as plt

from PIL import Image
import requests

"""
Picked at https://github.com/920232796/SETR-pytorch/blob/master/SETR/transformer_seg.py
"""

class BranchedDecoder(nn.Module):

    def __init__(self, in_channels, out_channels, features=[[256, 256], [256, 256], [512, 256, 128, 64]]):
        super().__init__()
        self.decoder_branch_1 = nn.Sequential(
            nn.Conv2d(in_channels, features[0][0], 2, padding=0),
            nn.BatchNorm2d(features[0][0]),
            nn.LeakyReLU(inplace=True),
            nn.Conv2d(features[0][0], features[0][1], 1, padding=0),
            nn.BatchNorm2d(features[0][1]),
            nn.LeakyReLU(inplace=True),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
        )

        self.decoder_branch_2 = nn.Sequential(
            nn.Conv2d(in_channels, features[1][0], 2, padding=0),
            nn.BatchNorm2d(features[1][0]),
            nn.LeakyReLU(inplace=True),
            nn.Conv2d(features[0][0], features[0][1], 1, padding=0),
            nn.BatchNorm2d(features[0][1]),
            nn.LeakyReLU(inplace=True),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True),
        )

        self.merge_branch = nn.Sequential(
            nn.Conv2d(features[2][0], features[2][1], 2, padding=0),
            nn.BatchNorm2d(features[2][1]),
            nn.LeakyReLU(inplace=True),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True),
            nn.Conv2d(features[2][1], features[2][2], 2, padding=0),
            nn.BatchNorm2d(features[2][2]),
            nn.LeakyReLU(inplace=True),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True),
            nn.Conv2d(features[2][2], features[2][3], 2, padding=0),
            nn.BatchNorm2d(features[2][3]),
            nn.LeakyReLU(inplace=True),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True),
        )

        self.final_layer = nn.Conv2d(features[2][3], out_channels, 3, padding=0)

    def forward(self, x):
        x1 = self.decoder_branch_1(x)

        x2 = self.decoder_branch_2(x)

        x = torch.cat((x1, x2), 1)

        x = self.merge_branch(x)

        x = self.final_layer(x)

        return x

class Decoder2D(nn.Module):

    # TODO: Maybe add dropout? Not sure if it is needed.

    def __init__(self, in_channels, out_channels, features=[512, 256, 128, 64]):
        super().__init__()

        self.conv1 = nn.Conv2d(in_channels, features[0], 2, padding=0)
        torch.nn.init.kaiming_uniform_(self.conv1.weight, mode="fan_in", nonlinearity="relu")

        self.conv2 = nn.Conv2d(features[0], features[1], 2, padding=0)
        torch.nn.init.kaiming_uniform_(self.conv2.weight, mode="fan_in", nonlinearity="relu")

        self.conv3 = nn.Conv2d(features[1], features[2], 2, padding=0)
        torch.nn.init.kaiming_uniform_(self.conv3.weight, mode="fan_in", nonlinearity="relu")

        self.conv4 = nn.Conv2d(features[2], features[3], 2, padding=0)
        torch.nn.init.kaiming_uniform_(self.conv4.weight, mode="fan_in", nonlinearity="relu")

        self.decoder_1 = nn.Sequential(
            self.conv1,
            nn.BatchNorm2d(features[0]),
            nn.LeakyReLU(inplace=True),
            nn.Dropout(),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
        )
        self.decoder_2 = nn.Sequential(
            self.conv2,
            nn.BatchNorm2d(features[1]),
            nn.LeakyReLU(inplace=True),
            nn.Dropout(),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
        )
        self.decoder_3 = nn.Sequential(
            self.conv3,
            nn.BatchNorm2d(features[2]),
            nn.LeakyReLU(inplace=True),
            nn.Dropout(),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
        )

        self.decoder_4 = nn.Sequential(
            self.conv4,
            nn.BatchNorm2d(features[3]),
            nn.LeakyReLU(inplace=True),
            nn.Dropout(),
            nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
        )

        self.final_out = (nn.Conv2d(features[-1], out_channels, 3, padding=0))

    def forward(self, x):
        x = self.decoder_1(x)
        x = self.decoder_2(x)
        x = self.decoder_3(x)
        x = self.decoder_4(x)
        x = self.final_out(x)
        return x

class BeitSegmentationModel(nn.Module):

    def __init__(
        self,
        lr=0.001,
        momentum=0.9,
        img_size=224,
        patch_dim=16,
        num_channels=3,
        num_classes=2,
        batch_size=16,
        pretrained_model="microsoft/beit-base-patch16-224-pt22k"
    ):

        super(BeitSegmentationModel, self).__init__()

        self.lr = lr
        self.momentum = momentum
        self.img_size = img_size
        self.patch_dim = patch_dim
        self.num_channels = num_channels
        self.num_classes = num_classes
        self.batch_size = batch_size

        # BEiT encoder without segmentation head, can use BeitConfig to
        # alter some of the default values used
        self.beit_base = BeitModel.from_pretrained(pretrained_model)

        for param in self.beit_base.parameters():
            param.requires_grad = False

        for param in self.beit_base.pooler.parameters():
            param.requires_grad = True

        self.decoder = Decoder2D(self.num_channels, self.num_classes)

    def encode(self, x):
        """
            Our self.encode should just be the BEiT base model calculating
            its hidden state and returning it. It returns the following
            * last_hidden_state
            * pooler_output
            * hidden_states
            * attentions
        """

        encoder_output = self.beit_base(pixel_values=x)[1].reshape(self.batch_size, self.num_channels, self.patch_dim, self.patch_dim)

        return encoder_output

    def forward(self, x):

        self.batch_size = len(x)

        encoder_pooler = self.encode(x)

        decoder_output = self.decoder(encoder_pooler)

        decoder_output = decoder_output.reshape(self.batch_size, self.img_size, self.img_size, self.num_classes)

        return decoder_output

if __name__ == "__main__":
    p = {
        "img_size": 224,
        "patch_dim": 16,
        "num_channels": 3,
        "num_classes": 2,
        "batch_size": 16,
        "pretrained_model": "microsoft/beit-base-patch16-224-pt22k-ft22k",
    }

    b = BeitSegmentationModel(
            img_size=p["img_size"],
            patch_dim=p["patch_dim"],
            num_channels=p["num_channels"],
            num_classes=p["num_classes"],
            batch_size=p["batch_size"],
            pretrained_model=p["pretrained_model"]
        )

    url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
    url1 = "http://images.cocodataset.org/test-stuff2017/000000000001.jpg"
    image = Image.open(requests.get(url1, stream=True).raw)
    image2 = Image.open(requests.get(url, stream=True).raw)

    images = [image, image2]

    results = b(images)

    for image in images:
        image.show()

    for image in results.detach().numpy():
        plt.imshow(image)
        plt.show()


import cv2
import numpy as np

def detect_cash(target_amount):
    # Load YOLOv3 network
    net = cv2.dnn.readNetFromDarknet("/home/jetson/CapstoneGUI/Cash_Detection/yolov3-tiny_testing.cfg", "/home/jetson/CapstoneGUI/Cash_Detection/yolov3-tiny_training_final.weights")

    # Load list of classes
    with open("/home/jetson/CapstoneGUI/Cash_Detection/classes.txt") as f:
        classes = [line.strip() for line in f.readlines()]

    # Initialize variables
    total_amount = 0
    #cap = cv2.VideoCapture(0)
    cap = cv2.VideoCapture("nvarguscamerasrc ! video/x-raw(memory:NVMM),format=NV12,width=640,height=480,framerate=30/1 ! nvvidconv ! video/x-raw,format=BGRx ! videoconvert ! video/x-raw,format=BGR ! appsink drop=1", cv2.CAP_GSTREAMER)
    target_reached = False

    while True:
        # Check for keypress
        ret, frame = cap.read()
        key = cv2.waitKey(1)

        # If "q" key is pressed, quit the program and close all windows
        if key == ord("q"):
            break

        # If "d" key is pressed, process a single frame
        elif key == ord("d"):
            detection_running = True
            target_reached = False
            ret, frame = cap.read()

            if ret:
                # Convert frame to a blob to feed into YOLOv3
                blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)

                # Feed the blob into the neural network and get the output predictions
                net.setInput(blob)
                layer_outputs = net.forward(net.getUnconnectedOutLayersNames())

                # Initialize lists for detected cash objects and their corresponding monetary values
                cash_objects = []
                cash_values = []

                # Loop through each output layer and detect cash objects
                for output in layer_outputs:
                    for detection in output:
                        scores = detection[5:]
                        class_id = np.argmax(scores)
                        confidence = scores[class_id]
                        if confidence > 0.5 and (classes[class_id].startswith("dollar_") or classes[class_id].startswith("coin_")):
                            # Extract bounding box coordinates and monetary value of cash object
                            box = detection[:4] * np.array([frame.shape[1], frame.shape[0], frame.shape[1], frame.shape[0]])
                            cash_objects.append(box.astype("int"))
                            if classes[class_id].startswith("dollar_"):
                                cash_values.append(int(classes[class_id].split("_")[1]))
                            else:
                                cash_values.append(0.01 if classes[class_id] == "coin_penny" else 0.05 if classes[class_id] == "coin_nickel" else 0.1 if classes[class_id] == "coin_dime" else 0.25)

            # Loop through each detected cash object and add its monetary value to the total amount
            for value in cash_values:
                total_amount += value

            # Check if target amount has been reached
            if total_amount >= target_amount:
                target_reached = True

                # Display message when target amount is reached
                cv2.putText(frame, "Target amount reached!", (10, 110), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
                break
        # Display the total amount and change required on the frame
        # Display the total amount and change required on the frame
        cv2.putText(frame, "Total amount: ${:.2f}".format(total_amount), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
        cv2.putText(frame, "Amount needed: ${:.2f}".format(target_amount - total_amount), (10, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
        cv2.putText(frame, "Press 'd' to detect, 'q' to add coins", (10, 150), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

        # Display the frame
        cv2.imshow("Cash Detection", frame)

    # Release the camera and close all windows
    cap.release()
    cv2.destroyAllWindows()
    return total_amount


"""Parse SOQL, including subqueries

Subqueries are very restricted by [Force.com SOQL]
(https://resources.docs.salesforce.com/sfdc/pdf/salesforce_soql_sosl.pdf)
(It's lucky for our implementation)
- "only root queries support aggregate expressions"
- Subqueries can not be in "OR" condition, because it is an additional level.

These expressions can be supported here, but currently unimplemented:
    FORMAT(), convertCurrency(), toLabel(),
    Date Functions..., convertTimezone() in Date Functions
    DISTANCE(x, GEOLOCATION(...))
Especially DISTANCE and GEOLOCATION are not trivial because they would
require a combined parser for parentheses and commas.

Unsupported GROUP BY ROLLUP and GROUP BY CUBE (their syntax for reports).
"""
from typing import Any, Callable, Dict, Iterable, List, Optional, overload, Sequence, Type, TypeVar, Tuple, Union
import datetime
import re
import pytz
from salesforce.dbapi.exceptions import ProgrammingError

_TRow = TypeVar('_TRow', Tuple[Any, ...], List[Any], Dict[str, Any])
_T = TypeVar('_T')

def nz(x: Optional[_T]) -> _T:
    """Not Zero type assert"""
    assert x is not None
    return x

# reserved wods can not be used as alias names
RESERVED_WORDS = set((
    'AND, ASC, DESC, EXCLUDES, FIRST, FROM, GROUP, HAVING, '
    'IN, INCLUDES, LAST, LIKE, LIMIT, NOT, NULL, NULLS, '
    'OR, SELECT, WHERE, WITH'
).split(', '))
AGGREGATION_WORDS = set((
    'AVG, COUNT, COUNT_DISTINCT, MIN, MAX, SUM'
).split(', '))
pattern_aggregation = re.compile(r'\b(?:{})(?=\()'.format('|'.join(AGGREGATION_WORDS)), re.I)
pattern_groupby = re.compile(r'\bGROUP BY\b', re.I)

class QQuery:
    """Parse the SOQL query to an object useful to correctly interpret a response.

    public methods:
        parse_rest_response(records, rowcount, row_type=list):

            Parse the response to rows of the tape list or dict
            parameters:
                records: response['records'] or a slice of its iterator
                rowcount: response['totalSize']

            The `cursor` that created the response can be necessary, but currently unused
    """
    # It can be later splitted to more specialized objects, if QQuery become
    # extended and too complicated.
    # type of query: QRootQuery, QFieldSubquery, QWhereSubquery
    # type of field: QField, QAggregation, QFieldSubquery

    # pylint:disable=too-many-instance-attributes

    def __init__(self, soql: Optional[str] = None) -> None:
        self.soql = None                  # type: Optional[str]
        self.fields = []                  # type: List[Union[str, QQuery]]
        # dictionary of chil to parent relationships - lowercase keys
        self.subroots = {}                # type: Dict[str, Any]  # recursive is Any
        self.aliases = []                 # type: List[str]
        self.root_table = None            # type: Optional[str]
        # is_aggregation: only to know if aliases are relevant for output
        self.is_aggregation = False
        self.has_child_rel_field = False
        # extra_soql: everything what is after the root table name (and
        # after optional alias), usually WHERE...
        self.extra_soql = None            # type: Optional[str]
        self.subqueries = None            # type: Optional[List[Tuple[str, Any]]]
        if soql:
            self._from_sql(soql)

    def _from_sql(self, soql: str) -> None:
        """Create Force.com SOQL tree structure from SOQL"""
        # pylint:disable=too-many-branches,too-many-nested-blocks
        assert not self.soql, "Don't use _from_sql method directly"
        self.soql = soql
        soql, self.subqueries = split_subquery(soql)
        match_parse = re.match(r'SELECT (.*) FROM (\w+)\b(.*)$', soql, re.I)
        if not match_parse:
            raise ProgrammingError('Invalid SQL: %s' % self.soql)
        fields_sql, self.root_table, self.extra_soql = match_parse.groups()
        fields = [x.strip() for x in fields_sql.split(',')]
        self.is_aggregation = bool(pattern_groupby.search(self.extra_soql) or
                                   pattern_aggregation.search(fields[0]))
        self.is_plain_count = fields[0].upper() == 'COUNT()'
        consumed_subqueries = 0
        expr_alias_counter = 0
        #
        if not self.is_plain_count:
            out_field = ''  # type: Union[str, QQuery]
            for field in fields:
                if self.is_aggregation:
                    match = re.search(r'\b\w+$', field)
                    if match:
                        alias = match.group()
                        assert alias not in RESERVED_WORDS, "invalid alias name"
                        if match.start() > 0 and field[match.start() - 1] == ' ':
                            out_field = field = field[match.start() - 1]
                    else:
                        alias = 'expr{}'.format(expr_alias_counter)
                        expr_alias_counter += 1
                    assert '&' not in field, "Subquery not expected as field in aggregation query"
                elif '&' in field:
                    assert field == '(&)'  # verify that the subquery was in parentheses
                    subquery = QQuery(self.subqueries[consumed_subqueries][0])
                    consumed_subqueries += 1
                    self.has_child_rel_field = True
                    out_field = subquery
                    # TODO more child relationships to the same table
                    alias = nz(subquery.root_table)
                else:
                    alias = out_field = field
                    if '.' in alias:
                        if alias.split('.', 1)[0].lower() == self.root_table.lower():
                            alias = alias.split('.', 1)[1]
                        if '.' in alias:
                            # prepare paths for possible empty outer joins
                            subroots = self.subroots
                            root_crumbs = alias.lower().split('.')[:-1]
                            for scrumb in root_crumbs:
                                subroots.setdefault(scrumb, {})
                                subroots = subroots[scrumb]
                self.aliases.append(alias)
                self.fields.append(out_field)
        # TODO it is not currently necessary to parse the exta_soql

    def _make_flat(self, row_dict: Dict[str, Any], path: Tuple[str, ...], subroots: Dict[str, Dict[str, Any]]
                   ) -> Dict[str, Any]:
        """Replace the nested dict objects by a flat dict with keys "object.object.name"."""
        # can get a cursor parameter, if introspection should be possible on the fly
        out = {}
        for k, v in row_dict.items():
            klc = k.lower()  # "key lower case"
            if (not (isinstance(v, dict) and 'attributes' in v)
                    or ('done' in v and 'records' in v and 'totalSize' in v)):
                # :
                if klc not in subroots:
                    out[klc] = v
                else:
                    strpath = '.'.join(path + (klc,)) + '.'
                    strip_pos = len(strpath) - len(klc + '.')
                    for alias in self.aliases:
                        if alias.lower().startswith(strpath):
                            out[alias.lower()[strip_pos:]] = None  # empty outer join field names
            else:
                new_subroots = subroots[klc] if k != 'attributes' else {}
                for sub_k, sub_v in self._make_flat(v, path + (klc,), new_subroots).items():
                    out[k.lower() + '.' + sub_k] = sub_v
        return out

    @overload                   # noqa
    def parse_rest_response(self, records: Iterable[Dict[str, Any]], rowcount: int, row_type: Type[_TRow]
                            ) -> Iterable[_TRow]: ...
    @overload                   # noqa
    def parse_rest_response(self, records: Iterable[Dict[str, Any]], rowcount: int,
                            ) -> Iterable[Tuple[Any, ...]]: ...
    def parse_rest_response(self, records: Iterable[Dict[str, Any]], # type: ignore[no-untyped-def] # noqa
                            rowcount: int, row_type=tuple) -> Iterable[Any]:
        """Parse the REST API response to DB API cursor flat response"""
        assert row_type in (dict, list, tuple)
        if self.is_plain_count:
            # result of "SELECT COUNT() FROM ... WHERE ..."
            assert list(records) == []
            if issubclass(row_type, dict):
                yield {'count': rowcount}
            elif issubclass(row_type, list):
                yield [rowcount]  # originally [resp.json()['totalSize']]
            elif issubclass(row_type, tuple):
                yield (rowcount,)
        else:
            for row_deep in records:
                if list(row_deep.keys()) == ['explain']:
                    yield (row_deep['explain'],)
                else:
                    assert self.is_aggregation == (row_deep['attributes']['type'] == 'AggregateResult')
                    row_flat = self._make_flat(row_deep, path=(), subroots=self.subroots)
                    # TODO Will be the expression "or x['done']" really correct also for long subrequests?
                    assert all(not isinstance(x, dict) or x['done'] for x in row_flat)
                    if issubclass(row_type, dict):
                        yield {k: fix_data_type(row_flat[k.lower()]) for k in self.aliases}
                    elif issubclass(row_type, list):
                        yield [fix_data_type(row_flat[k.lower()]) for k in self.aliases]
                    elif issubclass(row_type, tuple):
                        yield tuple(fix_data_type(row_flat[k.lower()]) for k in self.aliases)

SALESFORCE_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%f+0000'
SF_DATETIME_PATTERN = re.compile(r'[1-3]\d{3}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-6]\d.\d{3}\+0000$')

def fix_data_type(data: Any, tzinfo: Optional[datetime.timezone] = None) -> Any:
    # this is a simplified function. The data type should be finally read
    # from some reliable field mapping, not to guess by regexp like here.
    # Only a DateTime field has so specific regexp that the guess is
    # acceptable.
    if isinstance(data, str) and SF_DATETIME_PATTERN.match(data):
        datim = datetime.datetime.strptime(data, SALESFORCE_DATETIME_FORMAT)
        datim = datim.replace(tzinfo=tzinfo or pytz.utc)
        return datim
    return data

def mark_quoted_strings(sql: str) -> Tuple[str, List[str]]:
    """Mark all quoted strings in the SOQL by '@' and get them as params,
    with respect to all escaped backslashes and quotes.
    """
    # pattern of a string parameter (pm), a char escaped by backslash (bs)
    # out_pattern: characters valid in SOQL
    pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
    bs_pattern = re.compile(r"\\([\\'])")
    out_pattern = re.compile(r"^(?:[-!()*+,.:<=>\w\s|%s])*$")
    missing_apostrophe = "invalid character in SOQL or a missing apostrophe"
    start = 0
    out = []
    params = []
    for match in pm_pattern.finditer(sql):
        out.append(sql[start:match.start()])
        assert out_pattern.match(sql[start:match.start()]), missing_apostrophe
        params.append(bs_pattern.sub('\\1', sql[match.start() + 1:match.end() - 1]))
        start = match.end()
    out.append(sql[start:])
    assert out_pattern.match(sql[start:]), missing_apostrophe
    return '@'.join(out), params

def subst_quoted_strings(sql: str, params: Sequence[str]) -> str:
    """Reverse operation to mark_quoted_strings - substitutes '@' by params.
    """
    parts = sql.split('@')
    params_dont_match = "number of parameters doesn' match the transformed query"
    assert len(parts) == len(params) + 1, params_dont_match  # would be internal error
    out = []
    for i, param in enumerate(params):
        out.append(parts[i])
        out.append("'%s'" % param.replace('\\', '\\\\').replace("\'", "\\\'"))
    out.append(parts[-1])
    return ''.join(out)

def find_closing_parenthesis(sql: str, startpos: int) -> Optional[Tuple[int, int]]:
    """Find the pair of opening and closing parentheses.

    Starts search at the position startpos.
    Returns tuple of positions (opening, closing) if search succeeds, otherwise None.
    """
    pattern = re.compile(r'[()]')
    level = 0
    opening = []  # type: Union[int, List[None]]
    for match in pattern.finditer(sql, startpos):
        par = match.group()
        if par == '(':
            if level == 0:
                opening = match.start()
            level += 1
        if par == ')':
            assert level > 0, "missing '(' before ')'"
            level -= 1
            if level == 0:
                assert isinstance(opening, int)
                closing = match.end()
                return opening, closing
    return None

def transform_except_subquery(sql: str, func: Callable[[str], str]) -> str:
    """Call a func on every part of SOQL query except nested (SELECT ...)"""
    start = 0
    out = []
    while sql.find('(SELECT', start) > -1:
        pos = sql.find('(SELECT', start)
        out.append(func(sql[start:pos]))
        start, pos = nz(find_closing_parenthesis(sql, pos))
        out.append(sql[start:pos])
        start = pos
    out.append(func(sql[start:len(sql)]))
    return ''.join(out)

def split_subquery(sql: str) -> Tuple[str, List[Tuple[str, Any]]]:
    """Split on subqueries and replace them by '&'."""
    sql, params = mark_quoted_strings(sql)
    sql = simplify_expression(sql)
    _ = params  # NOQA
    start = 0
    out = []
    subqueries = []  # List[Tuple[str, Any]]
    pattern = re.compile(r'\(SELECT\b', re.I)
    match = pattern.search(sql, start)
    while match:
        out.append(sql[start:match.start() + 1] + '&')
        start, pos = nz(find_closing_parenthesis(sql, match.start()))
        start, pos = start + 1, pos - 1
        subqueries.append(split_subquery(sql[start:pos]))
        start = pos
        match = pattern.search(sql, start)
    out.append(sql[start:len(sql)])
    return ''.join(out), subqueries

def simplify_expression(txt: str) -> str:
    """Remove all unecessary whitespace and some very usual space"""
    minimal = re.sub(r'\s', ' ',
                     re.sub(r'\s(?=\W)', '',
                            re.sub(r'(?<=\W)\s', '',
                                   txt.strip())))
    # add space before some "(" and after some ")"
    return re.sub(r'\)(?=\w)', ') ',
                  re.sub(r'(,|\b(?:{}))\('.format('|'.join(RESERVED_WORDS)), '\\1 (', minimal)
                  )


from __future__ import print_function
import tensorflow as tf
from ops import *
import numpy as np

def read_and_decode(filename_queue, canvas_size):
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
            serialized_example,
            features={
                'wav_raw': tf.FixedLenFeature([], tf.string),
                'noisy_raw': tf.FixedLenFeature([], tf.string),
                'baseline_raw': tf.FixedLenFeature([], tf.string),
            })
    wave = tf.decode_raw(features['wav_raw'], tf.int32)
    wave.set_shape(canvas_size)
    wave = (2./65535.) * tf.cast((wave - 32767), tf.float32) + 1.
    noisy = tf.decode_raw(features['noisy_raw'], tf.int32)
    noisy.set_shape(canvas_size)
    noisy = (2./65535.) * tf.cast((noisy - 32767), tf.float32) + 1.
    baseline = tf.decode_raw(features['baseline_raw'], tf.int32)
    baseline.set_shape(canvas_size)
    baseline = (2./65535.) * tf.cast((baseline - 32767), tf.float32) + 1.

    return wave, noisy, baseline


import asyncio
import config
import psycopg2

params = config.sql_db

""" This script has sync and async functions. First script starts synchronously, then hits async
functions loop and fetches data from SQL asynchronously, after finishing fetching data it continues
synchronously and finish script"""

########### SYNC FUNC (normal fun)############
def counter_1():
    for i in range(0, 5):
        print(f"Sync_1: {i}")
###################################

########### BASIC ASYNC SAMPLE_3 'create_task' #####################
########### GETS DATA FROM 3 SQL DBR AT SAME TIME ####################
########### THIS IS USEFUL FOR REQUISTING FEW HTTP 'requests' or SQL DATA FECHING #################
########### CHECK 'aiohttp', FOR MULTIPLKE HTTP 'requests' HANDLING ##################
async def fetch_data():
    """ data fetching from 1st DB"""

    print("start fetching data from sql")
    # connecting to SQL
    con = psycopg2.connect(**params)
    cur = con.cursor()
    cur.execute(
        """SELECT id, company, client, phone_number, order_name,
        order_term, status, comments, update_date
        FROM orders
        ORDER BY status ASC, order_term ASC, order_name ASC, client ASC""")
    # fetching data from SQL
    query_start = cur.rowcount

    # this is just printing row number to see how data is fethed, but this could be any operation you want,
    # maybe some counting or whatever
    for num in range(0, query_start + 1):
        print({"ROW NUMBER 1": num})
        # this is just for wait 0.25s to see how numbers are counting
        await asyncio.sleep(0.25)
        # if value is "0" then wait till 'fetch_data_2()' will finish, in mean time 'fetch_data_2()'
        # and 'fetch_data_3()' will execute
        if num == 0:
            await fetch_data_2()

    con.close()

    print("data fetched")

    return {"RESULT": query_start}

async def fetch_data_2():
    """ data fetching from 2nd DB"""

    print("start fetching data from sql 2")
    con = psycopg2.connect(**params)
    cur = con.cursor()
    cur.execute(
        """SELECT id, company, client, phone_number, order_name,
        order_term, status, comments, update_date
        FROM orders
        ORDER BY status ASC, order_term ASC, order_name ASC, client ASC""")
    query_start = cur.rowcount

    # this is just printing row number to see how data is fethed, but this could be any operation you want.
    # maybe some counting or whatever.
    for num in range(0, query_start - 2):
        print({"ROW NUMBER <--  2": num})
        await asyncio.sleep(0.25)

    # some action after data is fetched. This just prints some text to see when data is fetched.
    # this could be any operation you want.
    print("data fetched2")

    return {"ROW NUMBER": query_start}

async def fetch_data_3():
    """ data fetching from 3nd DB"""

    print("start fetching data from sql 3")
    con = psycopg2.connect(**params)
    cur = con.cursor()
    cur.execute(
        """SELECT id, company, client, phone_number, order_name,
        order_term, status, comments, update_date
        FROM orders
        ORDER BY status ASC, order_term ASC, order_name ASC, client ASC""")
    query_start = cur.rowcount

    # this is just printing row number to see how data is fethed, but this could be any operation you want.
    # maybe some counting or whatever.
    for num in range(0, query_start + 1):
        print({"ROW NUMBER <----- 3": num})
        await asyncio.sleep(0.25)

    # some action after data is fetched. This just prints some text to see when data is fetched.
    # this could be any operation you want.
    print("data fetched 3")

async def main():
    """ main async func where all task goes and etc. and there is sample how return works in async func task handling"""
    # create tasks for async func
    task_1 = asyncio.create_task(fetch_data())
    task_2 = asyncio.create_task(fetch_data_2())
    task_3 = asyncio.create_task(fetch_data_3())

    # You have to set value so task if you want to RETURN normal result
    # with 'value = await task_1': <- this is 'Future'
    # "DATA": 1
    # with 'await task_2' you'll get:
    # <Task finished name='Task-2' coro=<fetch_data() done, defined at D:\Python\python-default\
    # threading_async_multiprocess\asyncio_await_basic_sample.py:62> result={'DATA': 1}>
    # with 'await task_3' and no RETURN statment you'll get:
    # TASK 2 RESULt: <Task finished name='Task-4' coro=<fetch_data_3() done, defined at
    # D:\Python\python-default\threading_async_multiprocess\async_fetch_data_from_3_DBs.py:69> result=None>

    # with asign value task
    value = await task_1
    print(f"TASK 1 RESULt: {value}")
    # with no asign value task
    await task_2
    print(f"TASK 2 RESULt: {task_2}")
    # func without return statment <---
    await task_3
    print(f"TASK 2 RESULt: {task_3}")

    # after all tasks are finish, this prints some text. This could be any operation you want, maybe UI filling, some
    # counting from two APIs or DBs or whatever you need to be.
    print("finished counting")

########### SYNC FUNC (normal fun)############
def counter_2():
    for i in range(0, 5):
        print(f"Sync_2: {i}")
###################################

counter_1()
## this creates ASYNC loop. You can asign this to button or whatever you like to. ##
asyncio.run(main())
####################################################################################
counter_2()


from flask import Flask, render_template, flash, request, redirect
from flask_debugtoolbar import DebugToolbarExtension
from forex_python.converter import CurrencyRates, CurrencyCodes

app = Flask(__name__)
app.config['SECRET_KEY'] = "oh-so-secret"
debug = DebugToolbarExtension(app)
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False

c = CurrencyRates(force_decimal=False)
cc = CurrencyCodes()

@app.route("/")
def homepage():
    """show homepage"""

    return render_template('home.html')

@app.route("/result", methods=["POST"])
def display_result():
    """ displays form for input"""

    input_currency = request.form["inputcurrency"]
    output_currency = request.form["outputcurrency"]

    try:
        input_amount = float(request.form["amount"])

        input_symbol = cc.get_symbol(input_currency)
        output_symbol = cc.get_symbol(output_currency)
        input_name = cc.get_currency_name(input_currency)
        output_name = cc.get_currency_name(output_currency)

        converted = c.convert(input_currency, output_currency, input_amount)
        converted = format(converted, ".2f")
        amount = format(input_amount, ".2f")

        return render_template('results.html', amount=amount,
            converted=converted,
            input_symbol=input_symbol,
            output_symbol=output_symbol,
            input_name=input_name,
            output_name=output_name,)

    except ValueError:
        flash("Error: Please input a number or decimal for the amount", "error")
        return redirect("/")
    except Exception as err:
        print(err)
        err = str(err)
        if err == "Currency Rates Source Not Ready":
            flash("Error: Not an acceptable currency! Please try again", "error")
        return redirect("/")


# ANálise de maioridade

from datetime import date
soma = 0
ano_atual = date.today().year
for i in range(5):
    ano = int(input('Digite o ano de nascimento: '))
    if (ano_atual - ano) < 18:
        soma += 1
print(f'{soma} pessoas ainda não atingiram a maioridade ')


from django.forms import *
from models import *
from utils import *

class ProyectoForm(ModelForm):
    tipos = ModelMultipleChoiceField(widget=CheckboxSelectMultiple(attrs={'class': ''}),
            queryset = TipoProyecto.objects.all(), )
    class Meta:
        model = Proyecto
        widgets = {
            'descripcion': Textarea(attrs={'class': 'textarea'}),
            'nombre': TextInput(attrs={'class': 'textbox_nombre'}),
            'website': TextInput(attrs={'class': 'textbox'}),
            'fecha_inicial': DateInput(attrs={'class': 'textbox'}, format="%d/%m/%Y"),
            'fecha_final': DateInput(attrs={'class': 'textbox'}, format="%d/%m/%Y"),
            'avance': Select(attrs={'class':'combobox'}),
        }

class ProyectoDepartamentoForm(ModelForm):
    class Meta:
        model = ProyectoDepartamento
        exclude = ['proyecto', 'monto_total']

class ProyectoMunicipioForm(ModelForm):
    def __init__(self, proyecto, *args, **kwargs):
        super(ProyectoMunicipioForm, self).__init__(*args, **kwargs)
        self.proyecto_id = proyecto.id
        self.fields['donantes'] = ModelMultipleChoiceField(widget=CheckboxSelectMultiple,
                queryset = magic_queryset(Donante, self.proyecto_id) , required=False)
        self.fields['contrapartes'] = ModelMultipleChoiceField(widget=CheckboxSelectMultiple,
                queryset = magic_queryset(Contraparte, self.proyecto_id), required=False)
        self.monto = MontoField()

    class Meta:
        model = ProyectoMunicipio
        exclude = ['proyecto']

class ProyectoDonanteForm(ModelForm):
    monto = MontoField()
    class Meta:
        model = ProyectoDonante
        exclude = ['proyecto']

class ProyectoContraparteForm(ModelForm):
    monto = MontoField()
    class Meta:
        model = ProyectoContraparte
        exclude = ['proyecto']

class ContraparteForm(ModelForm):
    class Meta:
        model = Contraparte
        widgets = {
            'descripcion': Textarea(attrs={'class': 'textarea'}),
            'nombre': TextInput(attrs={'class': 'textbox_nombre'}),
            'website': TextInput(attrs={'class': 'textbox'}),
            'pais': Select(attrs={'class':'combobox'}),
            'tipo': Select(attrs={'class':'combobox'}),
        }

class DonanteForm(ModelForm):
    class Meta:
        model = Donante
        widgets = {
            'descripcion': Textarea(attrs={'class': 'textarea'}),
            'nombre': TextInput(attrs={'class': 'textbox_nombre'}),
            'website': TextInput(attrs={'class': 'textbox'}),
            'pais': Select(attrs={'class':'combobox'}),
            'tipo': Select(attrs={'class':'combobox'}),
        }

class ProyectoFotosForm(ModelForm):
    class Meta:
        model = ProyectoFotos
        exclude = ['proyecto']
        widgets = {
            'fecha': TextInput(attrs={'class': 'textbox'}),
            }


# -*- coding: UTF-8 -*-
from utils import *

def main():
    locales_path = get_sys_arg(2, '', 'locales_new')

    execl_file_path = get_sys_arg(1, '语言包的 Excel 文件')

    book = import_excel(execl_file_path)

    if book.nsheets == 0:
        return

    make_dir(locales_path)

    sheet = book.sheet_by_index(0)
    rows = sheet.nrows
    cols = sheet.ncols
    for col in range(cols):
        if col < 1:
            continue

        file_name = sheet.cell_value(0, col)

        if len(file_name) == 0:
            continue

        js = ''
        for row in range(rows):
            if row < 1:
                continue
            key = sheet.cell_value(row, 0)
            value = sheet.cell_value(row, col)
            js = js_objstr_add(js, add_first_last(key),
                               add_first_last(value))

            if len(js) < 1:
                continue
        js += '\n};\n'

        file_path = locales_path + '/' + file_name + '.js'
        write_js_file(file_path, js)

main()


# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005)
optimizer_config = dict()
# learning policy
lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False)
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=40)
checkpoint_config = dict(
    by_epoch = True, interval = 50, max_keep_ckpts = 3)
#classwise 별로 출력
evaluation = dict(metric='mIoU', pre_eval=True,
                  classwise = True, save_best='mIoU')
work_dir = './work_dirs/baseline'
gpu_ids = [0]
auto_resume = False


# IMPORTS
from pathlib import Path
from isort import file
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({
    'axes.titlesize': 'medium',
    'axes.labelsize': 'small',
    'legend.title_fontsize' : 'small',
    }
)

# import datetime
from utils.atab import Atab

from pprint import pprint
import pandas as pd
from ipdb import set_trace as dbg

from utils.parse_plot_synop_ch import total_score_range, cat_total_score_range
from utils.check_params import check_params

def collect_relevant_files(file_prefix, file_postfix, debug, source_path, parameter):
    """Collect all files corresponding to current parameter in 'corresponding_files_dict'.

    Args:
        file_prefix (str): prefix of files we're looking for (i.e. total_scores)
        file_postfix (str): postfix of files we're looking for (i.e. .dat)
        debug (bool): add debug messages command prompt
        source_path (Path): path to directory, where source files are
        parameter (str): parameter of interest

    Returns:
        dict: dictionary containig all available lead time range (ltr) dataframes for parameter
    """
    # collect the files, corresponding to this parameter in the corresponding files dict.
    # the keys in this dict are the available lead time ranges for the current parameter.
    corresponding_files_dict = {}

    # for dbg purposes:
    files_list = []

    for file_path in source_path.glob(f"{file_prefix}*{parameter}{file_postfix}"):
        if file_path.is_file(): # check, that the corresponding path belongs to a file and not to a sub-directory

            # lt_range = key for corresponding_files_dict
            # TODO: change here, if ltr is longer than 5 chars
            lt_range = file_path.name[len(file_prefix):len(file_prefix)+5]

            # extract header & dataframe
            header = Atab(file=file_path, sep=" ").header
            df = Atab(file=file_path, sep=" ").data

            # clean df
            df = df.replace(float(header["Missing value code"][0]), np.NaN)

            df.set_index(keys='Score', inplace=True)

            # add information to dict
            corresponding_files_dict[lt_range] = {
                                                    # 'path':file_path,
                                                    'header':header,
                                                    'df':df
                                                }

            # add path of file to list of relevant files
            files_list.append(file_path)
    if debug:
        print(f"\nFor parameter: {parameter} these files are relevant:\n")
        pprint(files_list)
        print(f"\nThese files have been parsed & combined in the 'corresponding_files_dict'. Each key (lt-range) has a subdict with two keys: {corresponding_files_dict['19-24'].keys()}\n")

    return corresponding_files_dict

# enter directory / read total_scores files / call plotting pipeline
def _total_scores_pipeline(
    params_dict,
    plot_scores,
    plot_params,
    plot_cat_scores,
    plot_cat_params,
    plot_cat_thresh,
    file_prefix,
    file_postfix,
    input_dir,
    output_dir,
    season,
    model_version,
    grid,
    debug,
) -> None:
    """Read all ```ATAB``` files that are present in: data_dir/season/model_version/<file_prefix><...><file_postfix>
        Extract relevant information (parameters/scores) from these files into a dataframe.
        Rows --> Scores | Columns --> Stations | For each parameter, a separate station_scores File exists.

    Args:
        parameters (list): parameters, for which plots should be generated (i.e. CLCT, DD_10M, FF_10M, PMSL,...). part of file name
        file_prefix (str): prefix of files (i.e. time_scores)
        file_postfix (str): postfix of files (i.e. '.dat')
        input_dir (str): directory to seasons (i.e. /scratch/osm/movero/wd)
        output_dir (str): output directory (i.e. plots/)
        season (str): season of interest (i.e. 2021s4/)
        model_version (str): model_version of interest (i.e. C-1E_ch)
        scores (list): list of scores, for which plots should be generated
        debug (bool): print further comments & debug statements
    """
    print(f"\n--- initialising total scores pipeline")

    # tmp; define debug = True, to show debug statements for total_scores only
    debug = True

    source_path = Path(f"{input_dir}/{season}/{model_version}")
    for parameter in params_dict:
        corresponding_files_dict = collect_relevant_files(file_prefix, file_postfix, debug, source_path, parameter)

        # pass dict to plotting pipeline
        _generate_total_scores_plot(
            data=corresponding_files_dict,
            parameter=parameter,
            plot_scores=plot_scores,
            plot_params=plot_params,
            plot_cat_scores=plot_cat_scores,
            plot_cat_params=plot_cat_params,
            plot_cat_thresh=plot_cat_thresh,
            # TODO: add ens params/thresh/scores
            output_dir=output_dir,
            grid=grid,
            debug=debug,
        )
    return

############################################################################################################################
######################################### PLOTTING PIPELINE FOR TOTAL SCORES PLOTS #########################################
############################################################################################################################

def _set_ylim(param, score, ax, debug):
    # define limits for yaxis if available
    regular_param = (param, "min") in total_score_range.columns
    regular_score = score in total_score_range.index

    if regular_param and regular_score:
        lower_bound = total_score_range[param]["min"].loc[score]
        upper_bound = total_score_range[param]["max"].loc[score]
        # if debug:
        #     print(
        #         f"found limits for {param}/{score} --> {lower_bound}/{upper_bound}"
        # )
        if lower_bound != upper_bound:
            ax.set_ylim(lower_bound, upper_bound)

    # TODO: add computation of y-lims for cat & ens scores

    return

def _customise_ax(parameter, score, x_ticks,grid, ax):
    """Apply cosmetics to current ax.

    Args:
        parameter (str): current parameter
        score (str): current score
        x_ticks (list): list of x-ticks labels (lead time ranges, as strings)
        grid (bool): add grid to ax
        ax (Axes): current ax
    """
    if grid:
        ax.grid(which='major', color='#DDDDDD', linewidth=0.8)
        ax.grid(which='minor', color='#EEEEEE', linestyle=':', linewidth=0.5)
        ax.minorticks_on()

    ax.tick_params(axis='both', which='major', labelsize=8)
    ax.tick_params(axis='both', which='minor', labelsize=6)
    ax.set_title(f"{parameter}: {score}")
    ax.set_xlabel(f"Lead-Time Range (h)")
    ax.legend(fontsize=6)
    ax.set_xticks(range(len(x_ticks)), x_ticks)
    return

def _clear_empty_axes(subplot_axes, idx):
    # remove empty ``axes`` instances
    i = 1
    while (idx%4+i) < 4:
        ax = subplot_axes[idx%4+i]
        ax.axis('off')
        i += 1
    return

def _save_figure(output_dir, filename):
    print(f"---\t\tsaving: {output_dir}/{filename[:-1]}.png")
    plt.savefig(f"{output_dir}/{filename[:-1]}.png")
    plt.clf()
    return

def _generate_total_scores_plot(
    data,
    parameter,
    plot_params,
    plot_scores,
    plot_cat_scores,
    plot_cat_params,
    plot_cat_thresh,
    output_dir,
    grid,
    debug,
):
    """Generate Total Scores Plot."""
    if debug:
        print(f"--- starting plotting pipeline")
        print(f"---\t1) map parameter (i.e. TD_2M_KAL --> TD_2M*)")
    # get correct parameter, i.e. if parameter=T_2M_KAL --> param=T_2M*
    param = check_params(param=parameter, verbose=False) # TODO: change False back to debug

    if debug:
        print(f"---\t2) check if output_dir exists (& create it if necessary)")
    # check (&create) output directory for total scores plots
    # output_dir = f"{output_dir}/total_scores"
    if not Path(output_dir).exists():
        Path(output_dir).mkdir(parents=True, exist_ok=True)

    if debug:
        print(f"---\t3) initialise figure with a 2x2 subplots grid")
    # create 2x2 subplot grid
    fig, ((ax0, ax1),(ax2, ax3)) = plt.subplots(nrows=2, ncols=2, tight_layout=True, figsize=(10, 10), dpi=200)

    subplot_axes = {0:ax0, 1:ax1, 2:ax2, 3:ax3} # hash map to access correct axes later on

    # ltr_unsorted  ->  unsorted lead time ranges
    # ltr_sorted    ->  sorted lead time ranges (used for x-tick-labels later on )
    ltr_unsorted, ltr_sorted = list(data.keys()), []
    ltr_start_times_sorted = sorted([int(lt.split('-')[0]) for lt in ltr_unsorted])
    for idx, ltr_start in enumerate(ltr_start_times_sorted):
        for ltr in ltr_unsorted:
            if ltr.startswith(str(ltr_start).zfill(2)):
                ltr_sorted.insert(idx, ltr)

    # re-name & create x_int list, s.t. np.arrays are plottet against each other
    x_ticks = ltr_sorted
    x_int = list(range(len(ltr_sorted)))

    if debug:
        print(f"---\t4) create x-axis")
        print(f"---\t\tUnsorted ltr list:\t\t{ltr_unsorted}")
        print(f"---\t\tSorted ltr start times list:\t{ltr_start_times_sorted}")
        print(f"---\t\tSorted ltr list (= x-ticks):\t{ltr_sorted}")
        print(f"---\t\tx_int =\t\t\t\t{x_int}")

    # extract header from data & create title
    header = data[ltr_sorted[-1]]['header']
    footer = f"Model: {header['Model version'][0]} | Period: {header['Start time'][0]} - {header['End time'][0]} | © MeteoSwiss"
    unit = header["Unit"][0]

    # initialise filename
    filename = f"total_scores_{parameter}_"

    # scores = params_dict[parameter] # this is a list of lists

    ############################################################################
    ##################### REGULAR SCORES PLOTTING PIPELINE #####################
    ############################################################################
    if debug:
        print(f"---\t5) plot REGULAR parameter/scores (Because, regular & categorical scores should not be mixed on the same figure.)")

    if plot_scores and plot_params:
        regular_scores = plot_scores.split(',')
        # the idx of a score, maps the score to the corresponding subplot axes instance
        for idx, score in enumerate(regular_scores):
            # if debug:
            #     print(f"--- plotting:\t{param}/{score}")

            multiplt=False

            # save filled figure & re-set necessary for next iteration
            if idx > 0 and idx%4==0:
                # add title to figure
                plt.suptitle(
                    footer,
                    horizontalalignment="center",
                    verticalalignment="top",
                    fontdict={
                        "size": 6,
                        "color": "k",
                    },
                    bbox= dict(
                        facecolor='none',
                        edgecolor='grey',
                    ),
                )
                _save_figure(output_dir=output_dir, filename=filename)
                fig, ((ax0, ax1),(ax2, ax3)) = plt.subplots(nrows=2, ncols=2, tight_layout=True, figsize=(10, 10), dpi=200)
                subplot_axes = {0:ax0, 1:ax1, 2:ax2, 3:ax3}
                # reset filename
                filename = f"total_scores_{parameter}_"

            # get ax, to add plot to
            ax = subplot_axes[idx%4]
            ax.set_xlim(x_int[0], x_int[-1])
            ax.set_ylabel(f"{score.upper()} ({unit})")

            # plot two scores on one sub-plot
            if '/' in score:
                multiplt = True
                scores = score.split('/')
                filename += f"{scores[0]}_{scores[1]}_"
                _set_ylim(param=param, score=scores[0], ax=ax, debug=debug)

                # get y0, y1 from dfs
                if debug and idx==0:
                    print(f"---\t6) collect the data corresponding to {score} from all dataframes in the data dict in y-list")
                    print(f"---\t7) plot y-list against x_int")
                y0, y1 = [], []
                for ltr in ltr_sorted:
                    y0.append(data[ltr]['df']['Total'].loc[scores[0]])
                    y1.append(data[ltr]['df']['Total'].loc[scores[1]])

                # plot y0, y1
                ax.plot(x_int, y0, color="red", linestyle="-", marker='^', fillstyle='none', label=f"{scores[0].upper()}")
                ax.plot(x_int, y1, color="k", linestyle="-", marker='D', fillstyle='none', label=f"{scores[1].upper()}")

            # plot single score on sub-plot
            if not multiplt:
                filename += f"{score}_"
                _set_ylim(param=param, score=score, ax=ax, debug=debug)

                y = []
                # extract y from different dfs
                for ltr in ltr_sorted:
                    ltr_score = data[ltr]['df']['Total'].loc[score]
                    y.append(ltr_score)

                ax.plot(x_int, y, color="k", linestyle="-", marker='D', fillstyle='none', label=f"{score.upper()}")

            # customise grid, title, xticks, legend of current ax
            _customise_ax(parameter=parameter, score=score, x_ticks=x_ticks, grid=True, ax=ax)

            # save figure, if this is the last score
            if idx == len(regular_scores)-1:
                # add title to figure
                plt.suptitle(
                    footer,
                    horizontalalignment="center",
                    verticalalignment="top",
                    fontdict={
                        "size": 6,
                        "color": "k",
                    },
                    bbox= dict(
                        facecolor='none',
                        edgecolor='grey',
                    ),
                )
                # clear empty subplots
                _clear_empty_axes(subplot_axes=subplot_axes, idx=idx)
                # save & clear figure
                _save_figure(output_dir=output_dir, filename=filename)
    ############################################################################
    ################### CATEGORICAL SCORES PLOTTING PIPELINE ###################
    ############################################################################
    # remark: include thresholds for categorical scores
    if debug:
        print(f"---\t10) repeat plotting pipeline for categorical params/scores/thresh combinations")

    print(plot_cat_params)
    print(plot_cat_scores)
    print(plot_cat_thresh)
    print(plot_cat_params and plot_cat_scores and plot_cat_thresh)

    if plot_cat_params and plot_cat_scores and plot_cat_thresh:
        print(f"--- should now create total scores plots for all cat params/scores")
        cat_params = plot_cat_params.split(',')  # categorical parameters: TOT_PREC12,TOT_PREC6,TOT_PREC1,CLCT,T_2M,T_2M_KAL,TD_2M,TD_2M_KAL,FF_10M,FF_10M_KAL,VMAX_10M6,VMAX_10M1
        cat_scores = plot_cat_scores.split(',')  # categorical scores: FBI,MF,POD,FAR,THS,ETS
        cat_threshs = plot_cat_thresh.split(':') # categorical thresholds: 0.1,1,10:0.2,1,5:0.2,0.5,2:2.5,6.5:0,15,25:0,15,25:-5,5,15:-5,5,15:2.5,5,10:2.5,5,10:5,12.5,20:5,12.5,20
        cat_params_dict = {cat_param: [] for cat_param in cat_params}
        for param, threshs in zip(cat_params, cat_threshs):
            # first append all scores w/o thresholds to parameter
            for score in plot_scores.split(','):
                if '/' in score:
                    cat_params_dict[param].append(score.split('/'))
                else:
                    cat_params_dict[param].append([score])

            # afterwards append all scores that have a threshold in their name to current to parameter
            thresholds = threshs.split(',')
            for threshold in thresholds:
                for score in cat_scores:
                    if '/' in score:
                        cat_params_dict[param].append([x+f"({threshold})" for x in score.split('/')])

                    else:
                        cat_params_dict[param].append([f"{score}({threshold})"])

        if True:
            print("Categorical Parameter Dict: ")
            pprint(cat_params_dict)

    # TODO: implement the total scores pipeline for categorical scores as well

    ############################################################################
    #################### ENSEMBLE SCORES PLOTTING PIPELINE #####################
    ############################################################################
    # remark: include thresholds for categorical scores
    print(f"---\t11) repeat plotting pipeline for ensemble params/scores/thresh combinations")
    # TODO: implement the total scores pipeline for categorical scores as well

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

    return


from openerp import models, fields

class CrmLead(models.Model):
    _inherit = 'crm.lead'

    association = fields.Many2one(comodel_name='res.partner')

    def _lead_create_contact(self, cr, uid, lead, name, is_company,
                             parent_id=False, context=None):
        """Propagate association to created partner.
        """
        partner_id = super(CrmLead, self)._lead_create_contact(
            cr, uid, lead, name, is_company, parent_id=parent_id,
            context=context)
        self.pool['res.partner'].write(
            cr, uid, partner_id, {'association': lead.association.id},
            context=context)
        return partner_id


import sys
import ast
import traceback
from stackInspector import StackInspector

""" Clase para rastrear funciones que fueron ejecutadas. Para su uso, considere:
with CoverageTracer() as coverage:
    function_to_be_traced()

coverage.report_executed_lines()
"""

class CoverageTracer(StackInspector):

    def __init__(self):
        super().__init__(None, self.traceit)
        self.executed_lines = []

    # Funcion que rastrea el codigo, contar cuantas veces se ejecuta cada linea de codigo
    def traceit(self, frame, event: str, arg):
        function_name = frame.f_code.co_name
        if event == "line":
            line = frame.f_lineno
            # Evitamos rastrearnos a nosotros
            if not self.our_frame(frame) and not self.problematic_frame(frame):
                self.executed_lines.append([function_name, line])

        return self.traceit

    def report_executed_lines(self):
        result = set()
        for line in self.executed_lines:
            result.add((line[0], line[1]))
        return sorted(result, key=lambda a: a[1])

    def report_execution_count(self):
        result = []
        for line in self.executed_lines:
            count = self.executed_lines.count(line)
            if (line[0], line[1], count) not in result:
                result.append((line[0], line[1], count))
        result = sorted(result, key=lambda a: a[1])
        return result


from aiogram import Router, types
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
from aiogram.types import ChatMemberUpdated
from aiogram.filters.chat_member_updated import ChatMemberUpdatedFilter, \
                                                JOIN_TRANSITION, \
                                                LEAVE_TRANSITION

from src.collector.dao import Message
from .dao import ActiveChat

handlers_router = Router()

class RateTheBot(StatesGroup):
    confirm = State()
    rate = State()

@handlers_router.message(Command(commands=["start", "help"]))
async def send_welcome(message: types.Message):
    await message.reply("Hi! I'm SpanBot!\n"
                        "I can save your messages in db.\n"
                        "You may check connection to db with command /check"
                        " or /rate this bot.")

@handlers_router.message(Command(commands=["check"]))
async def check_api_connection(message: types.Message):
    try:
        amount_messages = await Message.filter(chat_id=message.chat.id).count()
    except Exception as e:
        await message.answer("Connection to DB: Error")
        print(e)
    else:
        await message.answer("Connection to DB: OK\n"
                             f"There are {amount_messages} messages from this "
                             "chat saved in DB.")

@handlers_router.message(Command(commands="rate"))
async def want_to_rate(message: types.Message, state: FSMContext):
    await state.set_state(RateTheBot.confirm)
    await message.reply("Do you want to rate this bot?\n"
                        "(You may end the dialogue with "
                        "command /cancel at any moment)")

@handlers_router.message(Command(commands="cancel"))
async def cancel_state(message: types.Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is None:
        return None
    await state.clear()
    await message.reply("You quit this dialogue.")

@handlers_router.message(RateTheBot.confirm)
async def rate_bot(message: types.Message, state: FSMContext):
    if message.text.strip().lower() == "yes":
        await state.set_state(RateTheBot.rate)
        await message.reply("How do you like this bot?\n"
                            "Send your mark from 1 to 5.")
    elif message.text.strip().lower() == "no":
        await state.clear()
        await message.reply("OK! You may do it later if you want.")
    else:
        await message.reply("Sorry, I don't understand.\n"
                            "Please send 'yes' or 'no'.")

@handlers_router.message(RateTheBot.rate)
async def get_bot_rating(message: types.Message, state: FSMContext):
    mark = message.text.strip()
    if mark in ["4", "5"]:
        await message.reply(f"Your mark is {mark}.\nThanks! Nice to know it.")
        await state.clear()
    elif mark in ["1", "2", "3"]:
        await message.reply(f"Your mark is {mark}.\n"
                            "I will try to become better!")
        await state.clear()
    else:
        await message.reply("Sorry, I don't understand.\n"
                            "Please send your mark from 1 to 5.")

@handlers_router.my_chat_member(
    ChatMemberUpdatedFilter(member_status_changed=JOIN_TRANSITION)
)
async def bot_was_added_in_chat(event: ChatMemberUpdated):
    await ActiveChat.get_or_create(chat_id=event.chat.id)

@handlers_router.my_chat_member(
    ChatMemberUpdatedFilter(member_status_changed=LEAVE_TRANSITION)
)
async def bot_was_kicked_from_chat(event: ChatMemberUpdated):
    await ActiveChat.filter(chat_id=event.chat.id).delete()


from flask import *
from googletrans import Translator, LANGUAGES

translator = Translator(service_urls=[
      'translate.google.com',])

langues = LANGUAGES
print(langues)

print(translator.translate('veritas lux mea',dest="fr").text)
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html',data=langues)

@app.route('/', methods=['GET', 'POST'])
def getText():
    if request.method == 'POST':
        # Retrieve the text from the textarea
        texte = request.form.get('Traduire')
        toLanguage = request.form.get("traduction_select")
        fromLanguage = request.form.get("traduire_select")

        traduction = translator.translate(texte,src=fromLanguage,dest=toLanguage).text
        auto_language = f"La langue détectée : {langues[translator.detect(texte).lang]}"

        return render_template('index.html',data=langues,sample_input=traduction,sample_text=texte,detect_language=auto_language)

    return render_template('index.html',data=langues)

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


from pessoa import *

def cadastro():
        nome = input('digite seu nome: ')
        idade = input('digite sua idade: ')
        sexo = input('digite seu sexo: ')
        cidade = input('digite sua cidade: ')
        estado = input('digite seu estado: ')

        return nome, idade, sexo, cidade, estado

pc = cadastro()

pessoa1 = pessoa(pc[0], pc[1], pc[2], pc[3], pc[4])

#teste
print(pessoa1.nome,',' ,pessoa1.idade, ',' ,pessoa1.sexo, ',' ,pessoa1.cidade, ',' ,pessoa1.estado)


from read_file import read_all_subjects, get_baselines, get_region_names
import numpy as np
from scipy.stats import ttest_ind
import pickle
from result_analysis import utils
from sklearn import preprocessing

class ttest:
    def __init__(self, data, group=["1", "3"]):
        self.group = group
        self.process_data(data, group)

    def process_data(self, data, group=["1", "3"]):
        if type(data) is dict:
            self.network = []
            self.feature = []
            self.dx = []

            for i in range(len(data["dx_label"])):
                if data["dx_label"][i] in group:
                    self.network.append(data["adjacency_matrix"][i])
                    self.feature.append(data["node_feature"][i][:, 2])
                    self.dx.append(data["dx_label"][i])

    def find_t_stat_node(self):
        feat_g1 = []
        feat_g2 = []
        for i in range(len(self.feature)):
            if self.dx[i] == self.group[0]:
                feat_g1.append(self.feature[i])
            elif self.dx[i] == self.group[1]:
                feat_g2.append(self.feature[i])

        feat_g1 = np.array(feat_g1)
        feat_g2 = np.array(feat_g2)

        p_val = np.zeros(feat_g1.shape[1])
        for i in range(feat_g1.shape[1]):
            a = feat_g1[:, i]
            b = feat_g2[:, i]
            p_val[i] = ttest_ind(a, b)[1]

        return p_val

    def find_t_stat_edge(self):
        feat_g1 = []
        feat_g2 = []
        for i in range(len(self.network)):
            if self.dx[i] == self.group[0]:
                feat_g1.append(self.network[i])
            elif self.dx[i] == self.group[1]:
                feat_g2.append(self.network[i])

        feat_g1 = np.array(feat_g1)
        feat_g2 = np.array(feat_g2)

        p_val = np.zeros(feat_g1.shape[1:])
        for i in range(feat_g1.shape[1]):
            for j in range(feat_g1.shape[2]):
                a = feat_g1[:, i, j]
                b = feat_g2[:, i, j]
                if i != j:
                    p_val[i, j] = ttest_ind(a, b)[1]
                else:
                    p_val[i, j] = 0

        return p_val

    def find_discriminative_pairs(self, p_cut_off=0.05):
        p_val_edge = self.find_t_stat_edge() < p_cut_off
        p_val_node = self.find_t_stat_node() < p_cut_off
        print("Node selected: {}".format(p_val_node.sum()))
        reg_pair = []
        for i in range(p_val_edge.shape[0]):
            for j in range(p_val_edge.shape[1]):
                if p_val_edge[i][j] and p_val_node[i] and p_val_node[j] and i != j:
                    reg_pair.append((i, j))

        return reg_pair

    def find_discriminative_links(self, p_cut_off=0.05):
        p_val_edge = self.find_t_stat_edge() < p_cut_off
        link_pair = []
        for i in range(p_val_edge.shape[0]):
            for j in range(p_val_edge.shape[1]):
                if p_val_edge[i][j] and i != j:
                    link_pair.append((i, j))

        return link_pair

    def get_triplet_data(self, p_cut_off=0.05):
        pairs = self.find_discriminative_pairs(p_cut_off)
        X = []
        label = []
        for i in range(len(self.dx)):
            network = self.network
            row = []
            feat = self.feature
            for (x, y) in pairs:
              row = row + [feat[i][x], feat[i][y], network[i][x, y]]
            X.append(row)
            if self.dx[i] == self.group[0]:
                label.append(0)
            else:
                label.append(1)

        X = np.array(X)
        X = X - X.mean(axis=0)
        X = X / np.std(X, axis=0)
        label = np.array(label)
        return X, label, pairs

    def get_link_data(self, p_cut_off=0.05, pairs=None):
        if pairs is None:
            pairs = self.find_discriminative_links(p_cut_off)
        X = []
        label = []
        for i in range(len(self.dx)):
            network = self.network
            row = []
            for (x, y) in pairs:
                row.append(network[i][x, y])
            X.append(row)
            if self.dx[i] == self.group[0]:
                label.append(0)
            else:
                label.append(1)

        X = np.array(X)
        X = preprocessing.robust_scale(X)
        label = np.array(label)
        return X, label, pairs

if __name__ == '__main__':
    data_set = get_baselines()
    groups = [["1", "2"], ["1", "3"], ["2", "3"]]
    reg_names = np.array(get_region_names())
    reg_list = []
    lasso_edges= get_lasso_edge_set(groups)
    for i, group in enumerate(groups):
        tt = ttest(data_set, group=group)
        reg = tt.find_discriminative_pairs(0.008)
        file_p = 't_pairs_' + group[0] + '_' + group[1] + '.pkl'

        common = set(reg).intersection(set(lasso_edges[i]))
        print("t-pairs: ", len(reg))
        print("lasso: ", len(lasso_edges[i]))
        print("t and lasso: ", len(common))
    # for i in range(len(reg_list) - 1):
    #     intersect = reg_list[i].intersection(reg_list[i + 1])
    #     print("Intersection between {} and {}:\n{}".format(i, i + 1, intersect))
    #     print("Intersection length: {}".format(len(intersect)))


import os

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///birthdays.db")
# engine = create_engine("postgresql:///test")
# db = scoped_session(sessionmaker(bind=engine))

@app.after_request
def after_request(response):
    """Ensure responses aren't cached"""
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":

        name = request.form.get("name")
        month = request.form.get("month")
        day = request.form.get("day")

        if not name or not month or not day:
            return render_template("error.html")

        current_id = db.execute("SELECT id FROM birthdays ORDER BY id DESC LIMIT 1")
        if not current_id:
            current_id = 1
        else:
            current_id = current_id[0]["id"] + 1
        db.execute("INSERT INTO birthdays (id, name, month, day) VALUES (?, ?, ?, ?)", current_id, name, month, day)

        return redirect("/")

    else:

        birthdays = db.execute("SELECT * FROM birthdays")
        print(birthdays)

        return render_template("index.html", birthdays=birthdays)