from datetime import datetime

import pandas as pd
import streamlit as st
from PIL import Image
from streamlit_drawable_canvas import st_canvas
from torchvision import transforms

from deployment_model_vit_h_14 import DeploymentModelViT_H_14
from deployment_model_dino_v2 import DeploymentModel_DINO_v2

# Load the ViT-H_14 model and the DINOv2 model
vit_h_model = DeploymentModelViT_H_14.getInstance()
dino_v2_model = DeploymentModel_DINO_v2.getInstance()

def load_images(img_list, limit=100):
    for i, image_file in enumerate(img_list):
        if i < limit:
            if i % 5 == 0:
                cols = st.columns(5)
            cols[i % 5].image('/home/group15/VPR/visual-product-recognition-2/Deployment/Streamlit_Web_App/' + image_file)

# Title of the app
st.title("Visual Product Recognition - ViT-H_14/DINOv2 Models - Group 15")

# Adding text
st.write("Visual Product Recognition systems let you find the product you are looking for very easily by replacing the"
         " traditional text queries with image queries. Let's get started...")
image_data = st.file_uploader(label='Upload the image you want to query on', type=['jpg', 'png'])

canvas_max_height = 500
canvas_max_width = 500

query_image_folder = '/home/group15/VPR/visual-product-recognition-2/Deployment/Streamlit_Web_App/query_images'

if image_data is not None:
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    image_file_name = str(timestamp) + '.jpg'
    uploaded_image = Image.open(image_data)
    uploaded_image.save('/home/group15/VPR/visual-product-recognition-2/Deployment/Streamlit_Web_App/query_images/' + image_file_name)
    width, height = uploaded_image.size

    canvas_height = canvas_max_height
    canvas_width = canvas_max_width

    image_pixel_by = 1
    if width >= height:
        image_pixel_by = canvas_max_width / width
        canvas_height = int(height * image_pixel_by)
    else:
        image_pixel_by = canvas_max_width / width
        canvas_width = int(width * image_pixel_by)

    canvas_result = st_canvas(
        fill_color="rgba(255, 255, 255, 0)",  # Fixed fill color with some opacity
        stroke_width=2,
        stroke_color="#FFFF00",
        background_color="#EEEEEE",
        background_image=uploaded_image,
        height=canvas_height,
        width=canvas_width,
        drawing_mode="rect",
        key="canvas"
    )

    multiple_bounding_box_error = None
    bbox_x = 0
    bbox_y = 0
    bbox_w = 0
    bbox_h = 0

    if canvas_result.json_data is not None:
        objects = pd.json_normalize(canvas_result.json_data["objects"])  # need to convert obj to str because PyArrow

        number_of_bounding_boxes = len(objects)
        if number_of_bounding_boxes > 1:
            multiple_bounding_box_error = st.error('You cannot have multiple bounding boxes within a single image. '
                                                   'Please undo the previously drawn bounding box before drawing'
                                                   'another', icon="ðŸš¨")
        elif number_of_bounding_boxes == 1 and multiple_bounding_box_error is not None:
            multiple_bounding_box_error.empty()

        # Define a transform to convert PIL
        # image to a Torch tensor
        transform = transforms.Compose([
            transforms.PILToTensor()
        ])

        for col in objects.select_dtypes(include=['object']).columns:
            objects[col] = objects[col].astype("str")
        if number_of_bounding_boxes == 1:
            bbox_x = int(int(objects['left']) / image_pixel_by)
            bbox_y = int(int(objects['top']) // image_pixel_by)
            bbox_w = int(int(objects['width']) // image_pixel_by)
            bbox_h = int(int(objects['height']) // image_pixel_by)
            st.write(f"Bounding Box : Left: {bbox_x}, Top: {bbox_y}, Width: {bbox_w}, Height: {bbox_h}")

            chosen_model = st.selectbox('Select a model', options=['Trained ViT-H_14', 'Zero Shot DINOv2'])
            model = None
            if chosen_model == 'Trained ViT-H_14':
                model = vit_h_model
            else:
                model = dino_v2_model

            if st.button("Search Similar Products", type="primary"):
                query_tensor = model.get_query_embedding(query_image_folder + '/' + image_file_name, bbox_x, bbox_y, bbox_w, bbox_h)
                list_of_images = model.get_matching_gallery_images(query_tensor)
                load_images(list_of_images)


# -*- coding: UTF-8 -*-
# © Kohulan Rajan - 2020
import tensorflow as tf
import os
import numpy as np
import pickle
import efficientnet.tfkeras as efn
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='+')

args = parser.parse_args()
print(args)
# Initial Setup for GPU
os.environ["CUDA_VISIBLE_DEVICES"]="0"

gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu, True)

for file_in in args.file:

	def main():
		train_captions = pickle.load(open("Capts_Path_"+file_in+"_"+file_in+".pkl","rb"))
		img_name_vector = pickle.load(open("Images_Path_"+file_in+"_"+file_in+".pkl","rb"))

		print ("Total number of selected SMILES Strings: ",len(train_captions), "\n")
		num_shards = int(len(train_captions)/128) #corresponds to total train files

		file_index = num_shards*int(file_in)

		get_train_tfrecord(num_shards,train_captions,img_name_vector,file_index)

	target_size=(300,300,3)
	def load_image(image_path):
		img = tf.io.read_file(image_path)
		img = tf.image.decode_png(img, channels=3)
		img = tf.image.resize(img, (300, 300))
		img = efn.preprocess_input(img)
		return img,image_path

	def _bytes_feature(value):
		"""Returns a bytes_list from a string / byte."""
		if isinstance(value, type(tf.constant(0))):
			value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
		return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

	def get_train_tfrecord(num_shards,train_captions,img_name_vector,file_index):

		print("Total number of TFrecords: ",num_shards,flush=True)

		#Using InceptionV3 and using the pretrained Imagenet weights
		image_model = efn.EfficientNetB3(
	        weights='noisy-student', # Choose between imagenet and 'noisy-student'
	#         weights='imagenet',
	        input_shape=target_size, include_top=False)
		new_input = image_model.input
		hidden_layer = image_model.layers[-1].output
		image_features_extract_model = tf.keras.Model(new_input, hidden_layer)

		for i in range(num_shards):
			subsets_num = int(len(train_captions) / num_shards)
			sub_split_img_id = img_name_vector[i * subsets_num: (i + 1) * subsets_num]
			sub_split_cap_train = train_captions[i * subsets_num: (i + 1) * subsets_num]

			tfrecord_name = 'Isomeric_TFR_SELFIES/'+ 'train-%02d.tfrecord' % file_index
			writer = tf.io.TFRecordWriter(tfrecord_name)
			counter = 0
			for j in (range(len(sub_split_img_id))):

				img = tf.expand_dims(load_image(sub_split_img_id[j])[0], 0)

				batch_features = image_features_extract_model(img)
				batch_features = tf.reshape(batch_features,(batch_features.shape[0], -1, batch_features.shape[3]))
				#print(batch_features.shape)

				#print(decoded_image.shape)
				caption_ = sub_split_cap_train[j]
				#image_id_ = sub_split_img_id[counter]
				counter = counter+1
				feature = {
					#'image_id': _bytes_feature(image_id_.encode('utf8')),
					'image_raw': _bytes_feature(batch_features.numpy().tostring()),
					'caption': _bytes_feature(caption_.tostring()),
					}
				example = tf.train.Example(features=tf.train.Features(feature=feature))

				serialized = example.SerializeToString()
				writer.write(serialized)
			print('%s write to tfrecord success!' % tfrecord_name,flush=True)
			file_index = file_index + 1

	if __name__ == '__main__':
		main()


import re
from datetime import datetime
import requests

def kelvin_to_celsius(kelvin_temp):
    celsius_temp = float(kelvin_temp) - 273.15
    return str(round(celsius_temp, 2))

#weather function
def weather_data_recieve(status,user_input,prev_input):

    def read_file(filepath):
    # Initialize an empty list to store the non-comment lines
        non_comment_lines = []

    # Open the file in read mode
        with open(filepath, 'r') as file:
            # Read the lines from the file
            lines = file.readlines()

            # Filter out the lines that do not start with "#"
            non_comment_lines = [line.strip() for line in lines if not line.startswith("#")]

        return non_comment_lines

    data = read_file("Open weather map API.txt")
    api_key=data[0]
    CityList={"binh duong","ho chi minh","ha noi","hue","da nang","vinh","nghe an"}
    City = user_input.lower()
    type_of_data_list={"temperature","humidity","report","description"}
    type_of_data=""
    for j in type_of_data_list:
        if j in user_input:
            type_of_data=j
    if status==2:
        type_of_data=""
        for j in type_of_data_list:
            if j in prev_input:
                type_of_data=j

        City=user_input

    if status==0:
        for i in CityList:
            if i in City:
                City=i
        if City not in CityList:
            return 2, "Sorry, that city may not be in my dataset, can you try to type the name of the city again?"

    # Make a request to the OpenWeatherMap API
    try:
        url = f"http://api.openweathermap.org/data/2.5/weather?q={City}&appid={api_key}"
        response = requests.get(url)
        data = response.json()
    except:
        return 0,"sorry, I can not connect to weather server"
    # Extract relevant information from the response
    wanswer=""
    try:
        temperature = str(data["main"]["temp"])
        temperature2=kelvin_to_celsius(temperature)
        humidity = str(data["main"]["humidity"])
    except:
        return 0, "I am sorry, I cannot check the weather status in the city you want."
    weather_description = str(data["weather"][0]["description"])
    if type_of_data=="temperature":
        wanswer=temperature2+ "Celsius"
    elif type_of_data=="humidity":
        wanswer=humidity +"percent"
    else:
        wanswer=weather_description
    return 0, f'Here is the answer based on your request, weather {type_of_data} in {City} is: {wanswer}'

def handle_real_time():
    # Get the current time
    current_time = datetime.now().strftime("%H:%M:%S")
    return f"The current time is {current_time}."

#open the dataset
def read_dataset(file_path):
    dataset = []
    with open(file_path, 'r') as file:
        lines = file.readlines()
        for line in lines:
            line = line.strip()
            if line and not line.startswith("#"):
                pattern = r'\[Q\]\s(.*?)\s\[G\]\s(.*?)\s\[R\]\s(.*?)\s\[A\]\s(.*)'
                match = re.search(pattern, line)
                if match:
                    question, guessing_keywords, required_keywords, answer = match.groups()
                    dataset.append((question.lower(), guessing_keywords.lower().split(', '), required_keywords.lower().split(', '), answer))
                else:
                    pass

    return dataset

def calculate_probability(guessing_keywords, user_input):
    keyword_count = len(guessing_keywords)
    overlapping_count = sum(keyword in user_input for keyword in guessing_keywords)
    return overlapping_count / keyword_count

def get_answer(question, guessing_keywords, required_keywords, dataset):
    max_probability = 0
    best_answer = None

    for item in dataset:
        keywords = item[2]
        if all(keyword in question for keyword in keywords):
            probability = calculate_probability(guessing_keywords, question)
            if probability > max_probability:
                max_probability = probability
                best_answer = item[3]

    return best_answer

#process input from user to get answer
def data_processing(userinput,frame,status,previous_input):
    dataset = read_dataset("data.txt")
    if status == 1:

        new_guessing_keywords = previous_input
        new_required_keywords = previous_input
        new_answer=userinput.lower()
        dataset.append((previous_input, new_guessing_keywords, new_required_keywords, new_answer))

        # Add the new answer to the data.txt file
        with open("data.txt", "a") as file:
            file.write(f"[Q] {previous_input} [G] {', '.join(new_guessing_keywords)} [R] {', '.join(new_required_keywords)} [A] {new_answer}\n")
            file.close()
        return 0, "Chatbot: Thanks for teaching me!"
    if status==2:
        Wstatus, weather_response=weather_data_recieve(status,userinput,previous_input)
        return Wstatus, weather_response

    user_input = userinput.lower()

    matching_answer = None
    for item in dataset:
        guessing_keywords = item[1]
        required_keywords = item[2]
        if all(keyword in user_input for keyword in required_keywords):
            if item[3].startswith("SpecialFunction:"):
                    # Check for special functions
                    special_function = item[3].split(":")[1].strip().lower()

                    if special_function == "realtime":
                        special_function_response = handle_real_time()
                        return 0, "Chatbot:" + special_function_response
                    if special_function == "weatherdata":
                        try:
                            Wstatus, weather_response=weather_data_recieve(status,userinput,previous_input)
                            return Wstatus, weather_response
                        except:
                            return 0, "I am sorry, perhaps your syntax is incorrect or your Internet connection has a issue"
                    else:
                        return 0, "I am sorry, this syntax is invalid, can you try again for another syntax?"
            matching_answer = get_answer(user_input, guessing_keywords, required_keywords, dataset)
            if matching_answer:
                    return 0, "Chatbot:" + matching_answer

    return 1, "Chatbot: I'm sorry. Perhaps my dataset is not prepared for this question.\n Can you help me provide the answer?"


# parse stack result to see the result is valid or not.
# if it is valid, then show the push pop process.

def parse(args):
    pre_char = None
    li = []
    result = []
    pop_symbol = "-"
    for char in args.split():
        if len(result) == 0:
            result.append(char)
            result.append(pop_symbol)
            continue

        pos = 0
        handled = False
        while pos < len(result):
            el = result[pos]
            if el == pop_symbol:
                pos += 1
                continue
            if char > el:
                pos += 1
                continue
            if char == 'D' or char == 'F':
                print (result)
                print (pos)
            result.insert(pos, char)
            result.append(pop_symbol)
            handled = True
            pos += 1
            break

        if not handled:
            result.append(char)
            result.append(pop_symbol)

    print(" ".join(result))

def verify(args):
    li = args.split()
    pos = 0
    print(args)
    while pos < len(li):

        char = li[pos]
        comp_pos = pos
        prev_char = None
        while comp_pos < len(li):
            cur_char = li[comp_pos]
            if cur_char < char:
                if not prev_char:
                    prev_char = cur_char
                elif prev_char < cur_char:
                    print("Error")
                    break
                else:
                    prev_char = cur_char

            comp_pos += 1

        pos += 1

if __name__ == "__main__":
    verify("B A C D E F H G I J")
    verify("A B C E D F H G J I")
    verify("B C E A F H G I J D")
    verify("D F E H C G B I J A")
    verify("C B A D E F G H I J")


#!/usr/bin/env python
# coding=utf-8

import datetime
import wx
import wx.html
import wx.lib.wxpTag
import webbrowser
from constants import *
from runtime import get_bundle_dir
from runtime import check_latest_version
from packaging.version import parse

class AboutDlg(wx.Dialog):
    text = '''

PixelFlasher

By Badabing

Version {1}

    {2}

Fork the project on
    GitHub and help improve it for all!

 Beware!

 If you are asked to donate or pay money for this program, check your source.

 This program is free, will always remain totally free, ad free, even donation free.

        <wxp module="wx" class="Button">
            <param name="label" value="Close">
            <param name="id" value="ID_OK">
        </wxp>

'''

    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, wx.ID_ANY, "About PixelFlasher")
        html = HtmlWindow(self, wx.ID_ANY, size=(420, -1))
        if "gtk2" in wx.PlatformInfo or "gtk3" in wx.PlatformInfo:
            html.SetStandardFonts()

        # check version if we are running the latest
        l_version = check_latest_version()
        if parse(VERSION) < parse(l_version):
            update_text = f"
Update  Version v{l_version} is available.
"
        else:
            update_text = "
 You're up to date!
"

        txt = self.text.format(get_bundle_dir(), VERSION, update_text, datetime.datetime.now().year)
        html.SetPage(txt)
        ir = html.GetInternalRepresentation()
        html.SetSize((ir.GetWidth() + 25, ir.GetHeight() + 25))
        self.SetClientSize(html.GetSize())
        self.CentreOnParent(wx.BOTH)

class HtmlWindow(wx.html.HtmlWindow):
    def OnLinkClicked(self, link):
        webbrowser.open(link.GetHref())


# sum of proper divisor

a = int(input("Enter number: "))

def pdiv(a):
    sum = 0
    for i in range(1,a):
        if(a%i==0):
            sum += i

    print(sum)

pdiv(a)


import cv2

capture = cv2.VideoCapture(0)

while True:
    sample , frame = capture.read()

    # 'sample' is a variable that is written bcoz.
    # capture.read() needs 2 variables assignment.
    # Not Of much Use -> 'sample' variable.

    frame = cv2.flip(frame , 1) # For Flipping Images ->
                                # 1 -> Lateral inversion {left becomes right}.

    cv2.imshow("Output Video" , frame)
    if cv2.waitKey(1) == 27 : # 'esc' key is used to break loop.
        break

if capture.isOpened():
    sample , frame_new = capture.read()

cv2.imshow("Captured Image" , frame_new)
cv2.waitKey(0)

###### IMPORTANT #######

#### MUST WRITE ###

capture.release() # To Switch Off WebCam

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

cv2.destroyAllWindows()


#2. Use Pandas to create dictionary in python.
import pandas as pd
mobiles = [
            ("apple", 60000,150000),
            ("samsung",40000,1000000),
            ("google",45000,90000)
            ]
df = pd.DataFrame(mobiles,columns = ['company','min rate','max rate'])
print(df)
# hello bye
dictionary = df.to_dict(orient='records')
print(dictionary)


from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.http import HttpResponse
from .models import Post
from django.db.models import F
from .utils import Markdown2Html
from textwrap import dedent
import datetime

# Create your views here.
def archive(request):
    # the day I gave birth to earthlyhumans
    start_year = datetime.date(2016, 6, 7).year
    # yes I think I'm Gaia.
    # No. Just kdding. Move on.
    current_year = datetime.date.today().year
    context = {'archive': []}
    for year in range(current_year, start_year - 1, -1):
        posts = Post.objects.filter(pub_date__year=year).order_by('-pub_date')
        context['archive'].append({'year': year, 'posts': posts})
    return base_render(request, 'blog/archive.html', context)

def front(request):
    posts = Post.objects.order_by('-pub_date')[:10]
    context = {'posts': posts}
    return base_render(request, 'blog/front.html', context)

def about(request):
    html = Markdown2Html().convert(dedent("""\
    We have, on an average, 7 minutes of your time before you leave this page and we can no longer jam an impression on you. But we feel that your time is valuable, so here we go.

    ### Earthly Humans

    We've grown accustomed to view everything from our tiny modern life bubble. We've grown so dependent on technology, entertainment, and social media that we've forgotten to live. When was the last time you were bored and you had nothing to do? How many posts do you read on your social feed daily? and how much of it actually makes you feel good?

    Earthly Humans is a self exploring journey and an initiative to make lives more meaningful, by allowing people to connect, understand, and enjoy the melodic convergence of earth and humans. This is our visison, but we'll execute it differently.

    We believe that simple is better than complicated, and that less is actually more. So we won't be wasting your time with fluff, instead we'll use a serene combination of thoughts and art to convey our message.

    ### WE not ME

    I keep using 'we', instead of 'me' because I want to encourage anyone to come and [help in this effort](/support)

    List of all researchers, contributors, supporters, and volunteers:

    * Mitesh Shah - [miteshshah.com](http://miteshshah.com)
    """))
    context = {'page_content': html}
    return base_render(request, 'blog/about.html', context)

def support(request):
    html = Markdown2Html().convert(dedent("""\
    # Show us some love <3

    Currently we remain ad-free, and I will be paying the bills out of my own pockets. But you're welcome to help us pay our server and hosting bills by leaving a small donation ($6 will cover our monthly expenses).

    You can also support us

    * by spreading the word. Share our initiative with humans you care about!
    * by sending feedback at [hermes@earthlyhumans.com](mailto:hermes@earthlyhumans.com)
        - Fun fact: Hermes is the god of trade, communication, and language in the greek mythology.
    * by contributing your thoughts. Send us your views on *anything* at [athena@earthlyhumans.com](mailto:athena@earthlyhumans.com)
        - Fun fact: Athena is the goddess of intelligence and wisdom in the greek mythology.
    """))
    context = {'page_content': html}
    return base_render(request, 'blog/support.html', context)

def contact(request):
    return base_render(request, 'blog/contact.html')

def article(request, slug):
    post = get_list_or_404(slug=slug)
    post.update(view_count=F('view_count') + 1)
    context = {'post': post[0]}
    return base_render(request, 'blog/article.html', context)

def update_with_popular_posts(context={}):
    context['popular_posts'] = Post.objects.order_by('-view_count')[:5]
    return context

def base_render(request, template, context={}, *args, **kwargs):
    context = update_with_popular_posts(context)
    return render(request, template, context, *args, **kwargs)


import os
# for random number
import random
# for logo and art
from art import stages,logo
# for array of words
from data import word_list

# need arrays and variable

chose=[]
loop=0
life=7

# flag variable

end=False

chosen_word=random.choice(word_list)

# for initial characters to print

for chr in chosen_word:
    chose+='-'
    # logo print
print(logo)
# hint word length
print(chose)

# main loop for guess the word

while end==False:

    guess=input('please enter a single character to guess the word: ').lower()
    os.system('cls')

    for chr in chosen_word:
        loop+=1
        if chr==guess:
            chose[loop-1]=guess

# for print art if guess is not match

    if guess not in chosen_word:
        life-=1
        print(f'{guess} is not in the word ')
        print(stages[life])

# end the game if lose

    if life==0:
        end=True
        print(f'you lose correct word was {chosen_word}')
# end game if won
    if '-' not in chose:
        print('You Save the man 😍')
        end=True
    # print chosen word
    print(chose)
    loop=0


import os
from setuptools import setup, find_packages

# Use README.md for long description
with open('README.md', 'r', encoding='utf-8') as f:
    long_description = f.read()

# Requirements
with open('requirements.in', 'r') as f:
    reqs = f.read().splitlines()

setup(
    name='my_package',
    author='Marcus',
    description='Python package test',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/marcusboyle/package_test',
    packages=find_packages(),
    python_requires='>=3.7',
    install_requires=reqs,
    zip_safe=False
)


import datetime

from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext

from soccer.games.models import Game

def scores_index(request):
    games = Game.objects.filter(date=datetime.date.today()).order_by("-date")
    games = Game.objects.order_by("-date")[:50]
    context = {
        'games': games,
        }
    return render_to_response("games/scores.html",
                              context,
                              context_instance=RequestContext(request))

def game_detail(request, game_id):
    game = get_object_or_404(Game, id=game_id)
    context = {
        'game': game,
        #'goals': game.goals.all(),
        }
    return render_to_response("games/detail.html",
                              context,
                              context_instance=RequestContext(request))


"""Tests for analog Tannergraph decoder and simulator."""

from __future__ import annotations

from typing import TYPE_CHECKING
from unittest import mock

import numpy as np
import pytest

from mqt.qecc.analog_information_decoding.simulators.analog_tannergraph_decoding import (
    AnalogTannergraphDecoder,
    AtdSimulator,
)
from mqt.qecc.analog_information_decoding.utils import simulation_utils
from mqt.qecc.analog_information_decoding.utils.data_utils import BpParams

if TYPE_CHECKING:
    from numpy.typing import NDArray

@pytest.fixture()
def code_params() -> dict[str, int]:
    """Return code parameters."""
    return {"n": 7, "k": 3, "d": 2}

@pytest.fixture()
def error_channel() -> NDArray[np.int32]:
    """Return error channel."""
    return np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]).astype(np.int32)

@pytest.fixture()
def pcm() -> NDArray[np.int32]:
    """Return parity check matrix."""
    return np.array([[1, 0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 1, 1], [0, 0, 1, 0, 1, 0, 1]]).astype(np.int32)

@pytest.fixture()
def atd(error_channel: NDArray[np.float64], pcm: NDArray[np.int32]) -> AnalogTannergraphDecoder:
    """Return distance of the hexagonal color code."""
    return AnalogTannergraphDecoder(
        pcm=pcm,
        bp_params=BpParams(osd_method="osd0"),
        error_channel=error_channel,
        sigma=0.1,
        ser=None,
    )

@pytest.fixture()
def atd_simulator_sigma(pcm: NDArray[np.int32], code_params: dict[str, int]) -> AtdSimulator:
    """Return AtdSimulator using sigma to initialize syndrome channel."""
    return AtdSimulator(
        hx=pcm,
        hz=pcm,
        lx=np.array([1, 1, 1, 1, 1, 1, 1]),
        lz=np.array([1, 1, 1, 1, 1, 1, 1]),
        codename="test",
        data_err_rate=0.1,
        sigma=0.1,
        seed=666,
        bp_params=BpParams(osd_method="osd0"),
        decoding_method="atd",
        code_params=code_params,
    )

@pytest.fixture()
def atd_simulator_ser(pcm: NDArray[np.int32], code_params: dict[str, int]) -> AtdSimulator:
    """Return AtdSimulator using error rate to initialize syndrome channel."""
    per = 0.1
    ser = 0.1
    return AtdSimulator(
        hx=pcm,
        hz=pcm,
        lx=np.array([1, 1, 1, 1, 1, 1, 1]),
        lz=np.array([1, 1, 1, 1, 1, 1, 1]),
        codename="test",
        data_err_rate=per,
        syndr_err_rate=ser,
        seed=666,
        bp_params=BpParams(osd_method="osd0"),
        decoding_method="atd",
        output_path="./res",
        code_params=code_params,
    )

def test_set_analog_syndrome(atd: AnalogTannergraphDecoder, error_channel: NDArray[np.float64]) -> None:
    """Test initialization of decoder channel probs with analog syndrome."""
    analog_syndr = np.array([0.1, 0.1, 0.1])
    expected_virtual_inits = np.array([2.0611536181902108e-09, 2.0611536181902108e-09, 2.0611536181902108e-09])
    expected = np.hstack([error_channel, expected_virtual_inits])

    res = atd.decode(analog_syndr)
    assert np.array_equal(atd.bposd_decoder.channel_probs, expected)
    assert res is not None
    assert len(res) == 10

def test_atd_simulator_data_error_channels_setup(pcm: NDArray[np.int32], code_params: dict[str, int]) -> None:
    """Test simulator data error channel computation and initialization."""
    per = 0.1
    sigma = 0.1
    sim = AtdSimulator(
        hx=pcm,
        hz=pcm,
        lx=np.array([]),
        lz=np.array([]),
        codename="test",
        data_err_rate=per,
        sigma=sigma,
        seed=666,
        bp_params=BpParams(osd_method="osd0"),
        decoding_method="atd",
        code_params=code_params,
    )
    expected_err_chnl = simulation_utils.error_channel_setup(
        error_rate=per,
        xyz_error_bias=np.array([0.1, 0.1, 0.1]).astype(np.float64),
        nr_qubits=pcm.shape[1],
    )
    assert np.array_equal(sim.x_decoder.error_channel, expected_err_chnl[0] + expected_err_chnl[1])
    assert np.array_equal(sim.z_decoder.error_channel, expected_err_chnl[2] + expected_err_chnl[1])

def test_atd_simulator_syndrome_error_channels_setup(atd_simulator_sigma: AtdSimulator) -> None:
    """Test AtdSimulator syndrome channel computation and initialization."""
    sigma = 0.1
    ser = simulation_utils.get_error_rate_from_sigma(sigma)
    expec_chnl = simulation_utils.error_channel_setup(
        error_rate=ser,
        xyz_error_bias=np.array([0.1, 0.1, 0.1]).astype(np.float64),
        nr_qubits=1,
    )
    assert atd_simulator_sigma.syndr_err_rate == simulation_utils.get_error_rate_from_sigma(sigma=sigma)
    assert atd_simulator_sigma.x_sigma == simulation_utils.get_sigma_from_syndr_er(expec_chnl[0][0] + expec_chnl[1][0])
    assert atd_simulator_sigma.z_sigma == simulation_utils.get_sigma_from_syndr_er(expec_chnl[2][0] + expec_chnl[1][0])

def test_atd_simulator_syndrome_error_channels_setup_ser(atd_simulator_ser: AtdSimulator) -> None:
    """Test AtdSimulator syndrome error computattion and initialization using error rate."""
    ser = 0.1
    expec_chnl = simulation_utils.error_channel_setup(
        error_rate=ser,
        xyz_error_bias=np.array([0.1, 0.1, 0.1]).astype(np.float64),
        nr_qubits=1,
    )
    assert atd_simulator_ser.x_sigma == simulation_utils.get_sigma_from_syndr_er(expec_chnl[0][0] + expec_chnl[1][0])
    assert atd_simulator_ser.z_sigma == simulation_utils.get_sigma_from_syndr_er(expec_chnl[2][0] + expec_chnl[1][0])

def test_single_sample(atd_simulator_ser: AtdSimulator) -> None:
    """Test single sample overall."""
    assert atd_simulator_ser.single_sample() is not None
    assert atd_simulator_ser.x_bp_iterations is not None
    assert atd_simulator_ser.z_bp_iterations is not None

def test_safe_results(atd_simulator_ser: AtdSimulator) -> None:
    """Test result saving."""
    with mock.patch("json.dump", return_value=True):
        res = atd_simulator_ser.save_results(1, 1, 1)
    assert res is not None
    assert res["code_K"] == 3
    assert res["code_N"] == 7

def test_run(atd_simulator_ser: AtdSimulator) -> None:
    """Test run method."""
    with mock.patch("json.dump", return_value=True):
        res = atd_simulator_ser.run(1)
    assert res is not None
    assert res["code_K"] == 3
    assert res["code_N"] == 7


'''12) Deseja-se publicar o número de acertos de cada aluno em uma prova em forma de testes. A prova consta de 30 questões, cada uma com cinco alternativas identificadas por A, B, C, D e E. Para isso são dados:
    o cartão gabarito;
    o número de alunos da turma;
    o cartão de respostas para cada aluno, contendo o seu número e suas respostas'''
def publicar_acertos(lista_gabarito, lista_cartao):
    saida_acertos = f''
    for i in range(len(lista_cartao)):
        acertos = 0
        for c in range(len(lista_gabarito)):
            if lista_cartao[i][c] == lista_gabarito[c]:
                acertos += 1
            else:
                continue

        saida_acertos += f'O aluno {i+1} teve {acertos} acertos\n'

    return saida_acertos

def coletar_respostas(lista_gabarito):
    while True:
        try:
            qtd_candit = int(input('Quantos candidatos são?\n'))
            lista_candidatos = []
            print('Digitar as',len(lista_gabarito),'respostas de cada candidadto.')
            for i in range(qtd_candit):
                lista_respostas = []
                for c in range(len(lista_gabarito)):
                    escolha = input(f'Candidato {i+1}; Questão {c+1}.\n ').upper()
                    if escolha in 'ABCDE':
                        lista_respostas.append(escolha)
                    else:
                        while escolha not in 'ABCDE':
                            escolha = input(f'Só é aceito A, B, C, D ou E como resposta!!!\nDigite novamente.\n').upper()
                            if escolha in 'ABCDE':
                                lista_respostas.append(escolha)
                            else:
                                continue
                lista_candidatos.append(lista_respostas)
            break
        except:
            print('DADO INCOERENTE!!!')

    return lista_candidatos

def main():
    while True:
        try:
            lista_gabarito = []
            for i in range(30):
                resposta = input(f'Digite o gabarito da {i+1}º questão.\n').upper()
                if resposta == 'A' or resposta == 'B' or resposta == 'C' or resposta == 'D' or resposta == 'E':
                    lista_gabarito.append(resposta)
                else:
                    while resposta not in 'ABCDE':
                        resposta = input('Só é aceito A, B, C, D ou E como gabarito!!\nDigite novamente.\n').upper()
                        if resposta in 'ABCDE':
                            lista_gabarito.append(resposta)
                        else:
                            pass

            lista_cartao = coletar_respostas(lista_gabarito)

            print(publicar_acertos(lista_gabarito, lista_cartao))
            break
        except:
            print('ERRO!!')

if __name__ == '__main__':
    main()


from django.urls import path, include
from rest_framework_simplejwt import views as jwt_views
from . import views

urlpatterns = [
    path('register/', views.register_view,name="register"),
    path('admin/', views.admin_view, name="admin"),
    path('student/', views.student_view, name="student"),
    path('teacher/', views.teacher_view, name="teacher"),
    path('admin/<int:pk>/', views.admin_update_view, name="admin_update"),
    path('token/', jwt_views.TokenObtainPairView.as_view(), name="access_token"),
    path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name="refresh_token"),
]


import unittest
from scheduler.job.base_test import BaseTest
from constant import TestType

class TestJobResultStatistic(unittest.TestCase):

    def test_job_result_statistic(self):
        job_id = 259
        test_type = TestType.FUNCTIONAL
        test_result = BaseTest.get_job_result(job_id, test_type)
        print(test_result)

if __name__ == "__main__":
    unittest.main()


# when printing (a, rmax) during brute-force, I noticed:
# if a == odd: rmax = a*(a-1)
# if a == even: rmax = a*(a-2)

total = 0
for a in range(3, 1001):
    if a & 1 == 1:
        total += a * (a - 1)
    else:
        total += a * (a - 2)
print(total)


import argparse
import random
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from collections import deque
plt.style.use('dark_background')

DESCRIPTION = "Visualization of a double pendulum path"

parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('--length_1', type=float, default=1.0,
                    help="Length of first pendulum arm")
parser.add_argument('--length_2', type=float, default=1.0,
                    help="Length of second penulum arm")
parser.add_argument('--mass_1', type=float, default=1.0,
                    help="Mass of pendulum 1")
parser.add_argument('--mass_2', type=float, default=1.0,
                    help="Mass of pendulum 2")
parser.add_argument('--theta_1', type=float, default=None,
                    help="Initial angle of pendulum 1 (random by default)")
parser.add_argument('--theta_2', type=float, default=None,
                    help="Initial angle of pendulum 2 (random by default)")
args = parser.parse_args()

G = 9.81
L1 = args.length_1
L2 = args.length_2
L = L1 + L2
M1 = args.mass_1
M2 = args.mass_2

if args.theta_1 is None:
    th1 = random.randint(-90, 90)
else:
    th1 = args.theta_1

if args.theta_2 is None:
    th2 = random.randint(-120, 120)
else:
    th2 = args.theta_2

w1 = 0.0
w2 = 0.0
t_stop = 60
dt = 0.01
history_len = int(t_stop/dt)

def derivs(state):
    dydx = np.zeros_like(state)

    dydx[0] = state[1]

    delta = state[2] - state[0]
    den1 = (M1+M2) * L1 - M2 * L1 * cos(delta) * cos(delta)
    dydx[1] = ((M2 * L1 * state[1] * state[1] * sin(delta) * cos(delta)
                + M2 * G * sin(state[2]) * cos(delta)
                + M2 * L2 * state[3] * state[3] * sin(delta)
                - (M1+M2) * G * sin(state[0]))
               / den1)

    dydx[2] = state[3]

    den2 = (L2/L1) * den1
    dydx[3] = ((- M2 * L2 * state[3] * state[3] * sin(delta) * cos(delta)
                + (M1+M2) * G * sin(state[0]) * cos(delta)
                - (M1+M2) * L1 * state[1] * state[1] * sin(delta)
                - (M1+M2) * G * sin(state[2]))
               / den2)

    return dydx

# create a time array from 0..t_stop sampled at 0.02 second steps
t = np.arange(0, t_stop, dt)

# initial state
state = np.radians([th1, w1, th2, w2])

# integrate the ODE using Euler's method
y = np.empty((len(t), 4))
y[0] = state
for i in range(1, len(t)):
    y[i] = y[i - 1] + derivs(y[i - 1]) * dt

x1 = L1*sin(y[:, 0])
y1 = -L1*cos(y[:, 0])

x2 = L2*sin(y[:, 2]) + x1
y2 = -L2*cos(y[:, 2]) + y1

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(autoscale_on=False, xlim=(-L, L), ylim=(-L, L))
ax.set_aspect('equal')

line, = ax.plot([], [], '#A3BE8C', lw=3)
mass1 = ax.scatter([x1], [y1], c='#A3BE8C', lw=5)
mass2 = ax.scatter([x2], [y2], c='#A3BE8C', lw=5)
trace, = ax.plot([], [], '#FFFFFF', linestyle='-.', lw=2, ms=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.96, '', transform=ax.transAxes)
history_x, history_y = deque(maxlen=history_len), deque(maxlen=history_len)
ax.text(0.05, 0.94, f"length 1: {L1}", transform=ax.transAxes)
ax.text(0.05, 0.92, f"length 2: {L2}", transform=ax.transAxes)
ax.text(0.05, 0.90, f"mass 1: {M1}", transform=ax.transAxes)
ax.text(0.05, 0.88, f"mass 2: {M2}", transform=ax.transAxes)
ax.text(0.05, 0.86, f"angle 1: {th1}", transform=ax.transAxes)
ax.text(0.05, 0.84, f"angle 2: {th2}", transform=ax.transAxes)
ax.tick_params(axis='both', colors='black')
ax.set_title("Double Pendulum Animation", fontsize=20)

def animate(i):
    thisx = [0, x1[i], x2[i]]
    thisy = [0, y1[i], y2[i]]

    if i == 0:
        history_x.clear()
        history_y.clear()

    history_x.appendleft(thisx[2])
    history_y.appendleft(thisy[2])

    line.set_data(thisx, thisy)
    mass1.set_offsets([x1[i], y1[i]])
    mass2.set_offsets([x2[i], y2[i]])
    trace.set_data(history_x, history_y)
    time_text.set_text(time_template % (i*dt))
    return line, mass1, mass2, trace, time_text

ani = animation.FuncAnimation(
    fig, animate, len(y), interval=dt*1000, blit=True)
plt.show()


import streamlit as st
import datetime as dt
import sys
import time
import pandas as pd
import os
sys.path.insert(1, os.path.dirname(os.path.abspath(__file__)))
from functions import utils as ut
from streamlit_extras.switch_page_button import switch_page
import plotly.express as px

st.set_page_config('Results')
st.sidebar.header('Results')

conn = ut.create_db()
all = ut.select_full_results(conn)
counts, count_all = ut.select_counts(conn)

@st.cache_data
def convert_df_to_csv(df):
    return df.to_csv(index=False).encode('utf-8')

names = list(counts['NAME'].unique())

name_box = st.selectbox('Choose student', names)
names = list(counts['NAME'].unique())
_counts= counts[counts['NAME']==name_box]
_counts['WEEK_START'] = _counts['WEEK_START'].dt.strftime('%m/%d/%Y')
count_all['WEEK_START'] = count_all['WEEK_START'].dt.strftime('%m/%d/%Y')
_all = all[all['NAME']==name_box]
st.dataframe(_all, hide_index=True, use_container_width=True)
fig = px.bar(_counts,
             x='WEEK_START',
             y='HW_NOT_DONE_COUNT',
             title=f'Homework Assignmnets Not Done for {name_box}')
fig.update_layout(xaxis_title='Week',
                  yaxis_title='Homework Not Done',)
fig2 = px.bar(count_all,
             x='WEEK_START',
             y='HW_NOT_DONE_COUNT',
             title='Homework Assignmnets Not Done for All Students',)
fig2.update_layout(xaxis_title='Week',
                  yaxis_title='Homework Not Done')
st.plotly_chart(fig, use_container_width=True)
st.plotly_chart(fig2, use_container_width=True)


import cv2
import mido
import time
import threading
import numpy as np

def main():
    img = cv2.imread("Van Gogh/Saint Remy/Half Figure of an Angel after Rembrandt.jpg")
    # img = cv2.imread("Van Gogh/Saint Remy/Irises.jpg")
    # img = cv2.imread("Van Gogh/Paris/Vase with Asters and Phlox.jpg")
    # img = cv2.imread("Van Gogh/Paris/The Kingfisher.jpg")
    # img = cv2.imread("Van Gogh/Paris/The Hill of Montmartre with Quarry.jpg")
    hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    scale_percent = 25
    width = int(img.shape[1] * scale_percent / 100)
    height = int(img.shape[0] * scale_percent / 100)
    dim = (width, height)

    img = cv2.resize(img, dim)
    hsv_img = cv2.resize(hsv_img, dim)

    # cv2.imshow("OG", img)
    # cv2.imshow("HSV", hsv_img)

    in_port = mido.open_input("loopMIDI Port 0")
    out_port = mido.open_output("loopMIDI Port 1")

    step_size = 80
    x_list = range(0, width, step_size)
    y_list = range(0, height, step_size)
    x_index = 0
    y_index = 0

    clock_count = 0
    for msg in in_port:
        if clock_count == 192 or msg.type == "start":
            x = x_list[x_index]
            y = y_list[y_index]

            sub_img = hsv_img[y:y + step_size, x:x + step_size]
            mean_hsv = np.round(np.mean(sub_img.reshape(-1, 3), axis=0)).astype(np.int)

            hue = scale_between_range(mean_hsv[0], 0, 179, 10, 100)
            saturation = scale_between_range(mean_hsv[1], 0, 255, 10, 100)
            intensity = scale_between_range(mean_hsv[2], 0, 255, 10, 100)

            note_duration = scale_between_range(hue + saturation + intensity, 3, 127 * 3, 2, 6)
            make_sound(hue, saturation, intensity, intensity, note_duration, out_port)

            hsv_img[y:y + step_size, x:x + step_size] = img[y:y + step_size, x:x + step_size]
            cv2.imshow("HSV", hsv_img)
            cv2.waitKey(1)

            x_index += 1
            if x_index == len(x_list):
                x_index = 0
                y_index += 1
                if y_index == len(y_list):
                    break

            clock_count = 0

        if msg.type == "clock":
            clock_count += 1

    cv2.destroyAllWindows()

def make_sound(note_0, note_1, note_2, vel, dur, out_port):
    hue_note = mido.Message("note_on", note=note_0, velocity=vel)
    sat_note = mido.Message("note_on", note=note_1, velocity=vel)
    int_note = mido.Message("note_on", note=note_2, velocity=vel)
    out_port.send(hue_note)
    out_port.send(sat_note)
    out_port.send(int_note)

    hue_note = mido.Message("note_off", note=note_0, velocity=vel)
    sat_note = mido.Message("note_off", note=note_1, velocity=vel)
    int_note = mido.Message("note_off", note=note_2, velocity=vel)
    threading.Timer(dur, lambda: out_port.send(hue_note)).start()
    threading.Timer(dur, lambda: out_port.send(sat_note)).start()
    threading.Timer(dur, lambda: out_port.send(int_note)).start()

def scale_between_range(value, in_min, in_max, out_min, out_max):
    scaled = round(out_min + (value - in_min) * ((out_max - out_min) / (in_max - in_min)))
    if scaled > out_max:
        return out_max
    if scaled < out_min:
        return out_min
    return scaled

if __name__ == "__main__":
    main()


with open(r'C:\Projekt\Python\AdventCode\2021\Day2\planned_course.txt') as f:
    lines = f.readlines()

# Part 1
def part_one():
    depth = 0
    horizontal = 0

    for line in lines:
        split = line.split(" ")
        if split[0] == 'up':
            depth = depth - int(split[1])
        elif split[0] == 'down':
            depth = depth + int(split[1])
        elif split[0] == 'forward':
            horizontal = horizontal + int(split[1])

    return depth * horizontal

def part_two():
    depth = 0
    horizontal = 0
    aim = 0

    for line in lines:
        split = line.split(" ")
        if split[0] == 'up':
            aim = aim - int(split[1])
        elif split[0] == 'down':
            aim = aim + int(split[1])
        elif split[0] == 'forward':
            horizontal = horizontal + int(split[1])
            depth = depth + aim * int(split[1])

    return depth * horizontal

if __name__ == '__main__':
    print(part_one())
    print(part_two())


"""
Create a function that takes a string consisting of one or more words separated by spaces. It should return a new string converted to "sponge case," where each word starts with a lowercase letter, and then alternates between upper and lower case for each following letter in the word.

Examples:

sponge_case("spongebob") # Should return "sPoNgEbOb"

sponge_case("Who are YOU calling A Pinhead") # Should return "wHo aRe yOu cAlLiNg a pInHeAd"

assert sponge_case("WHAT is UP my dude") == "wHaT iS uP mY dUdE"

sponge_case("E") # Should return "e"

sponge_case("e") # Should return "e"
"""

def sponge_case(sentence):
  # turn the sentence into an array of individual words
  words = sentence.split()

  # create a new array of sponge-case words using our helper function
  new_words = []
  for word in words:
    new_words.append(sponge_single_word(word))

  # Join the new spongy words with spaces
  return " ".join(new_words)

# Helper function that converts a single word to sponge-case
def sponge_single_word(word):
  new_word = ""
  # Instructions say the word must start with a lowercase letter
  # We will toggle this variable to alternate between lower and upper case
  lower = True

  for letter in word:
    # if our toggle is set to lowercase, add a lowercase version of the letter
    if lower:
      new_word += letter.lower()
    # if our toggle is set to lowercase, add a uppercase version of the letter
    else:
      new_word += letter.upper()
    # flip our toggle
    lower = not lower

  return new_word

# Test cases
assert sponge_case("spongebob") == "sPoNgEbOb"
assert sponge_case("Who are YOU calling A Pinhead") == "wHo aRe yOu cAlLiNg a pInHeAd"
assert sponge_case("WHAT is UP my dude") == "wHaT iS uP mY dUdE"
assert sponge_case("E") == "e"
assert sponge_case("e") == "e"

print("All tests passed!")
print("Discuss time and space complexity if there's time remaining")

"""
***NOTES TO INTERVIEWER***

---------Answers to clarifying questions----------
Q: What should I do if the input is not a string? Or if the string is empty?
A: You do not need to worry about this case. You can assume the input will be a string with at least one letter in it.

Q: What should I do with punctuation, numbers, etc.?
A: You can assume the input will include only letters and spaces.

Q: What should I do if there's extra spaces?
A: You can assume there will be exactly one space in between words and no extra spaces at the beginning or end of the string.

--------------------------------------------------

---------Hints for struggling candidates----------

 - If your candidate struggles with an initial algorithm, encourage them to walk through an example and desrcibe how they would do it using only pen and paper

 - If they're having trouble determining how to handle multiple words, encourage them to first write code to solve the case where there's only a single word in the string

 - If your candidate is struggling to determine how to convert a letter to upper or lower case, encourage them to look up how to do that online

- If your candidate is struggling with test case #3, remind them that the question states that every word starts with a lowercase letter

 -------------------------------------------------

"""


import os
import random
import warnings

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data

from ignite.engine import Engine, Events
from ignite.handlers import ModelCheckpoint, Timer
from ignite.metrics import RunningAverage
from ignite.contrib.handlers import ProgressBar

import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils

class Net(nn.Module):
    def weights_init(self):
        for m in self.modules():
            classname = m.__class__.__name__
            if 'Conv' in classname:
                m.weight.data.normal_(0.0, 0.02)
            elif 'BatchNorm' in classname:
                m.weight.data.normal_(1.0, 0.02)
                m.bias.data.fill_(0)

    def forward(self, x):
        return x

class Generator(Net):
    def __init__(self, z_dim, nf):
        super(Generator, self).__init__()

        self.net = nn.Sequential(
            nn.ConvTranspose2d(in_channels=z_dim, out_channels=nf * 8, kernel_size=4, stride=1, padding=0, bias=False),
            nn.BatchNorm2d(nf * 8),
            nn.ReLU(inplace=True),

            nn.ConvTranspose2d(in_channels=nf * 8, out_channels=nf * 4, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(nf * 4),
            nn.ReLU(inplace=True),

            nn.ConvTranspose2d(in_channels=nf * 4, out_channels=nf * 2, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(nf * 2),
            nn.ReLU(inplace=True),

            nn.ConvTranspose2d(in_channels=nf * 2, out_channels=nf, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(nf),
            nn.ReLU(inplace=True),

            nn.ConvTranspose2d(in_channels=nf, out_channels=3, kernel_size=4, stride=2, padding=1, bias=False),
            nn.Tanh()
        )

        self.weights_init()

    def forward(self, x):
        return self.net(x)

class Discriminator(Net):
    def __init__(self, nf):
        super(Discriminator, self).__init__()

        self.net = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=nf, kernel_size=4, stride=2, padding=1, bias=False),
            nn.LeakyReLU(0.2, inplace=True),

            nn.Conv2d(in_channels=nf, out_channels=nf * 2, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(nf * 2),
            nn.LeakyReLU(0.2, inplace=True),

            nn.Conv2d(in_channels=nf * 2, out_channels=nf * 4, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(nf * 4),
            nn.LeakyReLU(0.2, inplace=True),

            nn.Conv2d(in_channels=nf * 4, out_channels=nf * 8, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(nf * 8),
            nn.LeakyReLU(0.2, inplace=True),

            nn.Conv2d(in_channels=nf * 4, out_channels=1, kernel_size=4, stride=1, padding=0, bias=False),
            nn.Sigmoid()
        )

        self.weights_init()

    def forward(self, x):
        output = self.net(x)
        return output.view(-1, 1).squeeze(1)

def check_dataset(dataset, dataroot):
    to_rgb = transforms.Lambda(lambda img: img.convert('RGB'))
    resize = transforms.Resize(64)
    crop = transforms.CenterCrop(64)
    to_tensor = transforms.ToTensor()
    normalize = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))

    if dataset == 'mnist':
        dataset = dset.MNIST(root=dataroot, download=True, transform=transforms.Compose([
            to_rgb, resize, to_tensor, normalize
        ]))
    else:
        raise RuntimeError("Invalid dataset name: {}".format(dataset))

    return dataset

PRINT_FREQ = 100
FAKE_IMG_FNAME = 'fake_sample_epoch_{:04d}.png'
REAL_IMG_FNAME = 'real_sample_epoch_{:04d}.png'
LOGS_FNAME = 'logs.tsv'
PLOT_FNAME = 'plot.svg'
SAMPLES_FNAME = 'samples.svg'
CKPT_PREFIX = 'networks'

def main():
    seed = 42
    random.seed(seed)
    torch.manual_seed(seed)

    z_dim = 100
    g_filters = 64
    d_filters = 64
    learning_rate = 0.0002
    beta_1 = 0.5
    alpha = 0.98
    batch_size = 64
    epochs = 25
    device = 'cuda'

    netG = Generator(z_dim, g_filters)
    netD = Discriminator(d_filters)

    bce = nn.BCELoss()

    optimizerG = optim.Adam(netG.parameters(), lr=learning_rate, betas=(beta_1, 0.999))
    optimizerD = optim.Adam(netD.parameters(), lr=learning_rate, betas=(beta_1, 0.999))

    dataset = check_dataset('mnist', '../Data/')
    loader = data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=4, drop_last=True)

    real_labels = torch.ones(batch_size, device=device)
    fake_labels = torch.zeros(batch_size, device=device)
    fixed_noise = torch.randn(batch_size, z_dim, 1, 1, device=device)

    def get_noise():
        return torch.randn(batch_size, z_dim, 1, 1, device=device)

    def step(engine, batch):
        real, _ = batch
        real = real.to(device)

        netD.zero_grad()

        output = netD(real)
        errD_real = bce(output, real_labels)
        D_x = output.mean().item()

        errD_real.backward()

        noise = get_noise()
        fake = netG(noise)

        output = netD(fake.detach())
        errD_fake = bce(output, fake_labels)
        D_G_z1 = output.mean().item()

        errD_fake.backward()

        errD = errD_real + errD_fake
        optimizerD.step()

        # GEN UPDATE
        netG.zero_grad()

        output = netD(fake)
        errG = bce(output, real_labels)
        D_G_z2 = output.mean().item()

        errG.backward()

        optimizerG.step()

        return {
            'errD': errD.item(),
            'errG': errG.item(),
            'D_x': D_x,
            'D_G_z1': D_G_z1,
            'D_G_z2': D_G_z2
        }

    output_dir = "../data/dcgan/"

    trainer = Engine(step)
    checkpoint_handler = ModelCheckpoint(output_dir, CKPT_PREFIX, save_interval=1, n_saved=10, require_empty=False)
    timer = Timer(average=True)

    monitoring_metrics = ['errD', 'errG', 'D_x', 'D_G_z1', 'D_G_z2']
    RunningAverage(alpha=alpha, output_transform=lambda x: x['errD']).attach(trainer, 'errD')
    RunningAverage(alpha=alpha, output_transform=lambda x: x['errG']).attach(trainer, 'errG')
    RunningAverage(alpha=alpha, output_transform=lambda x: x['D_x']).attach(trainer, 'D_x')
    RunningAverage(alpha=alpha, output_transform=lambda x: x['D_G_z1']).attach(trainer, 'D_G_z1')
    RunningAverage(alpha=alpha, output_transform=lambda x: x['D_G_z2']).attach(trainer, 'D_G_z2')

    pbar = ProgressBar()
    pbar.attach(trainer, metric_names=monitoring_metrics)

    @trainer.on(Events.ITERATION_COMPLETED)
    def print_logs(engine):
        if (engine.state.iteration - 1) % PRINT_FREQ == 0:
            fname = os.path.join(output_dir, LOGS_FNAME)
            columns = engine.state.metrics.keys()
            values = [str(round(value, 5)) for value in engine.state.metrics.values()]

            with open(fname, 'a') as f:
                if f.tell() == 0:
                    print('\t'.join(columns), file=f)
                print('\t'.join(values), file=f)

            message = '[{epoch}/{max_epoch}][{i}/{max_i}]'.format(epoch=engine.state.epoch,
                                                                  max_epoch=epochs,
                                                                  i=(engine.state.iteration % len(loader)),
                                                                  max_i=len(loader))
            for name, value in zip(columns, values):
                message += ' | {name}: {value}'.format(name=name, value=value)

            pbar.log_message(message)

    @trainer.on(Events.EPOCH_COMPLETED)
    def save_real_example(engine):
        img, y = engine.state.batch
        path = os.path.join(output_dir, REAL_IMG_FNAME.format(engine.state.epoch))
        vutils.save_image(img, path, normalize=True)

    trainer.add_event_handler(event_name=Events.EPOCH_COMPLETED, handler=checkpoint_handler,
                              to_save={
                                  'netG': netG,
                                  'netD': netD
                              })

    timer.attach(trainer, start=Events.EPOCH_STARTED, resume=Events.ITERATION_STARTED,
                 pause=Events.ITERATION_COMPLETED, step=Events.ITERATION_COMPLETED)

    @trainer.on(Events.EPOCH_COMPLETED)
    def print_timer(engine):
        pbar.log_message('Epoch {} done. Time per batch: {:.3f}[s]'.format(engine.state.epoch, timer.value()))
        timer.reset()

    @trainer.on(Events.EPOCH_COMPLETED)
    def create_plots(engine):
        try:
            import matplotlib as mpl
            mpl.use('agg')

            import numpy as np
            import pandas as pd
            import matplotlib.pyplot as plt

        except ImportError:
            warnings.warn('Loss plots will not be generated -- pandas or matplotlib not found')

        else:
            df = pd.read_csv(os.path.join(output_dir, LOGS_FNAME), delimiter='\t')
            x = np.arange(1, engine.state.iteration + 1, PRINT_FREQ)
            _ = df.plot(x=x, subplots=True, figsize=(20, 20))
            _ = plt.xlabel('Iteration number')
            fig = plt.gcf()
            path = os.path.join(output_dir, PLOT_FNAME)

            fig.savefig(path)

    # @trainer.on(Events.EXCEPTION_RAISED)
    # def handle_exception(engine, e):
    #     if isinstance(e, KeyboardInterrupt) and (engine.state.iteration > 1):
    #         engine.terminate()
    #         warnings.warn('KeyboardInterrupt caught. Exiting gracefully.')
    #
    #         create_plots(engine)
    #         checkpoint_handler(engine, {
    #             'netG_exception': netG,
    #             'netD_exception': netD
    #         })
    #
    #     else:
    #         raise e

    trainer.run(loader, epochs)

main()


'''
kombucha_song = make_song(5, "kombucha")
next(kombucha_song) # '5 bottles of kombucha on the wall.'
next(kombucha_song) # '4 bottles of kombucha on the wall.'
next(kombucha_song) # '3 bottles of kombucha on the wall.'
next(kombucha_song) # '2 bottles of kombucha on the wall.'
next(kombucha_song) # 'Only 1 bottle of kombucha left!'
next(kombucha_song) # 'No more kombucha!'
next(kombucha_song) # StopIteration

default_song = make_song()
next(default_song) # '99 bottles of soda on the wall.'
'''

def make_song(count=99, beverage='soda'):
    while count >= 0:
        if count > 1:
            yield "{} bottles of {} on the wall.".format(count, beverage)
            count -= 1
        elif count == 1:
            yield "Only {} bottle of {} left!".format(count, beverage)
            count -= 1
        elif count == 0:
            yield "No more {}!".format(beverage)
            count -= 1
        else:
            raise StopIteration

a = make_song(5, "kombucha")
print("1", next(a))
print("2", next(a))
print("3", next(a))
print("4", next(a))
print("5", next(a))
print("6", next(a))
print("7", next(a))
print("+++++++++++++")

"""
solution from udemy:

def make_song(verses=99, beverage="soda"):
    for num in range(verses, -1, -1):
        if num > 1:
            yield "{} bottles of {} on the wall.".format(num, beverage)
        elif num == 1:
            yield "Only 1 bottle of {} left!".format(beverage)
        else:
            yield "No more {}!".format(beverage)
"""


import sys
input = sys.stdin.readline

m = int(input())
s = set()
for i in range(m):
    li = input().split()

    if len(li) == 1:
        if li[0] == 'all':
            s = set([i for i in range(1, 21)])
        else:
            s = set()
        continue

    else:
        b = int(li[1])

        if li[0] == 'add':
            if b not in s:
                s.add(b)
        elif li[0] == 'remove':
            s.discard(b)
        elif li[0] == 'check':
            if b in s:
                print(1)
            else:
                print(0)
        elif li[0] == 'toggle':
            if b in s:
                s.discard(b)
            elif b not in s:
                s.add(b)

# import sys
#
# m = int(sys.stdin.readline())
# S = set()
#
# for _ in range(m):
#     temp = sys.stdin.readline().strip().split()
#
#     if len(temp) == 1:
#         if temp[0] == "all":
#             S = set([i for i in range(1, 21)])
#         else:
#             S = set()
#
#     else:
#         func, x = temp[0], temp[1]
#         x = int(x)
#
#         if func == "add":
#             S.add(x)
#         elif func == "remove":
#             S.discard(x)
#         elif func == "check":
#             print(1 if x in S else 0)
#         elif func == "toggle":
#             if x in S:
#                 S.discard(x)
#             else:
#                 S.add(x)


import sys
import csv
import random

questions = []
categories = []
choices = []

pseudo = ["When day is Christmas?", "Type in the number 5", "Name a fruit", "Name a vegetable",
			"Name a country that starts with C", "Name an ocean", "Type the number 56", "Name an animal",
			"What month does Halloween fall under?", "Type the word hello", "Who is the current president?"]

def textMaker(filename):
	with open(filename,'rU') as csvfile:
	    reader = csv.reader(csvfile, delimiter=',')
	    for row in reader:
	      questions.append(row[0])
	      categories.append(row[1])
	      choices.append(row[2])

	f = open("template.txt", "w")
	f.write("[[AdvancedFormat]]\n\n")
	for i in range(0, len(questions) - 1):
		f.write("[[Block]]\n")
		if ((i + 1) % 5 == 0):
			f.write("[[Question:TextEntry:SingleLine]]\n")
			random.shuffle(pseudo);
			f.write(pseudo[0] + "\n");
		else:
			f.write("[[Question:Matrix]]\n")
			f.write(questions[i + 1] + ".\n\n")
			f.write("[[Choices]]\n")
			choices_temp = choices[i + 1].split(",")
			random.shuffle(choices_temp)
			for choice in choices_temp:
				f.write(choice.strip() + "\n")
			f.write("[[AdvancedAnswers]]\n")
			cat_temp = categories[i + 1].split(",")
			random.shuffle(cat_temp)
			for cat in cat_temp:
				f.write("[[Answer]]\n")
				f.write(cat.strip() + "\n")
		f.write("\n")

textMaker(sys.argv[1])


import cgi
from google.appengine.ext import db

from base import *
from pagefeed.models import Transform

class TransformHandler(BaseHandler):
	root = "/transform/"

	def all_instances(self):
		return Transform.find_all(self.user())

	def get(self):
		transforms = self.all_instances().fetch(limit=50)
		self.response.out.write(render_page('transforms', {'transforms':transforms}))

	def key(self):
		key = self.request.get('key')
		if not key:
			key = None
		return key

	def _get_transform_params(self):
		params = dict(owner=self.user())
		for param in Transform.required_properties:
			if param in params: continue
			value = self.request.get(param)
			if not value:
				raise ValueError(param)
			params[param] = value
		return params

	def post(self):
		transform_params = self._get_transform_params()
		if self.key() is not None:
			xform = db.get(self.key())
			assert isinstance(xform, Transform)
			[setattr(xform, k, v) for k,v in transform_params.items()]
		else:
			xform = Transform.create(self.request.get('action'), **transform_params)
		xform.put()
		if self.is_ajax():
			self.response.out.write(render('snippets', 'transform.html', {'transform':xform}))
		else:
			self.redirect(self.root)

class TransformDeleteHandler(TransformHandler):
	def post(self):
		debug("key: %r" % (self.key(),))
		xform = Transform.get(self.key())
		xform.delete()
		if not self.is_ajax():
			self.redirect(self.root)


from math import factorial, sqrt

def estimate_pi():
    accumulated_sum = 0
    limit_reached = False
    k = 0
    while not limit_reached:
        term = factorial(4 * k) * (1103 + 26390 * k) / ((factorial(k) ** 4) * (396 ** (4 * k)))
        accumulated_sum += term
        limit_reached = term < 1e-15
        k += 1
    return 2 * sqrt(2) * accumulated_sum / 9801

print(1 / estimate_pi())


'''
A_expt No. 5e:

Image Multiplication for 'Region of Interest' (ROI) Operations
'''

# Important imports:
from matplotlib import pyplot as plt, gridspec as gs

# importing images
img1=plt.imread('CH02\Fig0230(a)(dental_xray).tif')
img2=plt.imread('CH02\Fig0230(b)(dental_xray_mask).tif')

# plots
fig4=plt.figure(4)
gs4=gs.GridSpec(2,4)

ax41=plt.subplot(gs4[0:1,0:2])
ax41.set_title("Original Image")
ax41.axis("off")
ax41.imshow(img1,cmap='gray')

ax42=plt.subplot(gs4[1:2,0:2])
ax42.set_title("Region selection")
ax42.axis("off")
ax42.imshow(img2,cmap='gray')

ax42=plt.subplot(gs4[0:2,2:4])
ax42.set_title("Region of interest")
ax42.axis("off")
ax42.imshow(img1*img2,cmap='gray')

plt.suptitle(' Image Multiplication for "Region of Interest" (ROI) Operations',font='Times New Roman',fontweight="bold",fontsize=16)
plt.tight_layout()
fig4.set_size_inches(10, 8)
plt.savefig('input_output/A_expt5_e.jpg',dpi=400,)
fig4.set_size_inches(5, 4)
plt.show()


import discord
from discord.ext import commands
from apscheduler.schedulers.asyncio import AsyncIOScheduler
import datetime

def get_expire_time(minutes: int) -> datetime.datetime:
    """ get expire time after minutes from now
    args
        minutes: int
    return
        expire_time: datetime.datetime
    """
    now = datetime.datetime.now()
    expire_time = now + datetime.timedelta(minutes=minutes)
    return expire_time

bot = commands.Bot(command_prefix='!')

sched = AsyncIOScheduler()
sched.start()

class Timer(commands.Cog, name="Timer"):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name='start', help="Start timer recommended: '!start 25 5'")
    async def start(self, ctx, work_time: int=25, break_time: int=5):
        """ Start pomodoro timer
        Action:
            Start break_time timer after work_time timer
        Args:
            work_time : work timer (minute)
            break_time : break timer after work_time (minute)
        """

        if sched.get_job(job_id=str(ctx.author.id)) != None :
            await ctx.channel.send(
            f"```css\n[⚠Pomodoro timer already working!]\n - stop command : !stop```")
            return

        async def break_schedule(ctx, work_time, break_time):
            print('Enter break schedule')
            await ctx.channel.send(
                f"{ctx.author.mention}```css\n[🔥Break time end!] Let's work :)```")
            work_expire_time = get_expire_time(work_time)
            print(work_expire_time)
            sched.add_job(work_schedule, 'date', run_date=work_expire_time, args=[ctx,work_time, break_time],id=str(ctx.author.id))
            pass

        async def work_schedule(ctx, work_time, break_time):
            print('Enter work schedule')
            await ctx.channel.send(
                f"{ctx.author.mention}```css\n[🏁Work time end!] Let's break :)```")
            break_expire_time = get_expire_time(break_time)
            print(break_expire_time)
            sched.add_job(break_schedule, 'date', run_date=break_expire_time, args=[ctx,work_time, break_time],id=str(ctx.author.id))
            pass

        work_expire_time = get_expire_time(work_time)
        sched.add_job(work_schedule, 'date', run_date=work_expire_time, args=[ctx,work_time, break_time],id=str(ctx.author.id))

        await ctx.channel.send(
            f"```css\n[Work {work_time}min, Break {break_time}min] Pomodoro Timer START.\n - stop command : !stop```")

    @commands.command(name='stop', help="Stop timer")
    async def stop(self, ctx):
        """ Stop pomodoro timer
        Action:
            Stop pomodoro timer
        """
        sched.remove_job(job_id=str(ctx.author.id))
        await ctx.channel.send(
            f"```css\nPomodoro Timer STOP.\n - start command : !start [work_min] [break_min]```")

def setup(bot):
    bot.add_cog(Timer(bot))


import math

def divisors(a):
    divs = [1]
    for x in range(2, 1 + math.ceil(math.sqrt(a))):
        if a % x == 0:
            divs.append(x)
            divs.append(round(a/x))
    return(sorted(divs))

def amicable(a, b):
    if a == b:
        return(False)
    x = sum(divisors(a))
    y = sum(divisors(b))
    return(x == b and y == a)

sums = list()
for x in range(0, 10000):
    sums.append(sum(divisors(x)))

amicables = list()
for x in range(0, 10000):
    y = sums[x]
    if amicable(x, y) and set([x,y]) not in amicables:
        amicables.append(set([x,y]))

print(amicables)
last = list()
for x in amicables:
    for y in x:
        last.append(y)

print(sorted(last))
print(sum(last))


"""
This file is meant to test the geoencoder class as in TDD methodology
"""

from application.utils.geoencoder import Geoencoder
import json

# - Geoencoder:
geo = Geoencoder()

#   - find the location and address
def test_parse_address():
    with open("application/tests/mocks/address_dict.json") as file:
        JSON_DICT = json.load(file)

    test_dict = {
        "latitude": 44.8496861,
        "longitude": -0.5085099,
        "address": "1 Rue Martin du Gard, 33150 Cenon, France",
    }

    geo_search = geo.parse_address(JSON_DICT)

    assert geo_search["latitude"] == test_dict["latitude"]
    assert geo_search["longitude"] == test_dict["longitude"]
    assert geo_search["address"] == test_dict["address"]


from fuzzywuzzy import fuzz

import logging as log

from genetic.populate import GenMaster, string_mutator
from langtools.translate import Translator
from langtools.text_distance import text_distance
import data.voynich.voynich as voy
import data.lang.turkish.turkish as turk

def run():
    vo_alphabet = voy.get_alphabet()
    turk_alphabet = turk.get_alphabet()

    vo_words = voy.get_first_page_normal().split(".")

    log.debug("Voynich words from 1st page: %s", vo_words)

    turk_words = turk.get_words()[:100]

    log.debug("Get %d turkish words", len(turk_words))

    def dist(s1, s2):
        return 100 - fuzz.ratio(s1, s2)

    def calculate(tralph):
        tr = Translator(vo_alphabet, tralph)
        words_translated = [tr.trans(w) for w in vo_words]

        return text_distance(words_translated, turk_words, dist)

    log.info("Generate population...")
    population = []
    for i in range(100):
        population.append(string_mutator(turk_alphabet, len(turk_alphabet)))

    log.info("Population generated")

    gm = GenMaster(population)

    for i in range(100):
        log.info("Start %d generation calculation", i)
        gm.generation(calculate)
        log.info("Calculation terminated")
        log.debug("%d generation is: %s", i, gm.population)

        tr = Translator(vo_alphabet, gm.population[0])
        translated = " ".join([tr.trans(w) for w in vo_words])
        log.info("Translated text: %s", translated)

    log.info("Final generation is: %s", gm.population)


from .util import change_in_nets

class EquivClass:
    """Defines an equivalence class of ExpressionNodes

    This represents nodes that are mathematically distinct,
    but physically equivalent.

    Attributes:
        nodes (set of ExpressionNode): The nodes in this equivalence class
        rep (ExpressionNode): The representative of this equivalence class
        out_nets (dict): The output nets of this equivalence class
        parents (set of EquivClass): The parents of this equivalence class
    """

    def __init__(self, rep):
        """Initializes an EquivClass object

        Args:
            rep (ExpressionNode): The representative of this equivalence class
            nodes (list of ExpressionNode): The nodes in this equivalence class
        """
        self.rep = rep
        self.nodes = {rep}
        self.out_nets = rep.out_nets
        self.parents = set()

    def __len__(self):
        """Returns the number of nodes in this equivalence class"""
        return len(self.nodes)

    def __iter__(self):
        """Iterates over the nodes in this equivalence class"""
        return iter(self.nodes)

    def equiv(self, other):
        """Returns whether this equivalence class is equivalent to another

        Args:
            other (EquivClass): The equivalence class to compare to
        """
        if not isinstance(other, EquivClass):
            raise TypeError("other must be an EquivClass")

        other_rep = other.rep
        # Check whether the two representatives are equivalent
        if self.rep > other.rep or self.rep < other.rep:
            return False
        if self.rep.value != other.rep.value:
            return False

        # Check whether their subtrees are also equivalent
        for a in range(len(self.rep.children)):
            this_c = self.rep[a]
            if this_c is not None:
                try:
                    other_c = other_rep[a]
                except IndexError:
                    return False
                if not this_c.equiv_class == other_c.equiv_class:
                    return False

        return True

    def __str__(self):
        """Returns a string representation of this equivalence class"""
        return "ec({}@{})#{}".format(self.rep, self.rep.graph, len(self))

    def __repr__(self):
        return str(self)

    def _recalculate_parents(self):
        """Recalculates the parents of this equivalence class"""
        self.parents = set()
        for node in self:
            parent = node.parent
            if parent is None:
                self.parents.add(None)
            else:
                self.parents.add(parent.equiv_class.rep)
        return

    def change_rep(self, new_rep):
        """Changes the representative of this equivalence class"""
        if new_rep not in self.nodes:
            raise ValueError("new_rep must be in this equivalence class")

        # Change the attributes of related equivalence classes
        for c in new_rep:
            if c is None:
                continue
            c.equiv_class.parents.remove(self.rep)
            c.equiv_class.parents.add(new_rep)

        # Change the attributes of this equivalence class
        for node in self:
            parent = node.parent
            index = parent.children.index(node)
            change_in_nets(parent, self.out_nets, new_rep.out_nets, index)
        self.rep = new_rep
        self.out_nets = new_rep.out_nets

        return

    def merge(self, other, check_equiv=True):
        """Merges this equivalence class with another equivalence class

        Args:
            other (EquivClass): The equivalence class to merge with
        """
        if not isinstance(other, EquivClass):
            raise TypeError("other must be an EquivClass")
        if check_equiv and not self.equiv(other):
            raise ValueError("Cannot merge non-equivalent equivalence classes")

        # Merge the equivalence classes
        self.nodes |= other.nodes
        self.parents |= other.parents

        # Merge the out_nets
        for k, v in self.out_nets.items():
            if v == [None]:
                self.out_nets[k] = other.out_nets[k]

        # Assign the correct equivalence class to new nodes
        # Overwrite input nets of new nodes
        for node in other.nodes:
            node.equiv_class = self
            parent = node.parent
            index = parent.children.index(node)
            change_in_nets(parent, node.out_nets, self.rep.out_nets, index)

        return self

    def is_bifurcation(self):
        """Returns whether this equivalence class bifurcates

        That is to say, this answers ∃n ≡ self s.t n.parent !≡ self.parent
        """
        return len(self.parents) > 1

    def reset(self):
        """Resets the equivalence classes of all nodes in this class"""
        for node in self:
            node.equiv_class = EquivClass(node)
            parent = node.parent
            index = parent.children.index(node)
            change_in_nets(parent, self.rep.out_nets, node.out_nets, index)
        return

if __name__ == "__main__":
    raise RuntimeError("This module is not intended to be run directly")


from vunit import VUnit
from itertools import product
from random import sample, choice
import glob
from os.path import dirname
# Create VUnit instance by parsing command line arguments
vu = VUnit.from_argv()
vu.add_vhdl_builtins()
# Function for mult range calculations
def get_ranges(dat_w,margin):
    min_val = -(2**(dat_w-1))
    max_val = (-min_val)-1
    if 2*margin < max_val:
        ab_value_ranges = [
            (min_val,min_val+margin,-margin,margin-1),
            (-margin,+margin,-margin,margin-1),
            (max_val,max_val-margin,-margin,margin-1)
            ]
    else:
        ab_value_ranges = [(min_val, max_val, min_val, max_val)]
    return ab_value_ranges

# Function to vary tb configurations
def generate_tests(obj, in_dat_w, inp_pipeline,product_pipeline, out_pipeline, conjugate_b=None, adder_pipeline=None):
    """
    Generate test by varying the generics of common_counter:
        in_dat_w : int {4,5,6,7,8}
        conjugate_b : int {TRUE,FALSE}
        out_dat_w : int {2*in_dat_w}
        out_pipeline : >=0
        inp_pipeline : {0,1}
        adder_pipeline : {0,1}
        product_pipeline : {0,1}
    """
    testnum = 1
    if not conjugate_b:
        for i_d_w in in_dat_w:
            margin = 16
            ab_value_ranges = get_ranges(i_d_w,margin)
            ab_value_ranges = sample(ab_value_ranges, min(2, len(ab_value_ranges)))
            for a_v_min, a_v_max, b_v_min, b_v_max in ab_value_ranges:
                value_range_string = ", a_val = [%d, %d] , b_val = [%d, %d]" % (a_v_min, a_v_max,b_v_min,b_v_max)
                config_name = "i_d_w=%i, o_d_w=%i, inp_pipeline=%i, out_pipeline=%i, prod_pipe=%i" % (i_d_w, 2 * i_d_w + 1, inp_pipeline, out_pipeline, product_pipeline) +\
                                value_range_string
                config_name = "TestNum%d"%(testnum)
                testnum=testnum+1
                obj.add_config(
                    name = config_name,
                    generics=dict(g_in_dat_w=i_d_w, g_out_dat_w=2*i_d_w + 1, g_pipeline_input=inp_pipeline, g_pipeline_product=product_pipeline,
                    g_pipeline_output=out_pipeline, g_a_val_min=a_v_min, g_a_val_max=a_v_max, g_b_val_min=b_v_min, g_b_val_max=b_v_max)
                )
    else:
        for i_d_w, conj_b in product(in_dat_w,conjugate_b):
            margin = 16
            ab_value_ranges = get_ranges(i_d_w,margin)
            a_v_min, a_v_max, b_v_min, b_v_max = choice(ab_value_ranges)
            config_name = "i_d_w=%i, o_d_w=%i, conj_b=%i, inp_pipeline=%i, out_pipeline=%i, add_pipe=%i, prod_pipe=%i" % (i_d_w, 2 * i_d_w + 1, conj_b, inp_pipeline, out_pipeline, adder_pipeline, product_pipeline)
            config_name = "ConjTest%d"%(testnum)
            testnum=testnum+1
            obj.add_config(
                name = config_name,
                generics=dict(g_in_dat_w=i_d_w, g_out_dat_w=2*i_d_w + 1, g_conjugate_b=conj_b, g_pipeline_input=inp_pipeline, g_pipeline_product=product_pipeline, g_pipeline_adder=adder_pipeline,
                g_pipeline_output=out_pipeline, g_a_val_min=a_v_min, g_a_val_max=a_v_max, g_b_val_min=b_v_min, g_b_val_max=b_v_max)
            )

script_dir = dirname(__file__)

# CASPER MUlTIPLIER Library
casper_multiplier_lib = vu.add_library("casper_multiplier_lib", allow_duplicate=True)
txt = glob.glob(script_dir + "/*.vhd")
for x in txt:
    s = x.split('/')[-1]
    casper_multiplier_lib.add_source_files(x)

# COMMON COMPONENTS Library
common_components_lib = vu.add_library("common_components_lib",allow_duplicate=True)
common_components_lib.add_source_files(script_dir + "/../common_components/common_pipeline.vhd")
common_components_lib.add_source_files(script_dir + "/../common_components/common_pipeline_sl.vhd")

# COMMON PACKAGE Library
common_pkg_lib = vu.add_library("common_pkg_lib",allow_duplicate = True)
common_pkg_lib.add_source_files(script_dir + "/../common_pkg/*.vhd")
common_pkg_lib.add_source_files(script_dir + "/../common_pkg/tb_common_pkg.vhd")

# TECHNOLOGY Library
technology_lib = vu.add_library("technology_lib",allow_duplicate = True)
technology_lib.add_source_files(script_dir + "/../technology/technology_select_pkg.vhd")

# XPM Multiplier library
ip_xpm_mult_lib = vu.add_library("ip_xpm_mult_lib", allow_duplicate=True)
ip_xpm_mult_lib.add_source_files(script_dir + "/../ip_xpm/mult/*.vhd")

# STRATIXIV Multiplier library
ip_stratixiv_mult_lib = vu.add_library("ip_stratixiv_mult_lib", allow_duplicate=True)
ip_stratixiv_mult_lib.add_source_files(script_dir + "/../ip_stratixiv/mult/*rtl.vhd")

inp_pipeline_values = 1
product_pipeline_values = 0
adder_pipeline_values = 1
out_pipeline_values = 1
in_dat_w_values = [18] + sample(range(4, 8), 1)
conj_values = [True,False]

#TB CONFIGURATION
TB_GENERATED_1 = casper_multiplier_lib.test_bench("tb_tb_vu_common_complex_mult")
TB_GENERATED_2 = casper_multiplier_lib.test_bench("tb_tb_vu_common_mult")

generate_tests(
    TB_GENERATED_1,
    in_dat_w_values,
    inp_pipeline_values,
    product_pipeline_values,
    out_pipeline_values,
    conj_values,
    adder_pipeline_values
)
generate_tests(
    TB_GENERATED_2,
    in_dat_w_values,
    inp_pipeline_values,
    product_pipeline_values,
    out_pipeline_values
)

# RUN
vu.set_compile_option("ghdl.a_flags", ["-frelaxed", "-Wno-hide"])
vu.set_sim_option("ghdl.elab_flags", ["-frelaxed","--syn-binding"])
vu.main()


import logging

from odoo import api, fields, models, _, Command
from odoo.exceptions import ValidationError
from odoo.http import request

_logger = logging.getLogger(__name__)

class ResUsers(models.Model):
    _inherit = 'res.users'

    website_id = fields.Many2one('website', related='partner_id.website_id', store=True, related_sudo=False, readonly=False)

    _sql_constraints = [
        # Partial constraint, complemented by a python constraint (see below).
        ('login_key', 'unique (login, website_id)', 'You can not have two users with the same login!'),
    ]

    @api.constrains('login', 'website_id')
    def _check_login(self):
        """ Do not allow two users with the same login without website """
        self.flush_model(['login', 'website_id'])
        self.env.cr.execute(
            """SELECT login
                 FROM res_users
                WHERE login IN (SELECT login FROM res_users WHERE id IN %s AND website_id IS NULL)
                  AND website_id IS NULL
             GROUP BY login
               HAVING COUNT(*) > 1
            """,
            (tuple(self.ids),)
        )
        if self.env.cr.rowcount:
            raise ValidationError(_('You can not have two users with the same login!'))

    @api.model
    def _get_login_domain(self, login):
        website = self.env['website'].get_current_website()
        return super(ResUsers, self)._get_login_domain(login) + website.website_domain()

    @api.model
    def _get_email_domain(self, email):
        website = self.env['website'].get_current_website()
        return super()._get_email_domain(email) + website.website_domain()

    @api.model
    def _get_login_order(self):
        return 'website_id, ' + super(ResUsers, self)._get_login_order()

    @api.model
    def _signup_create_user(self, values):
        current_website = self.env['website'].get_current_website()
        # Note that for the moment, portal users can connect to all websites of
        # all companies as long as the specific_user_account setting is not
        # activated.
        values['company_id'] = current_website.company_id.id
        values['company_ids'] = [Command.link(current_website.company_id.id)]
        if request and current_website.specific_user_account:
            values['website_id'] = current_website.id
        new_user = super(ResUsers, self)._signup_create_user(values)
        return new_user

    @api.model
    def _get_signup_invitation_scope(self):
        current_website = self.env['website'].sudo().get_current_website()
        return current_website.auth_signup_uninvited or super(ResUsers, self)._get_signup_invitation_scope()

    @classmethod
    def authenticate(cls, db, login, password, user_agent_env):
        """ Override to link the logged in user's res.partner to website.visitor.
        If a visitor already exists for that user, assign it data from the
        current anonymous visitor (if exists).
        Purpose is to try to aggregate as much sub-records (tracked pages,
        leads, ...) as possible. """
        visitor_pre_authenticate_sudo = None
        if request and request.env:
            visitor_pre_authenticate_sudo = request.env['website.visitor']._get_visitor_from_request()
        uid = super(ResUsers, cls).authenticate(db, login, password, user_agent_env)
        if uid and visitor_pre_authenticate_sudo:
            env = api.Environment(request.env.cr, uid, {})
            user_partner = env.user.partner_id
            visitor_current_user_sudo = env['website.visitor'].sudo().search([
                ('partner_id', '=', user_partner.id)
            ], limit=1)
            if visitor_current_user_sudo:
                # A visitor exists for the logged in user, link public
                # visitor records to it.
                if visitor_pre_authenticate_sudo != visitor_current_user_sudo:
                    visitor_pre_authenticate_sudo._merge_visitor(visitor_current_user_sudo)
                visitor_current_user_sudo._update_visitor_last_visit()
            else:
                visitor_pre_authenticate_sudo.access_token = user_partner.id
                visitor_pre_authenticate_sudo._update_visitor_last_visit()
        return uid


from potencia_aleatoria import PotenciaAleatoria

class AnalisadorPotencia:
    def __init__(self, base, expoente):
        self.base = base
        self.expoente = expoente
        self.padrao_ultimos_digitos = self.listar_padrao_de_ultimos_digitos()
        self.ultimo_digito = self.encontrar_ultimo_digito_da_potencia()

    def __str__(self):
        analise = "\n"
        analise += f"Potência: {self.base}^{self.expoente}\n"
        analise += f"Base: {self.base}\n"
        analise += f"Expoente: {self.expoente}\n"
        analise += f"Último dígito: {self.ultimo_digito}\n"
        analise += f"Padrão de últimos dígitos: {self.padrao_ultimos_digitos}"

        return analise

    def listar_padrao_de_ultimos_digitos(self):
        ultimo_digito_numero = self.extrair_ultimo_digito_do_numero(self.base)
        padrao_ultimos_digitos = []

        for e in range(self.expoente):
            if ultimo_digito_numero in padrao_ultimos_digitos:
                return padrao_ultimos_digitos

            padrao_ultimos_digitos.append(ultimo_digito_numero)
            ultimo_digito_numero = self.calcular_ultimo_digito_do_expoente_seguinte(ultimo_digito_numero)

        # O padrão não foi encontrado. O expoente não é grande suficiente para gerar o padrão.
        return []

    def extrair_ultimo_digito_do_numero(self, numero):
        return int(str(numero)[-1])

    def calcular_ultimo_digito_do_expoente_seguinte(self, ultimo_digito_numero):
        ultimo_digito_numero *= self.base
        ultimo_digito_numero = self.extrair_ultimo_digito_do_numero(ultimo_digito_numero)
        return ultimo_digito_numero

    def encontrar_ultimo_digito_da_potencia(self):
        padrao_ultimos_digitos = self.listar_padrao_de_ultimos_digitos()

        if padrao_ultimos_digitos:
            periodo_do_padrao = len(padrao_ultimos_digitos)
            resto_expoente = self.expoente % periodo_do_padrao

            for i in range(periodo_do_padrao):
                resto_da_posicao_do_digito_do_padrao = (i + 1) % periodo_do_padrao

                if resto_expoente == resto_da_posicao_do_digito_do_padrao:
                    ultimo_digito_potencia = padrao_ultimos_digitos[i]
                    return ultimo_digito_potencia

        # Se chegar aqui, então o expoente dado não foi grande suficiente para encontrar o padrão...
        # No entanto, isso significa que ele é pequeno o suficiente para calcular a potência e descobrir o último dígito diretamente!

        ultimo_digito_potencia = self.calcular_potencia()
        return ultimo_digito_potencia

    def calcular_potencia(self):
        potencia = pow(self.base, self.expoente)
        ultimo_digito_potencia = self.extrair_ultimo_digito_do_numero(potencia)
        return ultimo_digito_potencia

if __name__ == "__main__":
    for i in range(10):
        potencia = PotenciaAleatoria()
        analisador = AnalisadorPotencia(potencia.base, potencia.expoente)
        print(analisador)


def encrypt(n, plaintext, key='1234567890'):
    result = ''

    for l in plaintext:
        try:
            i = (key.index(l) + n) % 10
            result += key[i]
        except ValueError:
            result += l

    return result

def decrypt(n, ciphertext, key='1234567890'):
    result = ''

    for l in ciphertext:
        try:
            i = (key.index(l) - n) % 10
            result += key[i]
        except ValueError:
            result += l

    return result

def show_result(plaintext, n, key='1234567890'):
    """
        >>> from demoapp.tools.caesarcipher import *
        >>> origin = '1234567890abcdefghijklmnopqrstuvwxyz'
        >>> e1 = encrypt(1, origin)
        '2345678901abcdefghijklmnopqrstuvwxyz'
        >>> e2 = encrypt(3, origin)
        '4567890123abcdefghijklmnopqrstuvwxyz'
        >>> assert(origin == decrypt(1, e1))
        >>> assert(origin == decrypt(3, e1))
    """
    encrypted = encrypt(n, plaintext, key)
    decrypted = decrypt(n, encrypted, key)

    print('Rotation: %s' % n)
    print('Plaintext: %s' % plaintext)
    print('Encrytped: %s' % encrypted)
    print('Decrytped: %s' % decrypted)


"""Берёт те статьи из словаря XI-XVII, для которых не нашлось соответствий в словаре Аванесова. Пишет это всё в 'matched.json'."""
__author__ = "Michael Voronov, Anna Sorokina"
__license__ = "GPLv3"

import json
import pandas

import pyximport; pyximport.install()
from unification import unify

with open('prematched.json', 'r') as f:
    prematched = json.loads(f.read())

shit = pandas.read_csv('wordlist_linked.csv', delimiter=',', header=0, low_memory=False)
x11 = list(shit.LemmaIndex)

for x11_lemma in x11:
    if isinstance(x11_lemma, str):
        x11_unified = unify(x11_lemma)
        if not x11_unified in prematched:
            prematched[x11_unified] = {
                'XVII_lemma': x11_lemma
            }

with open('matched.json', 'w') as f:
    json.dump(prematched, f, indent=4, ensure_ascii=False)


from tkinter import *
from tkinter import messagebox
import requests, bs4
import sys
import io
from contextlib import redirect_stdout

def pogoda(city): #функция с погодой на сегодняшний день
    city=city.get()
    s=requests.get('https://sinoptik.com.ru/погода-'+city) #URL сайта, откуда берется информация о городе и его погоде
    b=bs4.BeautifulSoup(s.text, "html.parser")

    buffer = io.StringIO()

    p = b.select('.rSide .description') #краткое описание
    pogoda = p[0].getText()
    print('\n '+pogoda.strip()+'\n', file=buffer)

    p3=b.select('.temperature .p3') #температура утром
    pogoda1=p3[0].getText()
    p4=b.select('.temperature .p4')
    pogoda2=p4[0].getText()
    p5=b.select('.temperature .p5') #тепература днём
    pogoda3=p5[0].getText()
    p6=b.select('.temperature .p6')
    pogoda4=p6[0].getText()
    print(' Утром ' + pogoda1 + ' ' + pogoda2, file=buffer)
    print(' Днём ' + pogoda3 + ' ' + pogoda4, file=buffer)

    s=b.select('.infoDaylight') #восход и закат
    sun=s[0].getText()
    print(sun,file=buffer)

    v=b.select('.weatherDetails .p5') #давление
    davlenie=v[4].getText()
    print(' Давление '+davlenie+' мм',file=buffer)

    vlazhnost=v[5].getText()  #влажность
    print(' Влажность '+vlazhnost+' %',file=buffer)

    veter=b.select('.gray .p5') #направление и скорость ветра
    veter2=veter[2].find("div")["data-tooltip"]
    print(' Ветер '+veter2,file=buffer)

    osadki=v[7].getText()  #вероятность осадков
    print(' Вероятность осадков '+osadki+' %',file=buffer)
    output = buffer.getvalue()
    return output

def pogoda2(city): #функция с погодой на неделю
    city=city.get()
    s=requests.get('https://sinoptik.com.ru/погода-'+city)
    b=bs4.BeautifulSoup(s.text, "html.parser")
    buffer2 = io.StringIO()
    p = b.select('.tabs .main')
    i=0
    while i!=7:
        day = p[i].getText() #температура каждого дня
        print(day,file=buffer2)
        i=i+1
        number="bd"+str(i)
        desc2=b.find("div",attrs={"id":number}) #описание погоды каждого дня
        desc3=desc2.find("div",attrs={"class":"weatherIco"})["title"]
        print(" ",desc3,"\n",file=buffer2)
    output2 = buffer2.getvalue()
    return output2

top = Tk()
top.geometry("400x200")
top.title('Forecast')

def pogodaMsg():
    msg = messagebox.showinfo("Результат",pogoda(city))
def pogoda2Msg():
    msg = messagebox.showinfo("Результат",pogoda2(city))

L1 = Label(top, text = "Введите город")
L1.place(x = 50,y = 50)
city = Entry(top, bd = 5)
city.place(x = 200,y = 50)

B = Button(top, text = "Погода на сегодня", command = pogodaMsg)
B.place(x = 50,y = 100)

B = Button(top, text = "Погода на неделю", command = pogoda2Msg)
B.place(x = 200,y = 100)

top.mainloop()


import os
import abc

class SubparserException(Exception):
    """
    Exception class thrown when a subparser encounters an unrecoverable error.
    """

class Subparser(object):
    """
    Base class for subparsers which can be instantiated and registered with a ConfigManager.
    """

    __metaclass__ = abc.ABCMeta
    subparserException = SubparserException

    @abc.abstractmethod
    def parse(self, configManager, config):
        """
        Function which must accept a _Config instance of configuration options parsed thus far, and return a dictionary
        containing new configuration options to add to the _Config object.

        Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
                config        - The _Config object containing configuration options populated thus far.

        Outputs: A dictionary of new configuration options to add to the Config object.
        """

        raise NotImplementedError()

class ConfigFileSubparser(Subparser):
    """
    Base class for subparsers which require an input file to parse.
    """

    def __init__(self, filepath=None, filename=None, filepathConfig=None, filenameConfig=None):
        """
        Initializes this configuration file parser.
        Note: At least one set of either filepath & filename, or filepathConfig & filenameConfig must be passed.
              If both are passed, both will be checked, though only the first will be parsed.  The order that they will
              be checked is filenameConfig/filepathConfig first, then filepath/filename second.

        Inputs: filepath       - Either a list containing the path directories to where the configuration file is
                                 stored or a string of the complete path to the directory where the configuration file
                                 to be parsed can be found.
                filename       - The name of the configuration file to be parsed.
                filepathConfig - The name of the configuration option to retrieve the configuration file path from.
                filenameConfig - The name of the configuration option to retrieve the the configuration filename from.
        """

        self.filepath = filepath
        self.filename = filename
        self.filepathConfig = filepathConfig
        self.filenameConfig = filenameConfig

        # Ensure either filepath/filename or filepathConfig/filenameConfig was passed.
        if (filepath is None or filename is None) and (filepathConfig is None or filenameConfig is None):
            raise self.subparserException("A file configuration parser must be either explicitely initialized using " +
                                          "filepath and filename keyword arguments, or filepathConfig and " +
                                          "filenameConfig keyword arguments")

    def _getConfigFile(self, config):
        """
        Retrieves a file descriptor to a configuration file to process.

        Inputs: config - The _Config object which is being populated.

        Outputs: An open file descriptor to the configuration file to parse in read mode if successful, else None.
        """

        joinPath = lambda p: (os.path.join(p) if isinstance(p, (tuple, list)) else p)

        if self.filepathConfig is not None and self.filenameConfig is not None:
            if hasattr(config, self.filepathConfig) and hasattr(config, self.filenameConfig):
                path = joinPath(getattr(config, self.filepathConfig))
                name = getattr(config, self.filenameConfig)

                if os.path.isfile(os.path.join(path, name)):
                    return open(os.path.join(path, name), 'r')

        if self.filepath is not None and self.filename is not None:
            path = joinPath(self.filepath)
            name = self.filename

            if os.path.isfile(os.path.join(path, name)):
                return open(os.path.join(path, name), 'r')