import logging
import tkinter as tk
from tkinter import ttk, messagebox
from typing import List
from src import protocols

__version__ = 0.1

# Set up logger.
logger = logging.getLogger(__name__)

class View(tk.Tk):
    def __init__(self, prompt='Prompt',
                 options: List[str] = ['exit'],
                 *args, **kwargs) -> None:
        super().__init__()
        self.title('Select an option')
        self.prompt = prompt
        self.options = options
        self.create_ui()
        self.controller_service = lambda x: None
        self.bind("<Return>", lambda *_:self.on_confirm())

    def on_confirm(self):
        if not self.listbox.curselection(): return
        # Get the selected items
        # selected_items = self.listbox.get(self.listbox.curselection())
        # Call the controller on the selected action.
        self.controller_service(int(self.listbox.curselection()[0]))

        # Destroy the window
        self.destroy()

    def create_ui(self):
        def on_select(event):
            # Check if any items are selected
            if self.listbox.curselection():
                # Enable the confirmation button
                self.button.config(state="normal")
            else:
                # Disable the confirmation button
                self.button.config(state="disabled")

        width = 280
        height = 250
        f_width = 270
        f_height = 240
        box_width = 40
        box_height = 12
        self.geometry(f"{width}x{height}+550+200")
        #self.columnconfigure(0,weight=1)
        #self.columnconfigure(1,weight=1)
        #self.columnconfigure(2,weight=1)

        # Create a frame to hold the widgets
        opts = ('flat', 'raised', 'sunken', 'solid', 'ridge', 'groove')
        self.frame = ttk.Frame(self, relief=opts[5], width=f_width,
                               height=f_height, padding=(width -f_width)//2)
        #self.frame.grid(column=0)#, sticky='NS')#, padx=5, pady=5)
        self.frame.pack(fill='both')
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=1)
        self.frame.rowconfigure(2, weight=1)
        self.frame.grid_propagate(False)

        self.frame_title = ttk.Frame(self.frame, width=f_width)
        self.frame_title.grid(row=0)
        self.frame_up = ttk.Frame(self.frame, width=f_width)
        self.frame_up.grid(row=1)
        self.frame_down = ttk.Frame(self.frame, width=f_width)
        self.frame_down.grid(row=2)

        self.titlebox = tk.Listbox(self.frame_title,
                                  width=box_width,
                                  height=box_height//2,
                                  justify='left')
        self.titlebox.insert("end", *self.prompt.splitlines())

        # Create a scrollbar for the listbox.
        scrollbar = tk.Scrollbar(self.frame_up)
        scrollbar.pack(side='right', fill='both')

        # Create a listbox widget to display the items.
        self.listbox = tk.Listbox(self.frame_up,
                                  width=box_width,
                                  height=box_height//2,
                                  yscrollcommand=scrollbar.set,
                                  justify='left')

        scrollbar.config(command = self.listbox.yview)

        # Insert options.
        self.listbox.insert("end", *self.options)
        # If item selected.
        self.listbox.bind("<<ListboxSelect>>", on_select)

        # Create a button widget to select an item from the listbox.
        self.button = ttk.Button(self.frame_down, state='disabled',
                                text="Select Item", command=self.on_confirm)

        # Create the cancel button
        cancel_button = ttk.Button(self.frame_down,
                                       text="Cancel",
                                       command=lambda:[
                                           self.controller_service(-1),
                                           self.destroy()])

        # Pack the widgets
        self.titlebox.pack(fill = 'both')
        self.listbox.pack(fill = 'both')
        self.button.pack(side='left', fill='y')
        cancel_button.pack(side='right')
        logger.info(f'{self.__class__} UI created')

    def bind_provider(self, call: protocols.ControllerSelect) -> None:
        '''
           Binds the function to the method
        '''

        logger.info(f'{self.__class__} binded to\
                     selection method {call.__name__}')
        self.controller_service = call

    def noActions(self, *args, **kwargs) -> None:
        logger.info(f'{self.__class__} tried to run but no method binded')
        messagebox.showerror(message="No method binded")

if __name__ == '__main__':

    # A multi lined prompt for title
    prompt = '''There once was a man called Jeff.
    He was a very good man.
    He was a very bad man.
    He was a very ugly man.
    He was a very fat man.
    He was a very stupid man.
    He was a very lazy man.
    He was a very rich man.'''

    # A set of options to select from.
    options = [f'Option {i}' for i in range(1,20)]
    app = View(options=options.copy(), prompt=prompt)

    # Included an exit option to represent normal app exiting option -1.
    options.append('Cancel')
    # Bind a messagebox as a provider for the selection method.
    app.bind_provider(
        lambda x: messagebox.showinfo(message=f'Selected option: {options[x]}') #type: ignore
        )
    # Start the main loop
    app.mainloop()


import sys
sys.stdin = open("C:\workspaces\자료구조\자료구조 활용 (스택, 큐, 해쉬, 힙)\input.txt", "rt")
from collections import deque

n,m = map(int, input().split())
# cnt = 0
# dq = list(map(int, input().split()))
# dq = deque(dq)

# while True:
#     if m == 0:
#         if max(dq) == dq[0]:
#             cnt += 1
#             print(cnt)
#             exit()
#         else:
#             m = len(dq) -1
#             dq.append(dq.popleft())
#     else:
#         if max(dq) == dq[0]:
#             cnt += 1
#             dq.popleft()
#             m -= 1
#         else:
#             dq.append(dq.popleft())
#             m -= 1

# 해설 풀이
cnt = 0
Q = [(pos, val) for pos, val in enumerate(list(map(int, input().split())))]
Q = deque(Q)
while True:
    cur = Q.popleft()
    if any(cur[1]<x[1] for x in Q):
        Q.append(cur)
    else:
        cnt += 1
        if cur[0] == m:
            break

print(cnt)

자료구조 활용 (스택, 큐, 해쉬, 힙)/7. 응급실(큐).py


from five import grok
from zope.component import queryMultiAdapter
from zope.interface import Interface
from zope.publisher.interfaces import NotFound
from zope.publisher.interfaces.browser import IBrowserPublisher

from AccessControl.ZopeSecurityPolicy import getRoles
from ZPublisher.BaseRequest import UNSPECIFIED_ROLES, DefaultPublishTraverse
from ZPublisher.BaseRequest import quote
from OFS.interfaces import IObjectManager
import zExceptions

from infrae.wsgi.interfaces import IRequest, ITraverser

class ObjectManagerPublishTraverse(DefaultPublishTraverse, grok.MultiAdapter):
    """The default Zope 3 folder traverser is register in Zope
    2.13.13. We register the Zope 2 one for Zope 2 folder, to prevent
    a broken ZMI.
    """
    grok.adapts(IObjectManager, IRequest)
    grok.provides(IBrowserPublisher)

def query_adapter(content, request, iface):
    """Query an adapter if needed.
    """
    if iface.providedBy(content):
        return content
    adapter = queryMultiAdapter((content, request), iface)
    if adapter is None:
        return DefaultPublishTraverse(content, request)
    return adapter

class Traverser(grok.MultiAdapter):
    grok.adapts(Interface, IRequest)
    grok.provides(ITraverser)
    grok.implements(ITraverser)

    def __init__(self, context, request):
        self.request = request
        self.context = context
        self.roles = getRoles(None, None, context, UNSPECIFIED_ROLES)

    def __call__(self, method, path):
        request = self.request
        content = self.context
        parents = request['PARENTS']
        request['TraversalRequestNameStack'] = path
        # Steps records the traversed path (used for some URL computation)
        steps = request.steps
        _steps = request._steps = map(quote, steps)
        entry_name = ''

        try:
            # We build parents in the wrong order, so we
            # need to make sure we reverse it when we're done.
            while 1:
                bpth = getattr(content, '__before_publishing_traverse__', None)
                if bpth is not None:
                    bpth(content, request)

                path = request.path = request['TraversalRequestNameStack']
                # Consume one item in the path.
                if path:
                    entry_name = path.pop()
                else:
                    # End of path, look for a view using IBrowserPublisher

                    next_content, default_path = query_adapter(
                        content, request, IBrowserPublisher).browserDefault(
                        request)

                    if next_content is not content:
                        self.roles = getRoles(
                            content, None, next_content, self.roles)
                        content = next_content

                    if default_path:
                        request._hacked_path=1
                        if len(default_path) > 1:
                            path = list(default_path)
                            method = path.pop()
                            request['TraversalRequestNameStack'] = path
                            continue
                        else:
                            entry_name = default_path[0]
                    elif (method and hasattr(content, method)
                          and entry_name != method
                          and getattr(content, method) is not None):
                        request._hacked_path=1
                        entry_name = method
                        method = 'index_html'
                    else:
                        break

                step = quote(entry_name)
                _steps.append(step)
                steps.append(entry_name)
                request['URL'] = '/'.join((request['URL'], step))

                try:
                    next_content = request.traverseName(content, entry_name)
                except (KeyError, AttributeError, NotFound):
                    raise zExceptions.NotFound(request['URL'])

                if (hasattr(content, '__bobo_traverse__') or
                    hasattr(content, entry_name)):
                    check_name = entry_name
                else:
                    check_name = None

                self.roles = getRoles(
                    content, check_name, next_content, self.roles)
                content = next_content

                parents.append(content)
        finally:
            parents.reverse()

        # Hacked path is for ZMI, where the real path is different
        # than the URL, and a base tag must be hacked in the body
        # response.
        if request._hacked_path:
            url = request['URL']
            index = url.rfind('/')
            if index > 0:
                request.response.setBase(url[:index])

        # content is PUBLISHED, or the first in parents (since it have
        # been reversed).
        request['PUBLISHED'] = parents.pop(0)

        # If content as a call method, get the roles defined on it, it
        # will be called.
        if hasattr(content, '__call__'):
            self.roles = getRoles(
                content, '__call__', content.__call__, self.roles)
        request.roles = self.roles

        return content


from django.urls import path
from . import views
from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Mehedi
from .models import Mehedi_Customer

# Create your views here.

class MehediView(TemplateView):
	template_name = 'mehedi.html'

class SmehediView(TemplateView):
	template_name = 'smehedi.html'

class Mehedi_artist_list(TemplateView):
	template_name = 'msp_list.html'

def mehedi_form_submission(request):
	print("Your data is saved!!!")
	name = request.POST['name']
	mob = request.POST['mob']
	address = request.POST['address']
	gender = request.POST['gender']
	age = request.POST['age']					#saving data to the variables for forms
	price_ohos = request.POST['price_ohos']
	price_ohbs = request.POST['price_ohbs']
	price_thos = request.POST['price_thos']
	price_thbs = request.POST['price_thbs']

	mehedi = Mehedi(name=name, mob=mob, address=address, gender=gender, age=age, price_ohos=price_ohos,
		price_ohbs=price_ohbs, price_thos=price_thos, price_thbs=price_thbs)

	mehedi.save()

	return render(request, 'sindex.html')

def mehedi_customer_form_submission(request):
	print("Your data is saved!!!")
	name = request.POST['name']
	mob = request.POST['mob']
	address = request.POST['address']							 #saving data in variables from customers of mehedi

	hand = request.POST['hand']
	artists = request.POST['artists']

	mehedi_customer = Mehedi_Customer(name=name, mob=mob, address=address,
						hand=hand,no_of_artist=artists)

	mehedi_customer.save()     #saving data in db

	m_artist = Mehedi.objects.all()
	context={
		"object_list": m_artist,                           #fetching data from database
	}
	return render(request,'msp.html',context)

	return render(request, 'msp.html')


from collections import defaultdict
class Solution:
    def minimumTotal(self, triangle: list) -> int:
        l = len(triangle)
        cache = defaultdict(dict)
        def path(d,i):
            if d==l-1:
                return triangle[l-1][i]

            if d in cache and i in cache[d]:
                return cache[d][i]
            cache[d][i] = min(path(d+1,i), path(d+1,i+1)) + triangle[d][i]
            return cache[d][i]

        return path(0,0)

print(Solution().minimumTotal([
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]))


import torch
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

def visualize_attention(input_toks, tgt_toks, model, tokenizer, device):
    input_toks = torch.tensor(input_toks).unsqueeze(0).to(device)
    tgt_toks = torch.tensor(tgt_toks).unsqueeze(0).to(device)

    (memory, encoder_attn_weights), memory_key_padding_mask = model.encode(input_toks, need_weights=True)
    res, mem_attn, self_attn = model.decode(tgt_toks, memory.repeat(1, tgt_toks.size(0), 1), memory_key_padding_mask.repeat(tgt_toks.size(0), 1), return_enc_dec_attn=True)

    mem_label = tokenizer.decode(input_toks[0].data.cpu().numpy().tolist(), decode_special=True).split(' ')
    tgt_label_attended_to = tokenizer.decode(tgt_toks[0].data.cpu().numpy().tolist(), decode_special=True).split(' ')
    tgt_label_attended_for = tokenizer.decode(tgt_toks[0].data.cpu().numpy().tolist(), decode_special=True).split(' ')

    def show_attn(fig, ax, matrix, attn_type, title):
        ax.set_title(title)

        ax.set_ylabel('Predicting the next token')
        ax.set_xlabel('Attending to this token')

        if attn_type=='encoder_self':
            ax.set_yticks(np.arange(len(mem_label)))
            ax.set_yticklabels(labels=mem_label, fontsize=16)

            ax.set_xticks(np.arange(len(mem_label)))
            ax.set_xticklabels(labels=mem_label, fontsize=16, rotation=90)
        elif attn_type=='decoder_self':
            ax.set_yticks(np.arange(len(tgt_label_attended_for)))
            ax.set_yticklabels(labels=tgt_label_attended_for, fontsize=16)

            ax.set_xticks(np.arange(len(tgt_label_attended_to)))
            ax.set_xticklabels(labels=tgt_label_attended_to, fontsize=16, rotation=90)
        elif attn_type=='mem':
            ax.set_yticks(np.arange(len(tgt_label_attended_for)))
            ax.set_yticklabels(labels=tgt_label_attended_for, fontsize=16)

            ax.set_xticks(np.arange(len(mem_label)))
            ax.set_xticklabels(labels=mem_label, fontsize=16, rotation=90)
        else:
            raise ValueError(f'attn type {attn_type} not understood')

        im = ax.imshow(matrix, cmap='Blues')
        fig.colorbar(im, ax=ax)

    fig, ax = plt.subplots(encoder_attn_weights.size(0), encoder_attn_weights.size(1))
    for i in range(encoder_attn_weights.size(0)):
        for j in range(encoder_attn_weights.size(1)):
            title = '%s Layer: %d Head: %d'%('Encoder SA', i,j)
            show_attn(fig, ax[i,j], encoder_attn_weights[i][j].data.cpu().numpy(), 'encoder_self', title)
    fig.set_size_inches(36,36)
    fig.tight_layout()

    fig, ax = plt.subplots(mem_attn.size(0), mem_attn.size(1))
    for i in range(mem_attn.size(0)):
        for j in range(mem_attn.size(1)):
            title = '%s Layer: %d Head: %d'%('Mem', i,j)
            show_attn(fig, ax[i,j], mem_attn[i][j].data.cpu().numpy(), 'mem', title)
    fig.set_size_inches(36,36)
    fig.tight_layout()

    fig, ax = plt.subplots(self_attn.size(0), self_attn.size(1))
    for i in range(self_attn.size(0)):
        for j in range(self_attn.size(1)):
            title = '%s AttentionLayer: %d Head: %d'%('Self', i,j)
            show_attn(fig, ax[i,j], np.clip(self_attn[i][j].data.cpu().numpy(), a_min=0, a_max=1), 'decoder_self', title)
    fig.set_size_inches(36,36)
    fig.tight_layout()


import os.path as osp

from ..build import DATASET_REGISTRY
from ..base_dataset import Datum, DatasetBase

@DATASET_REGISTRY.register()
class miniDomainNet(DatasetBase):
    """A subset of DomainNet.

    Reference:
        - Peng et al. Moment Matching for Multi-Source Domain
        Adaptation. ICCV 2019.
        - Zhou et al. Domain Adaptive Ensemble Learning.
    """

    dataset_dir = "domainnet"
    domains = ["clipart", "painting", "real", "sketch"]

    def __init__(self, cfg):
        root = osp.abspath(osp.expanduser(cfg.DATASET.ROOT))
        self.dataset_dir = osp.join(root, self.dataset_dir)
        self.split_dir = osp.join(self.dataset_dir, "splits_mini")

        self.check_input_domains(
            cfg.DATASET.SOURCE_DOMAINS, cfg.DATASET.TARGET_DOMAINS
        )

        train_x = self._read_data(cfg.DATASET.SOURCE_DOMAINS, split="train")
        train_u = self._read_data(cfg.DATASET.TARGET_DOMAINS, split="train")
        test = self._read_data(cfg.DATASET.TARGET_DOMAINS, split="test")

        super().__init__(train_x=train_x, train_u=train_u, test=test)

    def _read_data(self, input_domains, split="train"):
        items = []

        for domain, dname in enumerate(input_domains):
            filename = dname + "_" + split + ".txt"
            split_file = osp.join(self.split_dir, filename)

            with open(split_file, "r") as f:
                lines = f.readlines()
                for line in lines:
                    line = line.strip()
                    impath, label = line.split(" ")
                    classname = impath.split("/")[1]
                    impath = osp.join(self.dataset_dir, impath)
                    label = int(label)
                    item = Datum(
                        impath=impath,
                        label=label,
                        domain=domain,
                        classname=classname
                    )
                    items.append(item)

        return items


import plotly.graph_objects as go
from pymongo import MongoClient
from scipy.stats import norm
from scipy.optimize import curve_fit

# Подключение к MongoDB
client = MongoClient('mongodb://localhost:27017')
db = client['nevod']
collection = db['events_data']

# Собираем статистику для decor_Theta - average_eas_theta
theta_diff_count_map = {}

# Собираем статистику для decor_Phi - average_eas_phi
phi_diff_count_map = {}

data_theta = []
data_phi = []

for document in collection.find():
    decor_Theta = document["decor_Theta"]
    average_eas_theta = document["average_eas_theta"]
    theta_diff = round(decor_Theta - average_eas_theta)  # Округляем до целых
    data_theta.append(theta_diff)

    decor_Phi = document["decor_Phi"]
    average_eas_phi = document["average_eas_phi"]
    phi_diff = round(decor_Phi - average_eas_phi)  # Округляем до целых
    data_phi.append(phi_diff)

    if theta_diff not in theta_diff_count_map:
        theta_diff_count_map[theta_diff] = 1
    else:
        theta_diff_count_map[theta_diff] += 1

    if phi_diff not in phi_diff_count_map:
        phi_diff_count_map[phi_diff] = 1
    else:
        phi_diff_count_map[phi_diff] += 1

client.close()  # Закрываем соединение с базой данных

# Оценка параметров нормального распределения для theta
mu_theta, std_theta = norm.fit(data_theta)

# Создание аппроксимационной кривой для theta
x_theta = list(range(int(min(data_theta)), int(max(data_theta)) + 1))
y_theta = [norm.pdf(i, mu_theta, std_theta) for i in x_theta]

# График для decor_Theta - average_eas_theta
theta_diff_fig = go.Figure()

# Добавление гистограммы
theta_diff_fig.add_trace(go.Bar(
    x=list(theta_diff_count_map.keys()),
    y=list(theta_diff_count_map.values()),
    name='Histogram'
))

# Добавление аппроксимации
theta_diff_fig.add_trace(go.Scatter(
    x=x_theta,
    y=y_theta,
    mode='lines',
    name='Approximation'
))

theta_diff_fig.update_layout(
    xaxis_title='R_difference = Rounded(decor_Theta - average_eas_theta)',
    yaxis_title='Number of Files',
    title='Dependency of R_difference (decor_Theta - average_eas_theta) on the Number of Files',
    width=800,
    height=600
)

theta_diff_fig.show(renderer="browser")

# Оценка параметров нормального распределения для phi
mu_phi, std_phi = norm.fit(data_phi)

# Создание аппроксимационной кривой для phi
x_phi = list(range(int(min(data_phi)), int(max(data_phi)) + 1))
y_phi = [norm.pdf(i, mu_phi, std_phi) for i in x_phi]

# График для decor_Phi - average_eas_phi
phi_diff_fig = go.Figure()

# Добавление гистограммы
phi_diff_fig.add_trace(go.Bar(
    x=list(phi_diff_count_map.keys()),
    y=list(phi_diff_count_map.values()),
    name='Histogram'
))

# Добавление аппроксимации
phi_diff_fig.add_trace(go.Scatter(
    x=x_phi,
    y=y_phi,
    mode='lines',
    name='Approximation'
))

phi_diff_fig.update_layout(
    xaxis_title='R_difference = Rounded(decor_Phi - average_eas_phi)',
    yaxis_title='Number of Files',
    title='Dependency of R_difference (decor_Phi - average_eas_phi) on the Number of Files',
    width=800,
    height=600
)

phi_diff_fig.show(renderer="browser")


from datetime import datetime

from flask import Blueprint, redirect, render_template, url_for
from requests import get
from BigDataProject import app
from BigDataProject.db_local_copy.db_local_data_loader import load_copy

cart_routes = Blueprint('catalog', __name__, static_folder='static')

@cart_routes.route('/', methods=['GET'])
def main() -> render_template:
    """
    main catalog page

    :return:
    """
    games = []
    pagingState = None
    if app.config['DB_LOCAL_COPY']:
        for page in load_copy('BigDataProject/db_local_copy/db_local_data.txt'):
            games += page['page']
            pagingState = page['pagingState']
    else:
        # load data from db
        for page in range(2):
            headers = {'x-functions-key': app.config['DB_API_KEY']}
            params = {'pagingState': pagingState}
            response = get(app.config['LIST_GAMES_WITH_PRICES'],
                           headers=headers).json()
            pagingState = response['pagingState']
            games += response['page']
    return render_template("main.html", games=games, next_page=pagingState)

@cart_routes.route('/game_page/<name>', methods=['GET'])
def game_page(name, game_id = None) -> render_template:
    """
    main catalog page

    :return:
    """
    emotion_color = {
            "anger": "#DA6663",
            "fear": "#DA996B",
            "joy": "#BFB760",
            "love": "#ff75a7",
            "sadness": "#DA99B2",
            "surprise": "#5FBDDA",
            }
    print(app.config['DB_LOCAL_COPY'])
    if app.config['DB_LOCAL_COPY']:
        response = load_copy("BigDataProject/db_local_copy/db_local_data_game_info.txt")
        comments = load_copy("BigDataProject/db_local_copy/db_local_data_game_comments.txt")['comments']
    else:
        headers = {'x-functions-key': app.config['DB_API_KEY']}
        params = {'name': name}
        response = get(app.config['GET_GAME_BY_NAME'],
                       headers=headers,
                       params=params).json()

        comment_headers = {'x-functions-key': app.config['DB_API_KEY_COMMENTS']}
        comment_params = {'game_id': response['appId']}
        comments = get(app.config['GET_GAME_COMMENTS'],
                       headers=comment_headers,
                       params=comment_params).json()['comments']

    converted_data = [
            {"x": datetime.fromisoformat(record['datePrice']).timestamp() * 1000,
             "y": record['finalPrice']
             }
            for record in response['priceHistory']
            ]
    addition_data = []
    for i, day in enumerate(converted_data):
        if i > 0:
            part_day = day.copy()
            part_day['x'] = converted_data[i-1]['x'] + ( converted_data[i]['x'] - converted_data[i-1]['x']) / 4 * 2
            part_day['y'] = converted_data[i-1]['y'] + (converted_data[i]['y'] - converted_data[i-1]['y']) / 4 * 2
            addition_data.append(part_day)
            part_day = day.copy()
            part_day['x'] = converted_data[i-1]['x'] + ( converted_data[i]['x'] - converted_data[i-1]['x']) / 4 * 3
            part_day['y'] = converted_data[i-1]['y'] + (converted_data[i]['y'] - converted_data[i-1]['y']) / 4 * 3
            addition_data.append(part_day)
        addition_data.append(day)
    return render_template("dashboard.html",
                           data=addition_data,
                           game_info=response,
                           game_name=name,
                           game_id=game_id,
                           comments=comments,
                           emotion_color = emotion_color)


from flask import Blueprint, jsonify, render_template, redirect, request
from flask_login import login_required, current_user
from app.forms.create_edit_post import CreatePostForm, EditPostForm
from app.forms.comment_forms import CreateCommentForm
from app.models import db, Follow, Post, Comment, User
from datetime import datetime

post_routes = Blueprint('posts', __name__)

#** get all posts on database **#
@post_routes.route('/explore')
@login_required
def get_all_posts():
    posts = []
    all_posts_query = Post.query.order_by(Post.created_at.desc())
    all_posts = [post.to_dict_num_comments() for post in all_posts_query]

    for post in all_posts:
        user = User.query.get(post['user_id'])
        posts.append(user)

    users = [post.user_content() for post in posts]

    for i in range(len(users)):
        all_posts[i]['User'] = users[i]

    return {'Posts': all_posts}

#** Get all posts from the following feed **#
@post_routes.route('/')
@login_required
def get_posts():
    posts = []
    all_followed_posts = Post.query.join(Follow, Follow.follows_id == Post.user_id).filter(
        Follow.user_id == current_user.id).order_by(Post.created_at.desc())

    followed_posts = [post.feed_to_dict() for post in all_followed_posts]

    all_post = followed_posts

    for post in all_post:
        user = User.query.get(post['user_id'])
        posts.append(user)

    users = [post.user_content() for post in posts]

    for i in range(len(users)):
        all_post[i]['User'] = users[i]

    return {'Posts': all_post}

#** Get post by id **#
@post_routes.route('/<int:post_id>')
@login_required
def post_details(post_id):
    all_posts = Post.query.filter(Post.id == post_id)
    post = [post.post_details() for post in all_posts]
    user = User.query.get(post[0]['user_id'])
    post[0]['User'] = user.user_content()
    if post:
        return post[0]
    else:
        return jsonify({"Not Found": "Post not found", "Status Code": 404}), 404

#** Create a post **#
@post_routes.route('/form', methods=["POST"])
@login_required
def create_post():
    data = request.json
    new_post = Post(
        user_id=current_user.id,
        caption=data['caption'],
        post_url=data['post_url'],
    )
    db.session.add(new_post)
    db.session.commit()
    return new_post.to_dict(), 201

@post_routes.route('/<int:post_id>/comments')
@login_required
def get_post_comments(post_id):
    post = Post.query.get(post_id)

    if post:
        comments = Comment.query.filter(Comment.post_id == post_id)
        if comments:
            return jsonify(Comments=[comment.to_dict() for comment in comments])

    return jsonify(message='Post not found'), 404

# create a comment providing user_id, post_id, and body
@post_routes.route('/<int:post_id>/comments', methods=['POST'])
@login_required
def create_comment(post_id):
    form = CreateCommentForm()

    form["csrf_token"].data = request.cookies["csrf_token"]

    post = Post.query.get(post_id)

    # check if post exists
    if not post:
        return jsonify({"Not Found": "Post not found", "Status Code": 404}), 404

    if form.validate_on_submit():
        data = form.data

        comment = Comment(user_id=current_user.id,
                          post_id=post_id,
                          body=data['body'])

        db.session.add(comment)
        db.session.commit()
        return comment.to_dict()

#** Edit a post **#
@post_routes.route('/<int:post_id>', methods=["PUT"])
@login_required
def edit_post(post_id):
    form = EditPostForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    post = Post.query.get(post_id)
    if post:
        if post.user_id == current_user.id:
            post_caption = post.caption
            if form.validate_on_submit():
                data = form.data
                post.caption = data['caption']
                post.updated_at = datetime.now()
                db.session.add(post)
                db.session.commit()
                return post.to_dict()
            return render_template('edit_post.html', form=form, post_id=post_id, post_caption=post_caption)
        else:
            return jsonify({"Forbidden": "You cannot edit this post", "Status Code": 403}), 403
    else:
        return jsonify({"Not found": "Post not found", "Status Code": 404}), 404

#** Delete a post **#
@post_routes.route('/<int:post_id>', methods=['DELETE'])
@login_required
def delete_post(post_id):
    post = Post.query.get(post_id)

    if post:
        if post.user_id == current_user.id:
            db.session.delete(post)
            db.session.commit()
            return post.to_dict()
        else:
            return jsonify({"Forbidden": "You cannot delete this post", "Status Code": 403}), 403
    else:
        return jsonify({"Not found": "Post not found", "Status Code": 404}), 404


"""
This file contains implementation of SpecRNet architecture.
We base our codebase on the implementation of RawNet2 by Hemlata Tak (tak@eurecom.fr).
It is available here: https://github.com/asvspoof-challenge/2021/blob/main/LA/Baseline-RawNet2/model.py
"""
from typing import Dict

import torch.nn as nn

from src import frontends

def get_config(input_channels: int) -> Dict:
    return {
        "filts": [input_channels, [input_channels, 20], [20, 64], [64, 64]],
        "nb_fc_node": 64,
        "gru_node": 64,
        "nb_gru_layer": 2,
        "nb_classes": 1,
    }

class Residual_block2D(nn.Module):
    def __init__(self, nb_filts, first=False):
        super().__init__()
        self.first = first

        if not self.first:
            self.bn1 = nn.BatchNorm2d(num_features=nb_filts[0])

        self.lrelu = nn.LeakyReLU(negative_slope=0.3)

        self.conv1 = nn.Conv2d(
            in_channels=nb_filts[0],
            out_channels=nb_filts[1],
            kernel_size=3,
            padding=1,
            stride=1,
        )

        self.bn2 = nn.BatchNorm2d(num_features=nb_filts[1])
        self.conv2 = nn.Conv2d(
            in_channels=nb_filts[1],
            out_channels=nb_filts[1],
            padding=1,
            kernel_size=3,
            stride=1,
        )

        if nb_filts[0] != nb_filts[1]:
            self.downsample = True
            self.conv_downsample = nn.Conv2d(
                in_channels=nb_filts[0],
                out_channels=nb_filts[1],
                padding=0,
                kernel_size=1,
                stride=1,
            )

        else:
            self.downsample = False
        self.mp = nn.MaxPool2d(2)

    def forward(self, x):
        identity = x
        if not self.first:
            out = self.bn1(x)
            out = self.lrelu(out)
        else:
            out = x

        out = self.conv1(x)
        out = self.bn2(out)
        out = self.lrelu(out)
        out = self.conv2(out)

        if self.downsample:
            identity = self.conv_downsample(identity)

        out += identity
        out = self.mp(out)
        return out

class SpecRNet(nn.Module):
    def __init__(self, input_channels, **kwargs):
        super().__init__()
        config = get_config(input_channels=input_channels)

        self.device = kwargs.get("device", "cuda")

        self.first_bn = nn.BatchNorm2d(num_features=config["filts"][0])
        self.selu = nn.SELU(inplace=True)
        self.block0 = nn.Sequential(
            Residual_block2D(nb_filts=config["filts"][1], first=True)
        )
        self.block2 = nn.Sequential(Residual_block2D(nb_filts=config["filts"][2]))
        config["filts"][2][0] = config["filts"][2][1]
        self.block4 = nn.Sequential(Residual_block2D(nb_filts=config["filts"][2]))
        self.avgpool = nn.AdaptiveAvgPool2d(1)

        self.fc_attention0 = self._make_attention_fc(
            in_features=config["filts"][1][-1], l_out_features=config["filts"][1][-1]
        )
        self.fc_attention2 = self._make_attention_fc(
            in_features=config["filts"][2][-1], l_out_features=config["filts"][2][-1]
        )
        self.fc_attention4 = self._make_attention_fc(
            in_features=config["filts"][2][-1], l_out_features=config["filts"][2][-1]
        )

        self.bn_before_gru = nn.BatchNorm2d(num_features=config["filts"][2][-1])
        self.gru = nn.GRU(
            input_size=config["filts"][2][-1],
            hidden_size=config["gru_node"],
            num_layers=config["nb_gru_layer"],
            batch_first=True,
            bidirectional=True,
        )

        self.fc1_gru = nn.Linear(
            in_features=config["gru_node"] * 2, out_features=config["nb_fc_node"] * 2
        )

        self.fc2_gru = nn.Linear(
            in_features=config["nb_fc_node"] * 2,
            out_features=config["nb_classes"],
            bias=True,
        )

        self.sig = nn.Sigmoid()

    def _compute_embedding(self, x):
        x = self.first_bn(x)
        x = self.selu(x)

        x0 = self.block0(x)
        y0 = self.avgpool(x0).view(x0.size(0), -1)
        y0 = self.fc_attention0(y0)
        y0 = self.sig(y0).view(y0.size(0), y0.size(1), -1)
        y0 = y0.unsqueeze(-1)
        x = x0 * y0 + y0

        x = nn.MaxPool2d(2)(x)

        x2 = self.block2(x)
        y2 = self.avgpool(x2).view(x2.size(0), -1)
        y2 = self.fc_attention2(y2)
        y2 = self.sig(y2).view(y2.size(0), y2.size(1), -1)
        y2 = y2.unsqueeze(-1)
        x = x2 * y2 + y2

        x = nn.MaxPool2d(2)(x)

        x4 = self.block4(x)
        y4 = self.avgpool(x4).view(x4.size(0), -1)
        y4 = self.fc_attention4(y4)
        y4 = self.sig(y4).view(y4.size(0), y4.size(1), -1)
        y4 = y4.unsqueeze(-1)
        x = x4 * y4 + y4

        x = nn.MaxPool2d(2)(x)

        x = self.bn_before_gru(x)
        x = self.selu(x)
        x = nn.AdaptiveAvgPool2d((1, None))(x)
        x = x.squeeze(-2)
        x = x.permute(0, 2, 1)
        self.gru.flatten_parameters()
        x, _ = self.gru(x)
        x = x[:, -1, :]
        x = self.fc1_gru(x)
        x = self.fc2_gru(x)
        return x

    def forward(self, x):
        x = self._compute_embedding(x)
        return x

    def _make_attention_fc(self, in_features, l_out_features):
        l_fc = []
        l_fc.append(nn.Linear(in_features=in_features, out_features=l_out_features))
        return nn.Sequential(*l_fc)

class FrontendSpecRNet(SpecRNet):
    def __init__(self, input_channels, **kwargs):
        super().__init__(input_channels, **kwargs)

        self.device = kwargs['device']

        frontend_name = kwargs.get("frontend_algorithm", [])
        self.frontend = frontends.get_frontend(frontend_name)
        print(f"Using {frontend_name} frontend")

    def _compute_frontend(self, x):
        frontend = self.frontend(x)
        if frontend.ndim < 4:
            return frontend.unsqueeze(1)  # (bs, 1, n_lfcc, frames)
        return frontend # (bs, n, n_lfcc, frames)

    def forward(self, x):
        x = self._compute_frontend(x)
        x = self._compute_embedding(x)
        return x

if __name__ == "__main__":
    print("Definition of model")
    device = "cuda"

    input_channels = 1
    config = {
        "filts": [input_channels, [input_channels, 20], [20, 64], [64, 64]],
        "nb_fc_node": 64,
        "gru_node": 64,
        "nb_gru_layer": 2,
        "nb_classes": 1,
    }

    def count_parameters(model) -> int:
        pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
        return pytorch_total_params
    model = FrontendSpecRNet(input_channels=1, device=device, frontend_algorithm=["lfcc"])
    model = model.to(device)
    print(count_parameters(model))


#!/usr/bin/python3
"""Module for Base Class"""
import json

class Base:
    """Base Class"""
    __nb_objects = 0

    def __init__(self, id=None):
        """__init__: method that initialize an object"""
        if id is None:
            Base.__nb_objects += 1
            self.id = Base.__nb_objects
        else:
            self.id = id

    @classmethod
    def create(cls, **dictionary):
        """create: class method that returns an instance with all attributes
            already set
        Args:
            dictionary: double pointer to a dictionary to update an object
        Return:
            The new instance with the attributes set
        """
        if dictionary and dictionary != {}:
            if cls.__name__ == "Rectangle":
                new_object = cls(1, 1)
            elif cls.__name__ == "Square":
                new_object = cls(1)
            new_object.update(**dictionary)
            return new_object

    @classmethod
    def load_from_file(cls):
        """save_to_file: class method that returns a list of instances
        Return:
            A list of instances
        """
        filename = cls.__name__ + '.json'
        try:
            with open(filename, mode='r', encoding='utf-8') as r_file:
                content = r_file.read()
                list_of_dict = cls.from_json_string(content)
                if list_of_dict is None or len(list_of_dict) == 0:
                    return []
                else:
                    if all(type(obj) == dict for obj in list_of_dict):
                        list_of_ins = [cls.create(**item) for item in
                                       list_of_dict]
                        return list_of_ins
                    return []
        except Exception:
            return []

    @classmethod
    def save_to_file(cls, list_objs):
        """save_to_file: class method that writes the JSON string
            representation of list_objs to a file
        Args:
            list_objs: list of objects who inherits of Base
        """
        value = None
        if list_objs is None:
            value = []
        elif type(list_objs) == list and all(issubclass(type(a), Base) for a in
                                             list_objs):
            value = [obj.to_dictionary() for obj in list_objs]
        if value is not None:
            filename = cls.__name__ + '.json'
            with open(filename, mode='w', encoding='utf-8') as r_file:
                r_file.write(cls.to_json_string(value))

    @classmethod
    def load_from_file_csv(cls):
        """save_to_file: class method that returns a list of instances
        Return:
            A list of instances
        """
        filename = cls.__name__ + '.csv'
        list_of_objs = []
        try:
            with open(filename, mode='r', encoding='utf-8') as r_file:
                for line in r_file:
                    words = line.split(sep=',')
                    new_obj = None
                    if len(words) == 5:
                        new_obj = cls(int(words[1]), int(words[2]),
                                      int(words[3]), int(words[4]),
                                      int(words[0]))
                    if len(words) == 4:
                        new_obj = cls(int(words[1]), int(words[2]),
                                      int(words[3]), int(words[0]))
                    if new_obj is not None:
                        list_of_objs.append(new_obj)
            return list_of_objs
        except Exception:
            return []

    @classmethod
    def save_to_file_csv(cls, list_objs):
        """save_to_file: class method that writes the JSON string
            representation of list_objs to a csv file
        Args:
            list_objs: list of objects who inherits of Base
        """
        value = None
        if type(list_objs) == list and all(issubclass(type(a), Base) for a in
                                           list_objs):
            value = ""
            for obj in list_objs:
                if cls.__name__ == 'Rectangle':
                    value += (str(obj.id) + ',' + str(obj.width) + ',' +
                              str(obj.height) + ',' + str(obj.x) + ',' +
                              str(obj.y) + '\n')
                if cls.__name__ == 'Square':
                    value += (str(obj.id) + ',' + str(obj.size) + ',' +
                              str(obj.x) + ',' + str(obj.y) + '\n')
        if value is not None:
            filename = cls.__name__ + '.csv'
            with open(filename, mode='w', encoding='utf-8') as r_file:
                r_file.write(value)

    @staticmethod
    def from_json_string(json_string):
        """from_json_string: static method that returns the list of the JSON
            string representation
        Args:
            json_string: string representing a list of dictionaries
        Return:
            The list of the JSON string representation
        """
        list_of_objs = []
        if json_string is None:
            return list_of_objs
        if type(json_string) == str:
            if len(json_string) == 0:
                return list_of_objs
            try:
                list_of_objs = json.loads(json_string)
                if type(list_of_objs) == list:
                    if len(list_of_objs) == 0:
                        return list_of_objs
                    if all(type(obj) == dict for obj in list_of_objs):
                        return list_of_objs
            except Exception:
                return None

    @staticmethod
    def to_json_string(list_dictionaries):
        """to_json_string: static method that returns the JSON string
            representation of list_dictionaries
        Args:
            list_dictionaries: list of dictionaries containing data
            representation
        Return:
            A JSON string
        """
        if list_dictionaries is None or list_dictionaries == []:
            return "[]"
        return json.dumps(list_dictionaries)


import numpy as np
from scipy.optimize import fsolve
from inputs import *

npts = 50  # Number of pts on streamline
np_inlt = 5
np_inlt_eq = 2
stp = 0.1
np_outlt = 25
bw = np.zeros(nstations)
gamma = np.zeros(nstations)
#------------------------------------------------------------------------------
#==============================================================================
# Generating streamlines at hub nad tip using the krain single-stage compressor
#==============================================================================

def streamlines():
# Hub
    r_hub = np.linspace(R_hub_le, R_hub_te, npts)
    x_hub = X01 + (R**2 - (r_hub - R01)**2)**0.5
# Casing
    r_tip = np.linspace(R_tip_le, R_tip_te, npts)
    x_tip = X04 + (ae / be) * (be**2 - (r_tip - R04)**2)**0.5

# Non-dimesionalizing with leading edge hub radius as scaling factor
    bsf = r_tip[0]
    x_hub_nd = x_hub / bsf
    r_hub_nd = r_hub / bsf
    x_tip_nd = x_tip / bsf
    r_tip_nd = r_tip / bsf

#------------------------------------------------------------------------------
#==============================================================================
# Splitting the blade into 3 parts for rotor and stator
#==============================================================================

    # x = np.array((npts,nstations))
    # r = np.array((npts,nstations))

    r_s[0, :] = np.array([r_hub[0], r_tip[0]])
    x_s[0, :] = np.array([x_hub[0], x_tip[0]])
    for i in range(1, nstations):
        if i == nstations - 1:
            r_s[-1, :] = np.array([r_hub[-1], r_tip[-1]])
            x_s[-1, :] = np.array([x_hub[-1], x_tip[-1]])
        else:
            r_s[i, :] = r_s[i - 1, :] + gap[i - 1]
            x_s[i, :] = np.array([X01 + (R**2 - (r_s[i, 0] - R01)**2)**0.5, X04 + (ae / be) * (be**2 -
                                                                                (r_s[i, 1] - R04)**2)**0.5])

#-----------------------------Stator-------------------------------------------
#            r_s[2, :] = r_s[1, :]+gap
#            x_s[2, :] = np.array([X01 + (R**2-(r_s[2, 0]-R01)**2)**0.5,X04 + (ae/be)*(be**2-
#                      (r_s[2, 1]-R04)**2)**0.5])
#
#            r_s[3, :] = r_s[2, :]+s1_len
#            x_s[3, :] = np.array([X01 + (R**2-(r_s[3, 0]-R01)**2)**0.5,X04 + (ae/be)*(be**2-
#                      (r_s[3, 1]-R04)**2)**0.5])
#
#--------------------------------Rotor 2---------------------------------------
#            r_s[4, :] = r_s[3, :]+gap
#            x_s[4, :] = np.array([X01 + (R**2-(r_s[4, 0]-R01)**2)**0.5,X04 + (ae/be)*(be**2-
#                      (r_s[4, 1]-R04)**2)**0.5])

#----------------Area calculation at inlet and oultlet-------------------------
    for i in range(nstations):
        # Station 1(Inlet)
        rm[i] = np.mean(r_s[i, :])
        xm[i] = np.mean(x_s[i, :])
        area[i] = np.pi * (sum(r_s[i, :])) * ((r_s[i, 0] -
                                               r_s[i, 1])**2 + (x_s[i, 0] - x_s[i, 1])**2)**0.5
    bw = ((x_s[:, 0] - x_s[:, 1])**2 + (r_s[:, 0] - r_s[:, 1])**2)**0.5
    phi = np.fabs(np.degrees(
        np.arctan((r_s[:, 0] - r_s[:, 1]) / (x_s[:, 0] - x_s[:, 1]))))
    gamma = 90 - phi

#-----------------------------Streamlines--------------------------------------

    # Inlet Streamlines
    x_inlt = np.zeros(np_inlt) + (-stp * np_inlt)
    r_hub_inlt = np.zeros(np_inlt)
    r_tip_inlt = np.ones(np_inlt) * r_tip_nd[0]
    for i in range(0, np_inlt - 1):
        x_inlt[i + 1] = x_inlt[i] + stp

    for j in range(np_inlt - 1, -1, -1):
        if j >= np_inlt - np_inlt_eq:
            r_hub_inlt[j] = R01 / bsf - \
                ((R / bsf)**2 - (x_inlt[j] - (X01 / bsf))**2)**0.5
        else:
            r_hub_inlt[j] = r_hub_inlt[j + 1]

    # Outlet Streamlines
    R_DiffuserExit_nd = R_DiffuserExit / bsf
    r_outlt = np.linspace(r_hub_nd[-1], R_DiffuserExit_nd, np_outlt + 1)
    r_outlt = r_outlt[1:]
    x_hub_outlt = np.zeros(np_outlt) + x_hub_nd[-1]
    x_tip_outlt = np.zeros(np_outlt)

    # Diffuser
    Aoutlt = 2 * np.pi * (x_hub_nd[-1] - x_tip_nd[-1]) * r_hub_nd[-1]
    Aexit = 0.99 * (Aoutlt)

    area_diff = np.linspace(Aoutlt, Aexit, np_outlt)
    x_tip_outlt = x_hub_outlt - area_diff / (2 * np.pi * r_outlt)

    x_hub_nd = np.hstack((x_inlt, x_hub_nd, x_hub_outlt))
    r_hub_nd = np.hstack((r_hub_inlt, r_hub_nd, r_outlt))
    x_tip_nd = np.hstack((x_inlt, x_tip_nd, x_tip_outlt))
    r_tip_nd = np.hstack((r_tip_inlt, r_tip_nd, r_outlt))

    xsl = np.zeros((nsect, len(x_hub_nd)))
    rsl = np.zeros((nsect, len(x_hub_nd)))
    xsl_mean = np.zeros((1,len(x_hub_nd)))
    rsl_mean = np.zeros((1,len(x_hub_nd)))
    for j in range(len(x_hub_nd)):
        xsl[:, j] = np.linspace(x_hub_nd[j], x_tip_nd[j], nsect)
        rsl[:, j] = np.linspace(r_hub_nd[j], r_tip_nd[j], nsect)

#Calculating for LE and TE of blade rows using rm values
    xsl_mean = xsl[mean_num, :]*bsf
    rsl_mean =  rsl[mean_num, :]*bsf
    for i in range(0, nstations):
        #Searching for lower and upper r-values
        upb = rsl_mean>rm[1]
        lpb = rsl_mean<rm[1]
        upper_bound_r = rsl_mean[upb].min()
        lower_bound_r = rsl_mean[lpb].max()
        #Finding index of arry for lower and upper r-values
        mini = np.where(rsl_mean == lower_bound_r)
        maxi = np.where(rsl_mean == upper_bound_r)
        #Finding lower and upper x-values corresponding to r-values through index search
        upper_bound_x = xsl_mean[maxi[0][0]]
        lower_bound_x = xsl_mean[mini[0][0]]
        points = [(lower_bound_x, lower_bound_r), (upper_bound_x, upper_bound_r)]
        x_coords, r_coords = zip(*points)
        A = np.vstack([x_coords, np.ones(len(x_coords))]).T
        m, c = np.linalg.lstsq(A, r_coords)[0]
        def eq_hub(p):
            x, r = p
            return (r-m*x-c, x-X01 + (R**2 - (r - R01)**2)**0.5)
        x, r = fsolve(eq_hub, (lower_bound_x, lower_bound_r))
    return xm, rm, area, x_s, r_s, bsf, xsl, rsl, bw, gamma, m,c


import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import gym

from td_lambda.q_learning import plot_cost_to_go, plot_running_avg

class HiddenLayer:
    def __init__(self, M1, M2, f=tf.nn.tanh):
        self.W = tf.Variable(tf.random_normal(shape=(M1, M2)) * np.sqrt(2. / M1, dtype=np.float32))
        self.bias = tf.Variable(np.zeros(M2).astype(np.float32))
        self.f = f

    def forward(self, X):
        return self.f(tf.matmul(X, self.W) + self.bias)

class PolicyModel:
    def __init__(self, D, K, hidden_layer_sizes=[]):
        """
        :param D: input dimension (observation dimension)
        :param K: number of action, output dimension
        :param hidden_layer_sizes: size of neurons in hidden layers
        """
        self.layers = []
        M1 = D
        for M2 in hidden_layer_sizes:
            layer = HiddenLayer(M1, M2)
            self.layers.append(layer)
            M1 = M2

        # last layer
        self.layers.append(HiddenLayer(M1, K, tf.nn.softmax))

        self.X = tf.placeholder(tf.float32, shape=(None, D), name='X')
        self.actions = tf.placeholder(tf.int32, shape=(None,), name='actions')
        self.advantages = tf.placeholder(tf.float32, shape=(None,), name='advantage')

        # Calculate the output
        Z = self.X
        for layer in self.layers:
            Z = layer.forward(Z)
        p_a_given_s = Z
        self.predict_op = p_a_given_s

        # keeping only the prob for the action taken
        selected_prob = tf.log(
            tf.reduce_sum(p_a_given_s * tf.one_hot(self.actions, K), reduction_indices=[1]))
        cost = -tf.reduce_sum(self.advantages * selected_prob)

        self.train_op = tf.train.AdagradOptimizer(10e-2).minimize(cost)

    def set_session(self, sesstion):
        self.session = sesstion

    def partial_fit(self, X, actions, advantages):
        # Check dimension
        X = np.atleast_2d(X)
        actions = np.atleast_1d(actions)
        advantages = np.atleast_1d(advantages)

        self.session.run(self.train_op, feed_dict={
            self.X: X,
            self.actions: actions,
            self.advantages: advantages
        })

    def predict(self, X):
        X = np.atleast_2d(X)
        return self.session.run(self.predict_op, feed_dict={self.X: X})

    def sample_action(self, X):
        p = self.predict(X)[0]
        return np.random.choice(len(p), p=p)

class ValueModel:
    def __init__(self, D, hidden_layers_sizes):
        self.layers = []
        M1 = D
        for M2 in hidden_layers_sizes:
            layer = HiddenLayer(M1, M2)
            self.layers.append(layer)
            M1 = M2

        # final layer
        layer = HiddenLayer(M1, 1, lambda x: x)
        self.layers.append(layer)

        # inputs and targets
        self.X = tf.placeholder(tf.float32, shape=(None, D), name='X')
        self.Y = tf.placeholder(tf.float32, shape=(None, ), name='Y')

        # Calculate output and cost
        Z = self.X
        for layer in self.layers:
            Z = layer.forward(Z)
        y_hat = tf.reshape(Z, [-1])
        self.predict_op = y_hat

        cost = tf.reduce_sum(tf.square(self.Y - y_hat))
        self.train_op = tf.train.GradientDescentOptimizer(10e-5).minimize(cost)

    def set_session(self, sesstion):
        self.session = sesstion

    def partial_fit(self, X, Y):
        X = np.atleast_2d(X)
        Y = np.atleast_1d(Y)
        self.session.run(self.train_op, feed_dict={self.X: X, self.Y: Y})

    def predict(self, X):
        X = np.atleast_2d(X)
        return self.session.run(self.predict_op, feed_dict={self.X: X})

def play_one_mc(env, pmodel, vmodel, gamma):
    observation = env.reset()
    done = False
    totalreward = 0
    iters = 0

    states = []
    actions = []
    rewards = []

    while not done and iters < 2000:
        action = pmodel.sample_action(observation)
        prev_observatoin = observation
        observation, reward, done , info = env.step(action)

        if done:
            reward = -200

        states.append(prev_observatoin)
        actions.append(action)
        rewards.append(reward)

        if reward == 1:
            totalreward += reward
        iters += 1

    returns = []
    advantages = []
    G = 0
    for s, r in zip(reversed(states), reversed(rewards)):
        returns.append(G)
        advantages.append(G - vmodel.predict(s)[0])
        G = r + gamma*G
    returns.reverse()
    advantages.reverse()

    # update the models
    pmodel.partial_fit(states, actions, advantages)
    vmodel.partial_fit(states, returns)

    return iters, totalreward

if __name__ == '__main__':
    env = gym.make('CartPole-v0')
    D = env.observation_space.shape[0]  # 4
    K = env.action_space.n  # 2
    pmodel = PolicyModel(D, K, [])
    vmodel = ValueModel(D, [10])
    init = tf.global_variables_initializer()
    session = tf.InteractiveSession()
    session.run(init)
    pmodel.set_session(session)
    vmodel.set_session((session))
    gamma = 0.99

    N = 500
    totalrewards = np.empty(N)
    costs = np.empty(N)
    for n in range(N):
        num_steps, totalreward = play_one_mc(env, pmodel, vmodel, gamma)
        totalrewards[n] = totalreward
        if n % 1 == 0:
            print("episode:", n, "total reward: %.1f" % totalreward, "num steps: %d" % num_steps,
                  "avg reward (last 100): %.1f" % totalrewards[max(0, n - 100):(n + 1)].mean())

    print("avg reward for last 100 episodes:", totalrewards[-100:].mean())

    plt.plot(totalrewards)
    plt.title("Rewards")
    plt.show()

    plot_running_avg(totalrewards)


import numpy as np
import matplotlib.pyplot as plt
from skimage.measure import regionprops, label

def neighbours4(y, x):
    return (y-1, x), (y, x+1), (y+1, x), (y, x-1)

def neighbors8(y, x):
    return (y-1, x), (y-1, x+1), (y, x+1), (y+1, x+1), (y+1, x), (y+1, x-1), (y, x-1), (y-1, x-1)

def get_boundaries(region):
    image = region.image * region.label
    label = region.label
    pos = np.where(image == label)
    boundaries = []

    for y, x in zip(*pos):
        for yn, xn in neighbours4(y, x):
            if yn < 0 or yn > image.shape[0]-1:
                boundaries.append((y, x))
                break
            elif xn < 0 or xn > image.shape[1]-1:
                boundaries.append((y, x))
                break
            elif image[yn, xn] != label:
                boundaries.append((y, x))
                break
    return boundaries

def chain_algo(region):
    bounds = get_boundaries(region)
    bounds.append(bounds[0])

    return _chain(bounds)

def _chain(bounds):
    dirs = []
    bounds_len = len(bounds)

    if bounds_len > 0:
        y, x = bounds[0]
        del bounds[0]

        while bounds_len != len(dirs) and len(bounds) != 0:
            for n, (ny, nx) in enumerate(neighbors8(y, x)):
                if (ny, nx) in bounds:
                    dirs.append(n)
                    y, x = ny, nx
                    del bounds[bounds.index((ny, nx))]
                    break
    return dirs

def curvature(chain):
    result = []

    for i in range(len(chain)):
        diff = chain[i-1] - chain[i]
        result.append(diff)

    for i in range(len(chain)):
        result[i] = result[i] % 8
    return result

def match(lhs, rhs):
    # use slices
    if len(lhs) == len(rhs):
        for i in range(0, len(lhs)):
            if np.all(lhs[i:] == rhs[:-i]) == np.all(lhs[:i] == rhs[-i:]):
                return True
    return False

image = np.load("./practice/chain_algo/similar.npy")

labeled = label(image)
regions = regionprops(labeled)

chains = []

plt.imshow(labeled)
plt.show()

for i in range(labeled.max()):
    is_match = False

    chain = curvature(chain_algo(regions[i]))
    for n in range(len(chains)):
        if match(chain, chains[n]):
            is_match = True
            break
    if not is_match:
        chains.append(chain)

print(f"Number of objects: {len(chains)}")


# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author  :
# @file    :
# @Time    : 2023/4/21 14:52
# @Function:
import tkinter as tk
from PIL import ImageTk, Image
from tkinter import filedialog

numbs = 0
def panduan(image):
    global numbs
    rgb_im = image.convert('RGB')

    blue_pixel_count = 0
    threshold = 100
    all1 = image.width * image.height

    for x in range(image.width):

        for y in range(image.height):

            r, g, b = rgb_im.getpixel((x, y))

            if b > threshold:

                if b > r + 20:

                    if b > g + 20:

                        blue_pixel_count += 1

    print("The number of blue pixels:", blue_pixel_count)
    print("百分比:", blue_pixel_count / all1)
    numbs = blue_pixel_count / all1

    if blue_pixel_count/all1 >0.5:
        return True

    return False
FilePath = ""

# 创建根窗口
root = tk.Tk()

root.geometry("840x500")

root.title('Weather Recognition System')

w1 = tk.Label(root, text="")
# canvas = tk.Canvas(root, width=600, height=600)
# canvas.create_rectangle(2, 2, 454, 454, outline='blue', width=2)
# canvas.place(x=20, y=20)
canvas = tk.Canvas(root, width=600, height=600)
# canvas.create_image(0, 0, anchor='nw')
canvas.create_rectangle(2, 2, 454, 454, outline='blue', width=2)
canvas.place(x=20, y=20)
tianqis = ""
photo = ""
image_logo = Image.open("logo.jpg")

logos = ImageTk.PhotoImage(image_logo)
# show photo
# canvas = tk.Canvas(root, width=image_file.width, height=image_file.height)
canvas1 = tk.Canvas(root, width=300, height=300)
canvas1.create_image(0, 0, anchor='nw', image=logos)
canvas1.place(x=550, y=210)
def getfile():
    global FilePath,tianqis,photo

    FilePath = filedialog.askopenfilename(title=u'Open', filetypes=[("Image", ".jpg")])

    if FilePath:
        # 加载图像
        image_file = Image.open(FilePath)
        w, h = image_file.width, image_file.height
        # print(w,h)
        if image_file.width > image_file.height:
            # print("there")
            w = 450
            h = int(image_file.height / (image_file.width / 450))
        elif image_file.height > image_file.width:
            # print("theres")
            h = 450
            w = int(image_file.width / (image_file.height / 450))

        print("wh",w,h)
        img = image_file.resize((w, h), Image.ANTIALIAS)

        tianqis = panduan(img)
        photo = ImageTk.PhotoImage(img)
        # show photo
        # canvas = tk.Canvas(root, width=image_file.width, height=image_file.height)
        canvas.create_image(3, 3, anchor='nw', image=photo)

        canvas.place(x=20, y=20)
        w1 = tk.Label(root, text="                            ",font=('Helvetica', '20'))
        w1.place(x=650, y=130)
        w2 = tk.Label(root, text="                            ", font=('Helvetica', '20'))
        w2.place(x=650, y=170)

tianqi = ["Sunny","Not Sunny"]

def show():
    if tianqis:
        w1 = tk.Label(root, text=tianqi[0],background="red",font=('Helvetica', '20'))
        w1.place(x=650, y=130)
        w2 = tk.Label(root, text=f"{round(numbs*100,4)}%", background="blue", font=('Helvetica', '20'))
        w2.place(x=650, y=170)

    elif photo:
        w1 = tk.Label(root, text=tianqi[1],background="yellow",font=('Helvetica', '20'))
        w1.place(x=650, y=130)
        w2 = tk.Label(root, text=f"{round(numbs*100,4)}%", background="blue", font=('Helvetica', '20'))
        w2.place(x=650, y=170)

    else:
        w1 = tk.Label(root, text="                            ",font=('Helvetica', '20'))
        w1.place(x=650, y=130)
        w2 = tk.Label(root, text="                            ", font=('Helvetica', '20'))
        w2.place(x=650, y=170)

# 创建两个按钮
button1 = tk.Button(root, text="Open Photo", width=20, height=2,command=getfile)
button1.place(x=650,y=20)

button2 = tk.Button(root, text="Calculate Weather", width=20, height=2,command=show)
button2.place(x=650,y=80)

root.mainloop()


import requests
from bs4 import BeautifulSoup
from bs4 import NavigableString
from .basic import html_headers, convert_lang, capitalize_first, color_word, insert_end_dot, emphasie_text

def search(word, lang_source, lang_target):
    lang_source = convert_lang(lang_source)
    lang_target = convert_lang(lang_target)
    lst_definitions = []
    lst_examples = []
    lst_expressions = []
    with requests.Session() as session:
        source = session.get(f'https://www.linguee.com.br/{lang_source}-{lang_target}/search?source=auto&query={word}', headers=html_headers).text
        soup = BeautifulSoup(source, "html.parser")

        definitions = soup.find_all('a', class_='dictLink featured')
        for result in definitions:
            lst_definitions.append(result.get_text())

        examples = soup.find_all('div', class_='example')
        cnt = 0
        for result in examples:
            cnt+=1
            lst_txt = result.get_text().split('—')
            example = insert_end_dot(capitalize_first(lst_txt[0].strip()))
            example = color_word(word,example)
            translated = insert_end_dot(capitalize_first(lst_txt[1].strip()))
            lst_examples.append('"'+example+'"')

            term = result.parent.parent.find('h3').find('a')
            term = "".join([t for t in term.contents if type(t)==NavigableString])
            term = term.strip()

            lst_examples.append(f'"{translated}" {emphasie_text(term)}
')

        cnt=0
        inexact = soup.find('div', class_='example_lines inexact')
        if inexact is not None:
            lemmas = inexact.find_all('div', class_='lemma singleline')
            for lemma in lemmas:
                cnt+=1
                taglemma = lemma.find('span', class_='tag_lemma')
                dictLink_source = taglemma.find('a', class_='dictLink')

                lemmacontent = lemma.find('div', class_='lemma_content')
                dictLink2_target = lemmacontent.find('a', class_='dictLink')

                example = insert_end_dot(dictLink_source.get_text())
                translated = insert_end_dot(dictLink2_target.get_text())

                if example.find(word) > -1:
                    example = color_word(word,example)
                    lst_expressions.append('"'+example+'"')
                    lst_expressions.append('"'+translated+'"
')

    return ['', ','.join(lst_definitions), '', '
'.join(lst_examples), '', '
'.join(lst_expressions)]

#print(search('streak','english','portuguese'))


import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
	frame = cap.read()[1]
	gray = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
	cv2.imshow('frame',gray)
	k=cv2.waitKey(10)
	if k==27:
		break

cv2.destroyAllWindows()


import torch
from torch import nn
from torch.nn import functional as F

from .util import rescale_conv, rescale_module

class WaveUnet(nn.Module):
    def __init__(
        self,
        chin=1,
        chout=1,
        hidden=24,
        depth=5,
        normalize=True,
        rescale=0.1,
        floor=1e-3,
    ):
        """WaveUnet

        Args:
            chin (int, optional): input channels. Defaults to 1.
            chout (int, optional): output channels. Defaults to 1.
            hidden (int, optional): number of initial hidden channels.. Defaults to 24.
            depth (int, optional): number of layers. Defaults to 5.
            normalize (bool, optional): if true, normalize the input. Defaults to True.
            rescale (float, optional): controls custom weight initialization. Defaults to 0.1.
            floor (_type_, optional): stability flooring when normalizing. Defaults to 1e-3.
        """
        super().__init__()

        self.chin = chin
        self.chout = chout
        self.hidden = hidden
        self.depth = depth
        self.floor = floor
        self.normalize = normalize

        self.encoder = nn.ModuleList()
        self.decoder = nn.ModuleList()
        for index in range(depth):
            encode = []
            encode += [
                nn.Conv1d(chin, hidden, 15, 1, 7),
                nn.BatchNorm1d(hidden),
                nn.LeakyReLU(negative_slope=0.1),
            ]
            self.encoder.append(nn.Sequential(*encode))

            decode = []
            decode += [
                nn.Conv1d(hidden, chout, 5, 1, 2),
                nn.BatchNorm1d(chout),
                nn.LeakyReLU(negative_slope=0.1),
            ]

            self.decoder.insert(0, nn.Sequential(*decode))
            chout = hidden
            chin = hidden
            hidden += hidden

        self.middle = nn.Sequential(nn.Conv1d(depth * hidden, depth * hidden, 15, 1, 7))
        if rescale:
            rescale_module(self, reference=rescale)

    def forward(self, mix):
        if mix.dim() == 2:
            mix = mix.unsqueeze(1)

        if self.normalize:
            mono = mix.mean(dim=1, keepdim=True)
            std = mono.std(dim=-1, keepdim=True)
            mix = mix / (self.floor + std)
        else:
            std = 1
        x = mix

        skips = []
        for encode in self.encoder:
            x = encode(x)
            skips.append(x)
            x = x[:, :, ::2]

        # x = self.middle(x)
        for decode in self.decoder:
            skip = skips.pop(-1)
            x = F.interpolate(x, scale_factor=2, mode="linear", align_corners=True)
            x = x + skip[..., : x.shape[-1]]
            x = decode(x)

        return std * x

if __name__ == "__main__":
    model = WaveUnet()

    y = torch.rand((16, 1, 16384))

    print(model(y).shape)


import numpy as np
from .units import Units
import scipy.interpolate as interp
import scipy.integrate as integ
import scipy
import mystats
import collections

class HaloProfileBase:
    def __init__(self):
        print('%s Profile: Interp begins ...'%(self['name']))
        self._tags.update({
            'G': self['units']['G'], 'interp': interp.PchipInterpolator,
            'integ': integ.quad, 'vols': 4.0/3.0*np.pi*self['rs']**3,
        })
        self._interp_IM()
        self._interp_IV()
        self._interp_Isigma()
        self._interp_If()
    def __getitem__(self, key):
        return self._tags[key]
    def rho(self, r):
        return self['rho0']*self._Irho( r/self['rs'] )
    def M(self, r):
        return 3.0*self['Ms']*self._IM( r/self['rs'] )
    def V(self, r):
        return self['V0'] + 3.0*self['Vs']*self._IV( r/self['rs'] )
    def sigma2(self, r):
        x = r/self['rs']
        ans = 3.0*self['Vs']/self._Irho(x)*self._Isigma(x)
        if isinstance(ans, collections.Iterable):
            ans[ans<0.] = 0.
        else:
            if ans<0.: ans = 0.
        return ans
    def r_at_M(self, M):
        ans = self._inv_IM( M/(3.0*self['Ms']) )*self['rs']
        return ans
    def fE(self, E):
        xE = np.log(self['IE_eps']+(E-self['V0'])/(3.0*self['Vs']))
        ans = self['fE0'] * self._IfxE(xE)

        #xE_last = self['xEs'][-400]
        #if isinstance(xE, collections.Iterable):
        #    ans[ xE >= xE_last ] = 0.
        #else:
        #    if xE >= xE_last: ans = 0.

        return ans
    def _Irhoy(self, y):
        return self._Irho( np.exp(y) )
    def _interp_IM(self):
        Irhoy = self._Irhoy
        def f( y ):
            return np.exp( 3.0*y ) * Irhoy(y)
        y_vals = self['y_vals']
        IMys = [ self['integ']( f, self['yin'], y )[0] for y in y_vals ]
        _IMy = self['interp'](y_vals, IMys)
        self._IMy = _IMy
        self._IM = lambda x: _IMy( np.log(x) )
        Ms = self['mass'] / (3.0*_IMy(self['yvir']))
        self._tags.update({'Ms': Ms,
            'rho0':Ms/self['vols'],  'Vs':self['G']*Ms/self['rs']})
        _inv_IMy = self['interp']( IMys, y_vals )
        self._inv_IMy = mystats.InterpBound( IMys[0], IMys[-1], _inv_IMy )
        self._inv_IM = lambda IM: np.exp(_inv_IMy(IM) )
        print('  Interp for M done, IM = [%.4g...%.4g]'%( IMys[0], IMys[-1] ))
    def _interp_IV(self):
        IMy = self._IMy
        def f( y ):
            return IMy(y) / np.exp(y)
        y_vals = self['y_vals']
        IVys = [ self['integ']( f, self['yin'], y )[0] for y in y_vals ]
        _IVy = self['interp']( y_vals, IVys )
        self._IVy = _IVy
        self._IV = lambda x: _IVy( np.log(x) )
        self._tags['V0'] = -3.0*self['Vs']*IVys[-1]
        print('  Interp for V done, IV = [%.4g...%.4g]'%( IVys[0], IVys[-1] ))
    def _interp_Isigma(self):
        IMy, Irhoy = self._IMy, self._Irhoy
        def f(y):
            return IMy(y)*Irhoy(y) / np.exp(y)
        y_vals = self['y_vals']
        Isigmays = []
        for i, y in enumerate(y_vals):
            _int = self['integ']( f, y, self['yt'] )[0]
            Isigmays.append(_int)
        _Isigmay = self['interp'](y_vals, Isigmays)
        self._Isigmay = _Isigmay
        self._Isigma = lambda x: _Isigmay( np.log(x) )
        print('  Interp for sigma done, Isigma = [%.4g...%.4g]'%( Isigmays[0], \
            Isigmays[-1] ))
    def _interp_If(self):
        Irho_eps = 1.0
        IV_eps = q_eps = IE_eps =  0.01
        Int_eps = 1.0
        a_eps = -np.log(q_eps)+q_eps
        self._tags.update( {'Irho_eps':Irho_eps,
            'IV_eps':IV_eps, 'q_eps':q_eps, 'IE_eps':IE_eps,
            'Int_eps':Int_eps, 'a_eps':a_eps} )

        # make the integrand
        # It consists of a detivative drho / dV, or dx_rho / dx_V
        Irhos, IVs = self._Irhoy(self['y_vals']), self._IVy(self['y_vals'])
        xrhos, xVs = np.log( Irho_eps + Irhos ), np.log( IV_eps + IVs )
        _xrhoxV = self['interp']( xVs, xrhos )
        _dxrhoxV = _xrhoxV.derivative()
        expq_eps = np.exp(q_eps)
        def f(q, IE):
            expq = np.exp(q)
            A = expq - expq_eps
            IV = IE + A*A
            xV = np.log( IV_eps + IV )
            xrho = _xrhoxV(xV)
            return expq * _dxrhoxV( xV ) * np.exp(xrho) / np.exp(xV)

        IEs = IVs + 0.
        IEt = IVs[-1]
        Ints = []
        for i, IE in enumerate(IEs):
            f2int = lambda q: f(q, IE)
            q_lo, q_hi = q_eps, np.log(np.sqrt(IEt-IE)+expq_eps)
            Ints.append( self['integ']( f2int, q_lo, q_hi,
                epsrel=1.0e-4, limit=500 )[0] )
        Ints = np.array(Ints)

        # make derivative again
        xEs = np.log( IE_eps + IEs )
        xInts = np.log( Int_eps - Ints )
        self._tags.update({'xEs':xEs,'xInts':xInts,'IEs':IEs})
        _xIntxE = self['interp']( xEs, xInts )
        _dxIntdxE = mystats.InterpBound(xEs[0], xEs[-1], _xIntxE.derivative())
        _xIntxE = mystats.InterpBound(xEs[0], xEs[-1], _xIntxE)
        def _IfxE(xE):
            xInt = _xIntxE(xE)
            dxIntdxE = _dxIntdxE(xE)
            return - np.exp(xInt) / np.exp(xE) * dxIntdxE
        #self._IfxE = mystats.InterpBound(xEs[0], xEs[-400], _IfxE)
        self._IfxE = mystats.InterpBound(xEs[0], xEs[-1], _IfxE)
        self._tags['fE0'] = 2.0/( np.sqrt(8.0)*np.pi*np.pi ) * self['rho0'] \
            / ( 3.0*self['Vs'] )**1.5
        print('  Interp for fE done, xE = [%.4g...%.4g], xInt = [%.4g...%.4g]'%( \
            xEs[0], xEs[-1], xInts[0], xInts[-1] ))

class NFWProfile(HaloProfileBase):
    def __init__(self, mass, rs, rvir=None, rt=None, rw=None,
        r0=None, rcore=None, units=None, name='NFW', tags_kw = {} ):
        self._tags = {'mass': mass, 'name': name}
        self._tags.update(tags_kw)

        _rs = rs
        _rvir = rvir if rvir is not None else 15.0*_rs
        _rt = rt if rt is not None else 2.0*_rvir
        _rw = rw if rw is not None else 0.2*_rvir
        _r0 = r0 if r0 is not None else 1.0e-4*_rs
        _rin = 0.1*_r0
        _rcore = rcore if rcore is not None else 1.0e-10*_rs
        r_vals = np.array([_rin, _r0, _rcore,
            _rs, _rvir, _rw, _rt],dtype=float)

        for ir, rpost in enumerate(('in', '0', 'core', 's', 'vir', 'w', 't')):
            r_val = r_vals[ir]
            self._tags.update({
                'r'+rpost: r_val, 'x'+rpost: r_val/_rs,
                'y'+rpost: np.log(r_val/_rs) })

        self._tags['units'] = units if units else Units()
        y_ins = np.linspace(self['y0'], np.log( 0.8*self['xt'] ), 1500 )
        y_outs = np.log( np.linspace(0.801*self['xt'], self['xt'], 400) )
        self._tags['y_vals'] = np.hstack( (y_ins, y_outs) )
        HaloProfileBase.__init__(self)
    def _Irho(self, x):
        xp1 = 1.0+x
        xpc = self['xcore']+x
        return 1.0 / ( xpc*xp1*xp1 ) * \
            scipy.special.erf( (self['xt']-x)/self['xw'] )

class HernquistProfile(NFWProfile):
    def __init__(self, mass, rs, rvir=None, rt=None, rw=None,
        r0=None, rcore=None, units=None, name='Hernquist' ):
        NFWProfile.__init__(self, mass, rs, rvir, rt, rw,
            r0, rcore, units, name)
    def _Irho(self, x):
        xp1 = 1.0+x
        xpc = self['xcore']+x
        return 1.0/( xpc*xp1*xp1*xp1 ) * \
            scipy.special.erf( (self['xt']-x)/self['xw'] )

class DoublePowerlawProfile(NFWProfile):
    def __init__(self, alpha, beta, gamma,
        mass, rs, rvir=None, rt=None, rw=None,
        r0=None, rcore=None, units=None, name='Double power-law' ):
        tags_kw = { 'alpha': alpha, 'beta': beta, 'gamma':gamma }
        NFWProfile.__init__(self, mass, rs, rvir, rt, rw,
            r0, rcore, units, name, tags_kw=tags_kw)
    def _Irho(self, x):
        alpha, beta, gamma = self['alpha'], self['beta'], self['gamma']
        xpc = self['xcore']+x
        xin = np.power( xpc, gamma )
        xout = np.power( 1.0+np.power(x, 1.0/alpha), (beta-gamma)*alpha )
        return 1.0 / ( xin * xout )


import json
import math
from collections import namedtuple

class Ship(object):

    def __init__(self, owner, map, location, specs):
        assert map[location].ship is None, "Ship already at %s" % location
        self.owner = owner
        owner.ships.add(self)
        self.map = map
        self.location = location
        self.specs = specs
        self.id = hex(id(self))[2:]
        self.level = id(owner) % 5
        self.variant = id(self) % 4
        map.ships[self.id] = self
        self.map[location].ship = self
        self.hp = self.specs.max_hp
        self.ap = self.specs.max_ap
        self.remaining_range = float(self.specs.range)

    def available_moves(self):
        range = min(int(self.remaining_range), self.ap // self.specs.move_ap)
        return [sector for sector in
            self.map.sectors_in_circle(self.location, range)
            if sector.ship is None]

    def move_to(self, location):
        assert self.map[location].ship is None, "Ship already at %s" % location
        old_location = self.location
        dx = location[0] - old_location[0]
        dy = location[1] - old_location[1]
        dist = math.sqrt(dx*dx + dy*dy)
        self.remaining_range = max(0, self.remaining_range - dist)
        self.ap = max(0, self.ap - int(dist) * self.specs.move_ap)
        self.map[old_location].ship = None
        self.map[location].ship = self
        self.location = location
        return old_location, self.location

    def begin_turn(self):
        self.ap = self.specs.max_ap
        self.remaining_range = self.specs.range

    def damage(self, amount):
        self.hp = max(0, self.hp - amount)

    def as_dict(self):
        return {
            'owner': self.owner.as_dict(),
            'specs': self.specs.as_dict(),
            'cls': self.specs.cls,
            'name': self.specs.name,
            'descr': self.specs.descr,
            'id':self.id,
            'race': self.specs.race,
            'range': self.specs.range,
            'level': self.level,
            'variant': self.variant,
            'x': self.location[0],
            'y': self.location[1],
            'hp': self.hp,
            'ap': self.ap,
            }

def dictify(obj, base):
    d = dict(base.__dict__)
    d.update(obj.__class__.__dict__)
    d.update(obj.__dict__)
    for key, val in list(d.items()):
        if key.startswith('_'):
            del d[key]
        else:
            try:
                json.dumps(val)
            except TypeError:
                del d[key]
    return d

class Spec(object):
    """Ship specification"""

    def __init__(self):
        self.name = self.__class__.__name__

    def as_dict(self):
        d = dictify(self, Spec)
        d['weapons'] = [weapon.as_dict() for weapon in self.weapons]
        return d

class Weapon(object):
    """Weapon specification"""
    is_offense = True
    is_defense = True
    is_ranged = False

    def as_dict(self):
        return dictify(self, Weapon)

## Rone ship specs ##

class Scourge(Spec):
    cls = 0
    descr="Fighter"
    race = "rone"
    cost = 10
    range = 4
    move_ap = 2
    max_ap = 10
    max_hp = 24

    class _disruptor(Weapon):
        name = "Phase Disruptor"
        dmg_type = "electromag"
        dmg_level = 3
        max_use = 3
        use_ap = 2

    weapons = [_disruptor()]

class Gotha(Spec):
    cls = 2
    descr="Bomber"
    race = "rone"
    cost = 22
    range = 4
    move_ap = 3
    max_ap = 15
    max_hp = 38

    class _bomb(Weapon):
        name = "Incendiary Bomb"
        dmg_type = "thermal"
        dmg_level = 7
        max_use = 2
        use_ap = 4
        is_defense = False

    class _turret(Weapon):
        name = "Flak Turret"
        dmg_type = "impact"
        dmg_level = 3
        max_use = 4
        use_ap = 2
        is_ranged = True

    weapons = [_bomb(), _turret()]

class Draken(Spec):
    cls = 4
    descr="Dreadnought"
    race = "rone"
    cost = 39
    range = 3
    move_ap = 5
    max_ap = 25
    max_hp = 70

    class _cannon(Weapon):
        name = "Heavy Plasma Cannon"
        dmg_type = "thermal"
        dmg_level = 12
        max_use = 2
        use_ap = 5
        is_ranged = True

    class _turret(Weapon):
        name = "Magneto Pulse"
        dmg_type = "electromag"
        dmg_level = 25
        max_use = 1
        use_ap = 15

    weapons = [_cannon(), _turret()]

## Human Ship Specs ##

class Columbus(Spec):
    cls = 0
    descr="Scout"
    race = "human"
    cost = 12
    range = 5
    move_ap = 3
    max_ap = 16
    max_hp = 19

    class _laser(Weapon):
        name = "Laser Cannon"
        dmg_type = "thermal"
        dmg_level = 3
        max_use = 3
        use_ap = 1

    weapons = [_laser()]

class Pegasus(Spec):
    cls = 2
    descr="Cruiser"
    race = "human"
    cost = 25
    range = 4
    move_ap = 4
    max_ap = 16
    max_hp = 35

    class _phaser(Weapon):
        name = "Phaser"
        dmg_type = "electromag"
        dmg_level = 5
        max_use = 3
        use_ap = 3

    class _missile(Weapon):
        name = "Concussion Missle"
        dmg_type = "impact"
        dmg_level = 8
        max_use = 2
        use_ap = 4
        is_ranged = True

    weapons = [_phaser(), _missile()]

class MacArthur(Spec):
    cls = 3
    descr="Frigate"
    race = "human"
    cost = 42
    range = 3
    move_ap = 5
    max_ap = 22
    max_hp = 56

    class _railgun(Weapon):
        name = "Rail Gun"
        dmg_type = "impact"
        dmg_level = 10
        max_use = 3
        use_ap = 6
        is_ranged = True

    class _torpedo(Weapon):
        name = "Axion Torpedo"
        dmg_type = "electromag"
        dmg_level = 13
        max_use = 2
        use_ap = 10
        is_ranged = True
        is_defense = False

    weapons = [_railgun(), _torpedo()]

## Naree Ship Specs ##

class Milfoil(Spec):
    cls = 0
    descr="Scout"
    race = "naree"
    cost = 15
    range = 6
    move_ap = 2
    max_ap = 15
    max_hp = 16

    class _bloom(Weapon):
        name = "Photon Bloom"
        dmg_type = "electromag"
        dmg_level = 2
        max_use = 5
        use_ap = 1
        is_ranged = True

    weapons = [_bloom()]

class Cress(Spec):
    cls = 1
    descr="Fighter"
    race = "naree"
    cost = 29
    range = 5
    move_ap = 2
    max_ap = 20
    max_hp = 21

    class _beam(Weapon):
        name = "Lepton Beam"
        dmg_type = "thermal"
        dmg_level = 4
        max_use = 4
        use_ap = 2

    weapons = [_beam()]

class Lotus(Spec):
    cls = 3
    descr="Escort Ship"
    race = "naree"
    cost = 53
    range = 4
    move_ap = 4
    max_ap = 30
    max_hp = 45

    class _cannon(Weapon):
        name = "Fullerene Pulse Cannon"
        dmg_type = "impact"
        dmg_level = 8
        max_use = 4
        use_ap = 4
        is_ranged = True

    class _nova(Weapon):
        name = "Energy Nova"
        dmg_type = "electromag"
        dmg_level = 10
        max_use = 3
        use_ap = 5

    weapons = [_cannon(), _nova()]


from django.contrib.auth.models import User
from django.test import Client, TestCase
from django.utils import timezone
from django.utils.translation import deactivate_all

from user_payments.models import LineItem, Payment

class Test(TestCase):
    def setUp(self):
        self.user = User.objects.create_superuser("admin", "admin@test.ch", "blabla")
        deactivate_all()

    def login(self):
        client = Client()
        client.force_login(self.user)
        return client

    def test_model(self):
        self.assertEqual(Payment.objects.create_pending(user=self.user), None)

        LineItem.objects.create(user=self.user, amount=5, title="Something")

        payment = Payment.objects.create_pending(user=self.user)

        self.assertEqual(payment.email, "admin@test.ch")
        self.assertEqual(payment.amount, 5)
        self.assertEqual(
            payment.description, "Payment of 5.00 by admin@test.ch: Something"
        )
        self.assertEqual(str(payment), "Pending payment of 5.00")

        self.assertEqual(LineItem.objects.unbound().count(), 0)
        self.assertEqual(LineItem.objects.unpaid().count(), 1)

        payment.cancel_pending()

        self.assertEqual(Payment.objects.count(), 0)
        self.assertEqual(LineItem.objects.unbound().count(), 1)
        self.assertEqual(LineItem.objects.unpaid().count(), 1)

        payment = Payment.objects.create_pending(
            user=self.user, email="test@example.org"
        )

        # Overridden email address:
        self.assertEqual(payment.email, "test@example.org")

        payment.charged_at = timezone.now()
        payment.save()

        self.assertEqual(LineItem.objects.unbound().count(), 0)
        self.assertEqual(LineItem.objects.unpaid().count(), 0)
        self.assertEqual(str(payment), "Payment of 5.00")

    def test_explicit_lineitems(self):
        LineItem.objects.create(user=self.user, amount=5, title="Something")
        item = LineItem.objects.create(user=self.user, amount=5, title="Something")

        payment = Payment.objects.create_pending(user=self.user, lineitems=[item])
        self.assertEqual(payment.amount, 5)
        self.assertEqual(LineItem.objects.unbound().count(), 1)


from typing import List, Callable
from nltk.tokenize import sent_tokenize
from langchain.text_splitter import (
    RecursiveCharacterTextSplitter,
    TextSplitter,
    NLTKTextSplitter,
)
from transformers import PreTrainedTokenizerFast
from msgpack import Packer, Unpacker

# like `langchain.text_splitter.NLTKTextSplitter` but with configurable language and not small split merging
class NLTKTextSplitter(TextSplitter):
    """Splitting text using NLTK package."""

    def __init__(self, *, language, separator="\n\n", **kwargs):
        """Initialize the NLTK splitter."""
        super().__init__(**kwargs)
        self._tokenizer = lambda x: sent_tokenize(x, language)
        self._separator = separator

    def split_text(self, text: str) -> List[str]:
        """Split incoming text and return chunks."""
        # First we naively split the large input into a bunch of smaller ones.
        splits = self._tokenizer(text)
        return self._merge_splits(splits, self._separator)

class TextSplitterWithBigChunkSplitter(TextSplitter):
    def __init__(
        self,
        *,
        primary: TextSplitter,
        secondary: TextSplitter,
        hard_chunk_size_limit: int,
        length_function: Callable[[str], int]
    ):
        # setting chunk_size = hard_max_chunk is needed for using self._merge_splits
        super().__init__(
            chunk_size=hard_chunk_size_limit,
            chunk_overlap=0,
            length_function=length_function,
        )
        self._primary = primary
        self._secondary = secondary
        self._hard_chunk_size_limit = hard_chunk_size_limit

    def split_text(self, text: str) -> List[str]:
        main_splits = self._primary.split_text(text)

        # remove snippets that are larger than hard_max_chunk
        no_big_splits = []
        for split in main_splits:
            if self._length_function(split) > self._hard_chunk_size_limit:
                secondary_splits = self._secondary.split_text(split)
                no_big_splits.extend(secondary_splits)
            else:
                no_big_splits.append(split)

        return self._merge_splits(no_big_splits, "\n")

class SnippetExtractor(TextSplitterWithBigChunkSplitter):
    def __init__(
        self,
        *,
        language: str,
        chunk_size: int,
        hard_chunk_size_limit: int,
        tokenizer,
    ):
        token_len = lambda s: len(tokenizer(s).input_ids)
        super().__init__(
            primary=NLTKTextSplitter(
                language=language,
                chunk_size=chunk_size,
                chunk_overlap=0,
                length_function=token_len,
            ),
            secondary=RecursiveCharacterTextSplitter(
                chunk_size=chunk_size, chunk_overlap=0, length_function=token_len
            ),
            hard_chunk_size_limit=hard_chunk_size_limit,
            length_function=token_len,
        )

def ok(value: any) -> dict:
    return { 'Ok': value }
def err(value: any) -> dict:
    return { 'Err': str(value) }

def run_stdio_client():
    import sys
    tokenizers = {}

    # There is some bad interaction between stdin Binary I/O buffering code
    # and the Unpacker with can lead to hangs. Using Raw I/O avoids this issue.
    stdin = sys.stdin.buffer.raw
    stdout = sys.stdout.buffer

    # Disable buffer size safety check, we already checked it on the rust side
    # and keeping that option is sync is another potential source of bugs.
    unpacker = Unpacker(stdin, max_buffer_size = 0)
    packer = Packer()

    stdout.write(packer.pack("ready"));
    stdout.flush()

    for msg in unpacker:
        result = None
        try:
            tag = msg['tag']
            cmd = msg['cmd']
            if tag == 'initialize_tokenizer':
                tokenizers[cmd['name']] = PreTrainedTokenizerFast(tokenizer_file=cmd['path'])
                result = ok(True)
            elif tag == 'extract':
                snippets = SnippetExtractor(
                    language = cmd['language'],
                    chunk_size = cmd['chunk_size'],
                    hard_chunk_size_limit = cmd['hard_chunk_size_limit'],
                    tokenizer = tokenizers[cmd['tokenizer']],
                ).split_text(cmd['document'])
                result = ok(snippets)
            elif tag == 'ping':
                result = ok(True)
            else:
                result = err(f"unknown command: {tag}")
        except Exception as error:
            result = err(error)
        finally:
            stdout.write(packer.pack(result))
            stdout.flush()

if __name__ == '__main__':
    run_stdio_client()


# tweepy-bots/bots/config.py
import tweepy
import logging
import os

logger = logging.getLogger()

def create_api(a,b,c,d):
    consumer_key = a
    consumer_secret = b
    access_token = c
    access_token_secret = d

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True,
        wait_on_rate_limit_notify=True)
    try:
        api.verify_credentials()
    except Exception as e:
        logger.error("Error creating API", exc_info=True)
        raise e
    logger.info("API created")
    return api


from django.urls import path
from CookingHeaven.accounts import admin
from CookingHeaven.main import views
from CookingHeaven.main.views import generic, category, admin_panel, unit, err
from CookingHeaven.main.views import recipe

urlpatterns = [
    path('', generic.IndexTemplateView.as_view(), name='home'),
    path('dashboard/', generic.DashboardView.as_view(), name='dashboard'),

    path('recipe/create/', recipe.RecipeCreateView.as_view(), name='recipe create'),
    path('recipe/update/<int:pk>/', recipe.RecipeUpdateView.as_view(), name='recipe update'),
    path('recipe/delete/<int:pk>/', recipe.RecipeDeleteView.as_view(), name='recipe delete'),
    path('recipe/details/<int:pk>/', recipe.RecipeDetailsView.as_view(), name='recipe details'),
    path('recipe/like/<int:pk>/', recipe.LikeButtonView.as_view(), name='recipe like'),
    path('recipe/search/', recipe.RecipeSearchView.as_view(), name='recipe search'),
    path('category/create/', category.CategoryCreateView.as_view(), name='category create'),
    path('category/list/', category.CategoryListView.as_view(), name='category list'),
    path('category/update/<int:pk>', category.CategoryUpdateView.as_view(), name='category update'),
    path('category/delete/<int:pk>', category.CategoryDeleteView.as_view(), name='category delete'),

    path('unit/create/', unit.UnitCreateView.as_view(), name='unit create'),
    path('unit/list/', unit.UnitListView.as_view(), name='unit list'),
    path('unit/update/<int:pk>', unit.UnitUpdateView.as_view(), name='unit update'),
    path('unit/delete/<int:pk>', unit.UnitDeleteView.as_view(), name='unit delete'),

    path('error_page/', err.error_page, name= 'error page'),

    path('admin-panel/', admin_panel.AdminPanelView.as_view(), name='admin panel')

]


from django.urls import path
from AppBlog.views import *

urlpatterns = [

path('', destinosLeer, name = 'inicio'),
path('destinos', destinos, name='destinos'),
path('nosotros', nosotros, name='nosotros'),
path('destinosForm', destinosFormulario, name='destinosForm'),
path('destinosLeer', destinosLeer, name='destinosLeer'),
path('destinosEliminar/<id>', destinosEliminar, name='destinosEliminar'),
path('destinosEditar/<id>', destinosEditar, name='destinosEditar'),
]


import pygame

# Initialize Pygame
pygame.init()

# Get the screen dimensions
screen_info = pygame.display.Info()
screen_width = screen_info.current_w
screen_height = screen_info.current_h

# Create the screen
screen = pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)

# Set the pixel color
pixel_color = (255, 0, 0)  # Red color (RGB values)

# Set the pixel position to the center of the screen
pixel_position = (screen_width // 2, screen_height // 2)

# Draw the pixel on the screen
screen.set_at(pixel_position, pixel_color)
pygame.display.update()

# Wait for a keypress or a certain time
pygame.time.wait(3000)  # Wait for 3 seconds

# Quit Pygame
pygame.quit()


import matplotlib.pyplot as plt
import numpy as np
import sys
x = []
y = []
with open('loss_ratio','r') as f:
    da = f.read().split('\n')[:-1]
    for i in range(len(da)):
        da[i] = da[i].split()
    for i in da:
        if float(i[0]) < 10:
            x.append(i[0])
            y.append(i[1])
x = np.array(x).astype(float)
y = np.array(y).astype(float)
plt.scatter(y,x)
plt.xlabel('minimal ratio')
plt.ylabel('loss')
#plt.xlim(-5.0,5.0)
#plt.ylim(-5.0,5.0)
plt.show()


import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'

data = np.loadtxt('data.txt')

n = 500
x = [i for i in range(n)]

plt.plot(x, data[:n], linewidth=1.6)
plt.xlabel('$t$')
plt.ylabel('$x(t)$')
plt.show()