import numpy as np
from scipy.sparse import lil_matrix, identity, vstack, block_diag
from scipy.sparse.linalg import spsolve
from scipy.optimize import linprog

class LinearProgramming(object):
    """
    LinearProgramming(num_states, num_actions, rewards, state_transition_probs, discount)

    Finds an optimal value and a policy of a Markov decision process.
    Parameters
    ----------
    num_states : int
        Number of elements in the set of states.
    num_actions : int
        Number of elements in the set of actions.
    rewards : numpy.ndarray
        Reward values in given states and actions.
        $r(s, a)$.
    state_transition_probs : numpy.ndarray
        Probability in transion to a next state $s'$ given state $s$ and action $a$.
    """

    def __init__(self, num_states, num_actions, rewards, state_transition_probs, discount):

        self.rewards = rewards
        self.discount = discount
        self.state_transition_probs = state_transition_probs
        self.num_states = num_states
        self.num_actions = num_actions
        self.policy = np.empty((num_states), dtype=int)

        # Setup matrix form
        self.c = np.ones((num_states),dtype=np.float32) / num_states
        self.A = discount * state_transition_probs - block_diag(
            (np.ones((num_actions, 1), dtype=np.float32),) * num_states,
            format='csc'
        )
        self.b = - np.reshape(self.rewards, -1)

    def fit(self, max_iteration=1e3, tolerance=1e-3, verbose=False, logging=False, dual=False):

        if dual:
            res = linprog(
                self.b,
                A_eq = self.A.T,
                b_eq = -self.c,
                bounds = (0, None),
                method = 'interior-point',
                options = {
                    'maxiter':max_iteration,
                    'tol':tolerance,
                    'disp':verbose,
                    'sparse':False
                }
            )
            self.policy = np.argmax(np.reshape(res.x, (self.num_states, -1)), axis=1)
            _one_hot_policy =  np.eye(self.num_actions)[self.policy].astype(bool)
            _I_s = identity(self.num_states, dtype=np.float32, format='csc')
            _A = _I_s - self.discount * vstack(
                [self.state_transition_probs[s*self.num_actions+a, :] for s, a in enumerate(self.policy)],
                format='csc'
            )
            self.values = spsolve(_A, self.rewards[_one_hot_policy])
        else:
            res = linprog(
                self.c,
                A_ub = self.A,
                b_ub = self.b,
                bounds = None,
                method = 'interior-point',
                options = {
                    'maxiter':max_iteration,
                    'tol':tolerance,
                    'disp':verbose,
                    'sparse':False
                }
            )
            self.values = res.x
            for s in range(self.num_states):
                _q = self.rewards[s, :] + self.discount * self.state_transition_probs[s*self.num_actions:(s+1)*self.num_actions, :] * self.values
                # Evaluate the deterministic policy $\pi(s)$
                self.policy[s] = np.argmax(_q)

        return res

def test(Model):
    """
    Test code for debugging
    """

    from scipy.sparse import dok_matrix

    # Setup the number of states and actions
    n_states = 11
    n_actions = 3

    # Setup the reward $r(s,a)$
    rewards = np.zeros([n_states, n_actions])
    rewards[-1, -1] = 1

    # Setup the random state transition probability $P(s'|s,a)$
    p = np.float32(0.5)
    state_transition_probs = np.empty((n_states), dtype=np.object)
    for i in range(n_states):
        P = dok_matrix(
            (1.0 - p) * np.ones((n_actions, n_states), dtype=np.float32) / np.float32(n_states - 1)
        )
        for j in range(n_actions):
            P[j, np.random.randint(low=0, high=n_states)] = p
        state_transition_probs[i] = P
    state_transition_probs = vstack(state_transition_probs, format='csr')

    # Test model
    model = Model(
        n_states, n_actions, rewards, state_transition_probs,
        0.99 # - np.finfo(np.float32).eps
    )
    model.fit(max_iteration=100, tolerance=0.001, verbose=True, dual=False)

if __name__=='__main__':

    test(LinearProgramming)


"""
Unit tests for JobQueue class
"""

import logging
import mock
import time

import pytest

from jade.enums import Status
from jade.jobs.async_job_interface import AsyncJobInterface
from jade.jobs.job_queue import JobQueue

class FakeJob(AsyncJobInterface):
    def __init__(self, name, duration, blocking_jobs=None):
        self._name = name
        self._duration = duration
        self._blocking_jobs = set() if blocking_jobs is None else blocking_jobs
        self.start_time = None
        self.end_time = None
        self._is_complete = False

    def cancel(self):
        self._is_complete = True

    @property
    def cancel_on_blocking_job_failure(self):
        return False

    def get_id(self):
        return 0

    def is_complete(self):
        if self._is_complete:
            return True
        return time.time() > self.end_time

    @property
    def name(self):
        return self._name

    @property
    def return_code(self):
        assert self.is_complete()
        return 0

    def run(self):
        self.start_time = time.time()
        self.end_time = self.start_time + self._duration
        return Status.GOOD

    def get_blocking_jobs(self):
        return self._blocking_jobs

    def remove_blocking_job(self, name):
        self._blocking_jobs.remove(name)

    def set_blocking_jobs(self, jobs):
        assert False

def test_job_queue__is_full():
    duration = 10
    jobs = [FakeJob(str(i), duration) for i in range(4)]
    queue = JobQueue(2, poll_interval=1)
    assert not queue.is_full()
    for job in jobs:
        queue.submit(job)
    assert queue.is_full()

def test_job_queue__run_jobs_no_ordering():
    duration = 0.1
    jobs = [FakeJob(str(i), duration) for i in range(10)]
    JobQueue.run_jobs(jobs, 5, poll_interval=0.1)
    for job in jobs:
        assert job.is_complete()

def test_job_queue__run_jobs_ordering():
    duration = 0.1
    jobs = {}
    for i in range(1, 11):
        name = str(i)
        if i == 1:
            job = FakeJob(name, duration, blocking_jobs=set(["10"]))
        elif i == 2:
            job = FakeJob(name, duration, blocking_jobs=set(["1"]))
        elif i == 3:
            job = FakeJob(name, duration, blocking_jobs=set(["4", "5"]))
        else:
            job = FakeJob(name, duration)
        jobs[name] = job
    JobQueue.run_jobs(jobs.values(), 5, poll_interval=0.1)

    for job in jobs.values():
        assert job.is_complete()
        assert not job.get_blocking_jobs()

    assert jobs["1"].start_time > jobs["10"].end_time
    assert jobs["2"].start_time > jobs["1"].end_time
    assert jobs["3"].start_time > jobs["4"].end_time
    assert jobs["3"].start_time > jobs["5"].end_time

def test_job_queue__monitor_func():
    has_run = []

    def monitor(ids=None):
        has_run.append(1)

    duration = 0.1
    jobs = [FakeJob(str(i), duration) for i in range(1)]
    JobQueue.run_jobs(jobs, 5, poll_interval=0.1, monitor_func=monitor)
    assert has_run

def job_run():
    """Job run"""
    time.sleep(0.5)

def test_job_queue():
    """Job queue should run with expection"""

    job1 = mock.MagicMock()
    job1.name = "Job1"

    job2 = mock.MagicMock()
    job2.name = "Job2"

    job3 = mock.MagicMock()
    job3.name = "Job3"

    jobs = [job1, job2, job3]

    # TODO: Finish up this test
    # JobQueue.run_jobs(jobs, max_queue_depth=2)


from utils import *

# create vocabulary

def myProcessing(tweet, vocab_file):
    #tweet = tweet.lower()
    d = re.split('\s', tweet[:-1])
    v = read_vocab(vocab_file)
    n = len(d)
    t = len(v)
    print(n, t)
    X = np.zeros((t,), dtype=np.double)
    for word in d:
        if word in v:
            print("word: ", word)
            X[v.index(word)] += 1
    #print(X)
    return X

if __name__ == '__main__':
    myProcessing("France: 10 people dead after shooting at HQ of satirical weekly newspaper #CharlieHebdo, according to witnesses http://t.co/FkYxGmuS58", 'vocab1.txt')


from django.test import TestCase, Client

from tests.fixtures import gen_author, gen_book

client = Client()
BASE_URL='//127.0.0.1:8000'

class TestViews(TestCase):
    def setUp(self):
        self.authors = [
            gen_author(name='Filip Springer'),
            gen_author(name='Jiro Taniguchi'),
        ]
        self.books = [
            gen_book(title='Wanna z kolumnadą', author=self.authors[0]),
            gen_book(title='Miedzianka', author=self.authors[0]),
            gen_book(title='Idący człowiek', author=self.authors[1]),
        ]

    def test_book_list(self):
        response = client.get(f'{BASE_URL}')
        for book in self.books:
            self.assertIn(book, response.context['object_list'])
        self.assertEqual(response.status_code, 200)

    def test_book_detail(self, pk=1):
        response = client.get(f'{BASE_URL}/book_detail/{pk}')
        response_author = response.context['object'].author
        expected_author = self.books[0].author

        self.assertEqual(expected_author, response_author)
        self.assertEqual(self.books[0].title, response.context['object'].title)
        self.assertEqual(response.status_code, 200)


import pytube
import yt_dlp
import os
import cv2
from sklearn.cluster import KMeans
import numpy as np
import urllib.request
from Saturn import get_bucket
from discord import FFmpegPCMAudio
from urllib.request import urlopen

ffmpeg_options = {
    'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
    'options': '-vn',
}
YTDL_OPTIONS = {
    'format': 'bestaudio/best',
    'extractaudio': True,
    'audioformat': 'mp3',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0',
}
FFMPEG = os.environ.get("FFMPEG")
music_files_bucket = get_bucket("storage/music")
ytdl = yt_dlp.YoutubeDL(YTDL_OPTIONS)

def wrap(url):
    return FFmpegPCMAudio(urlopen(url), pipe=True, executable=FFMPEG)

class Goblin:
    def __init__(self, pytube_obj: pytube.YouTube):
        self.yt_obj = pytube_obj
        self.title = self.yt_obj.title
        self.thumbnail = self.yt_obj.thumbnail_url
        self.author = self.yt_obj.author
        try:
            self.seconds = self.yt_obj.length
        except TypeError:
            self.seconds = 0
        self.url = self.yt_obj.watch_url
        self.filename = 'vid_' + self.yt_obj.video_id + ".mp3"
        self.filename = music_files_bucket.alloc_file(self.filename)  # Pretend like file exists
        try:
            self.color = self.get_color()
        except:
            self.color = 0x000000

    def get_color(self):
        filename = self.filename + "_picture.jpg"
        music_files_bucket.alloc_file(filename)
        if not music_files_bucket.exists(os.path.basename(filename)):
            urllib.request.urlretrieve(self.thumbnail, filename)
        try:
            img = cv2.imread(filename)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        except cv2.error:
            return 0x000000
        reshape = img.reshape((img.shape[0] * img.shape[1], 3))
        cluster = KMeans(n_clusters=5).fit(reshape)
        centroids = cluster.cluster_centers_
        labels = np.arange(0, len(np.unique(cluster.labels_)) + 1)
        hist, _ = np.histogram(cluster.labels_, bins=labels)
        hist = hist.astype("float")
        hist /= hist.sum()
        colors = sorted([(percent, color) for (percent, color) in zip(hist, centroids)])
        color = int("0x" + '%02x%02x%02x' % tuple(int(c) for c in colors[len(colors) - 1][1]), base=16)
        dc_color = color
        return dc_color

    @staticmethod
    def search(query: str):
        s = pytube.Search(query)
        try:
            cr = s.completion_suggestions
        except:
            cr = []
        return s.results, cr

    @staticmethod
    def from_query(query: str, selector: int = 0):
        r, _ = Goblin.search(query)
        return Goblin(r[selector])

    @staticmethod
    def from_url(url: str):
        return Goblin(pytube.YouTube(url))

    async def get(self):
        data = ytdl.extract_info(self.url, download=False)
        if "entries" in data:
            # Takes the first item from a playlist
            data = data["entries"][0]
        url = data["url"]
        return wrap(url)

    # Fallback
    async def download(self):
        if os.path.exists(self.filename):
            return wrap(self.filename)
        video_info = yt_dlp.YoutubeDL().extract_info(
            url=self.url, download=False
        )
        options = {
            'format': 'bestaudio/best',
            'keepvideo': False,
            'outtmpl': self.filename,
        }
        with yt_dlp.YoutubeDL(options) as ydl:
            ydl.download([video_info['webpage_url']])

        return wrap(self.filename)


# BOJ:200_Data Strucuture1<Stack Algorithm>-#9093 단어뒤집기-p02
from collections import deque
n = int(input())

for _ in range(n):
    # input().split() returns list
    dq=deque((input().split()))
    # To pick the first word the first
    while dq:
        words = dq.popleft()
        # print the word out in backward
        for i in range(1,len(words)+1) :
            print(words[-i],end="")
        print(end=" ")
    print()


"""
    Policies for contextual bandit problems.

"""

import numpy as np
import tensorflow as tf
import contextlib
from termcolor import cprint

from rnlps.policies.base import Trial, Policy
from rnlps.policies.base import BaseOracle, BaseFixed, BaseRandom
from rnlps.policies.base import BaseThompsonRecurrentNetwork, BaseThompsonSinFeedforwardNetwork

@contextlib.contextmanager
def _printoptions(*args, **kwargs):
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    try:
        yield
    finally:
        np.set_printoptions(**original)

class Oracle(BaseOracle):
    pass

class Fixed(BaseFixed):
    pass

class Random(BaseRandom):
    pass

class ThompsonRecurrentNetwork(BaseThompsonRecurrentNetwork):
    """ Recurrent neural-linear: Thompson sampling based policy by using
        Bayesian linear regression on the representation(context) generated by
        the penultimate layer of the recurrent architecture. """

    def __init__(self, bandit, n_units, learning_rate, regularise_lambda, epochs, train_every,
                 std_targets, std_weights, verbose, seed):

        self.context_dims = bandit.context_dims

        BaseThompsonRecurrentNetwork.__init__(self, bandit, n_units,
        learning_rate, regularise_lambda, epochs, train_every, std_targets,
        std_weights, verbose, seed)

    def _setup_input(self):
        """ Returns the input and input size for reward prediction by the RNN. """

        self._arms = tf.placeholder(tf.int32, shape=None, name='arms')
        self._contexts = tf.placeholder(tf.float32, shape=[None, self.context_dims], name='contexts')

        rewards = tf.reshape(self._rewards[:-1], (-1, 1))
        # past rewards seen as features for prediction, first value is 0, last one can't be used as a feature for the next step

        arms_oh = tf.one_hot(self._arms, depth=self.bandit.n_arms,
                                dtype=tf.float32, name='arms_oh')

        contexts = self._contexts
        # Don't have a reward for the last context, ignore it while passing feed dict

        inputs = tf.concat([rewards, arms_oh, contexts], axis=1, name='inputs')
        isize = self.bandit.n_arms + 1 + self.context_dims

        return inputs, isize

    def _get_pred_from_sampled_model(self, trial, w, state):
        """ Obtains the predicted reward for every action under the sampled
        model(w). """

        pred = np.zeros(trial.n_arms)
        for arm in range(trial.n_arms):
            feed = {self._istate: state, self._arms: [arm],
                    self._rewards: [trial.rewards[-1], 0], self._contexts: [trial.contexts[-1]]}

            arm_features = self.session.run(self._h_output, feed)[0]
            pred[arm] = arm_features.dot(w)

        return pred

    def _get_feed_for_rnn(self, trial):
        """ Returns the input feed for the action selection by the policy. """

        feed = {self._arms: trial.arms, self._rewards: [0.] + trial.rewards, self._contexts: trial.contexts[:-1]}
        # Include contexts while dealing with contextual bandits

        return feed

class ThompsonSinFeedforwardNetwork(BaseThompsonSinFeedforwardNetwork):
    """ Neural-linear: Thompson sampling with Bayesian linear regression on
        the representation generated by a FFNN fed with handcrafted context and
         sinusoidal input units."""

    def __init__(self, bandit, order, periods, periods_dim, n_units,
                 learning_rate, regularise_lambda, epochs, train_every,
                 std_targets, std_weights, verbose, seed):

        self.context_dims = bandit.context_dims

        BaseThompsonSinFeedforwardNetwork.__init__(self, bandit, order, periods, periods_dim, n_units,
                     learning_rate, regularise_lambda, epochs, train_every,
                     std_targets, std_weights, verbose, seed)

        self._setup(seed)

    def _setup_input_size(self):
        """ Returns the number of units in the input layer, before and after
        including the sinusoidal units. """

        isize = len(self.periods)*2
        isize += self.bandit.n_arms + self.context_dims + (self.bandit.n_arms + self.context_dims+ 1) * self.order

        #add more units for the periodic transfromation
        isize_pre = isize + 1
        isize_post = isize + self.periods_dim

        return isize_pre, isize_post

    def _example(self, arms, rewards, contexts, t):
        """ Creates one sample of the handcrafted context-target pair. Used to
        generate the training data for training the NN representation model. """

        if t < self.order:
            raise Exception('Incomplete observation.')

        arms_oh = np.eye(self.bandit.n_arms)

        observation = []

        # Can be used for hard-coded periods
        for p in self.periods:
            angle = (2*np.pi*t)/p
            observation += [np.cos(angle), np.sin(angle)]

        observation.extend(arms_oh[arms[t]])

        observation.extend(contexts[t]) #Add the current context

        for i in range(self.order):
            observation.extend(arms_oh[arms[t - i - 1]])
            observation.append(rewards[t - i - 1])

            #Add the previous contexts
            observation.extend(contexts[t - i - 1])

        observation.append(t) #add the raw time-step as the new input
        target = rewards[t]

        return observation, target

contextual_policies = {'Oracle': Oracle,
            'Fixed': Fixed,
            'Random': Random,
            'ThompsonRecurrentNetwork': ThompsonRecurrentNetwork,
            'ThompsonSinFeedforwardNetwork': ThompsonSinFeedforwardNetwork}


import os
import numpy as np

project_path = "C:\\Users\\Night\\Documents\\Code\\Python\\npm\\popular"
project_dict = {}

folders = os.listdir(project_path)
length = len(folders)
now = -1
for folder in folders:
    now += 1
    project_dict[folder] = now

project_similarity = np.zeros((length, length))
class_path = "C:\\Users\\Night\\Documents\\Code\\Python\\npm_projects\\82-processed\\"
report_path = "C:\\Users\\Night\\Documents\\Code\\Python\\npm_projects\\diff\\"
folders = os.listdir(class_path)

popularity_report = "C:\\Users\\Night\\Documents\\Code\\Python\\npm_projects\\project_similarity\\" \
                    "file_popularity_report.txt"

output = open(popularity_report, 'w', encoding='UTF-8')
for folder in folders:
    folder_path = class_path + folder + "\\"
    if os.path.isdir(folder_path):
        report = report_path + folder + "_report.txt"
        f = open(report)
        lines = f.readlines()
        f.close()
        first_file = " "
        accum_similarity = 0
        max_accum_similarity = -1
        most_popular_file = " "
        for line in lines:
            if line.startswith("first file"):
                now_file = line.split("\\")[-1]
                if now_file != first_file:
                    if accum_similarity > max_accum_similarity:
                        max_accum_similarity = accum_similarity
                        most_popular_file = first_file
                    first_file = now_file
                    accum_similarity = 0
            elif line.startswith("overlap"):
                t = line.split(": ")[1]
                similarity = float(t)
                accum_similarity += similarity
        output.write(folder + "\n")
        output.write(most_popular_file + "\n")

output.close()


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

__version__ = 0.1

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

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

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

        # Destroy the window
        self.destroy()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

if __name__ == '__main__':

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

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

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


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

from user_payments.models import LineItem, Payment

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

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

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

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

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

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

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

        payment.cancel_pending()

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

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

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

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

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

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

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


from django import forms

from shop.models import Order

class ProductSearchForm(forms.Form):
    category = forms.CharField(
        max_length=100,
        required=False,
        label="",
        widget=forms.TextInput(attrs={"placeholder": "Search by category"})
    )

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ("username", "email")


from setuptools import setup, find_packages

with open('README.md', 'r') as f:
    long_desc = f.read()

setup(
    name = 'nft_sha_maker',
    version = '1.1',
    author = 'Samuel .O. Bamgbose',
    author_email = 'bsaintdesigns@gmail.com',
    description = ' A package that calculates the SHA256 from a CSV file',
    long_description = long_desc,
    long_description_content_type = 'text/markdown',
    py_modules = ['nft_sha_maker'],
    classifiers = [
        'Programming Language :: Python :: 3.10',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent'
    ],
    packages = find_packages(),
    python_requires = '>= 3.10',
    install_requires = [],
    entry_points = {
        'console_scripts' : [
            'nft_sha_maker = nft_sha_maker:__main__',
        ]
    }
)


from django.urls import path, include
from . import views
from django.conf import settings

urlpatterns = [
    path('', views.index, name='index'),
    path('userlist/', views.ListOfUsers, name='ListOfUsers'),
    path('login/', views.Login, name='Login'),
    path('createuser/', views.Create_User, name='Create_User'),
    path('totalblogs/', views.TotalBlogs, name='TotalBlogs'),
    path('createblogs/', views.Create_blogs, name='Create_blogs'),
    path('updateblogs/<int:id>/', views.Update_blogs, name='Update_blogs'),
    path('deleteblogs/<int:id>/', views.Delete_blogs, name='Delete_blogs'),
    path('getuser/', views.Get_user, name='Get_user'),

]


# type: ignore
import unittest
from fuse.utils.cpu_profiling import Profiler

class TestTimer(unittest.TestCase):
    def test_profiler_1(self) -> None:
        """ """
        from itertools import combinations

        def dummy_slow():
            N = 140  # 1000
            K = 2
            for _ in range(100):
                all_combs = combinations(range(N), K)
                all_combs = list(all_combs)
            return all_combs

        def dummy_quick():
            a = 1000
            a += 1
            return a

        def get_combs():
            for _ in range(10):
                x = dummy_slow()
                y = dummy_quick()

            return x, y

        with Profiler("banana"):
            get_combs()

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


# (c) Sandiway Fong, University of Arizona, 2022
from itertools import permutations
from nltk.tree import Tree
import sys
import re
from nltk.corpus import ptb

def dom(x, path):
    if path is None:
        path = list()
    yield x, path
    if not isinstance(x, str):
        path.append(x.label())
        for y in x:
            yield from dom(y, path.copy())

def cc(x):
    if not isinstance(x, str):
        if len(x) > 1:
            for y,z in permutations(x, 2):
                m1 = re.search(yregex, y.label())
                if m1:
                    for w, path in dom(z, None):
                        if isinstance(w, str):
                            m2 = re.search(wregex, w)
                        else:
                            m2 = re.search(wregex, w.label())
                        if m2:
                            print('tree',i+70000,':',y, 'c-commands', w, 'path', path)
            for u in x:
                cc(u)
        else:
            cc(x[0])

if len(sys.argv) == 2:
    with open(sys.argv[1]) as f:
        t  = Tree.fromstring(f.read())
        cc(t)


import tkinter as tk

class Menubar(tk.Menu):
    def __init__(self, mst):
        super().__init__()
        self['bg'] = 'gray30'
        self['fg'] = '#ffffff'
        self['font'] = 'Arial 10 bold'
        self.__create_optmenu(mst)
        mst.config(menu=self)

    def __create_optmenu(self, mst):
        optmenu = tk.Menu(self, tearoff=0, bg='gray30', fg='#ffffff', font='Arial 10 bold')
        optmenu.add_command(label='Help', command=self.help_screen)
        optmenu.add_separator()
        optmenu.add_command(label='Exit',command=mst.quit)
        self.add_cascade(label='Option', menu=optmenu)
    def help_screen(self):
    	help = tk.Toplevel()
    	help.title('Help')
    	help.resizable(False,False)
    	help.iconphoto(False, tk.PhotoImage(file='data/icon.png'))
    	img = tk.PhotoImage(file="data/help.png")
    	tab = tk.Label(help,image=img)
    	tab.img = img
    	tab.pack()
    	tk.Label(help,
    			text="Create by Lucas G. Meneses",
    			width=33).pack()
    	tk.Label(help,
    			text="Icons made by Smashicons\nfrom www.flaticon.com",
    			fg='#404040',
    			width=33).pack()


mon0825 = {
    "FOOTBALL_B": [24, "MAIN FIELD 1", "XX"],
    "FLOORBALL_B": [24, "ISH", "SH"],
    "TENNIS_B": [10, "TC", "GP"],
    "TENNIS_G": [8, "TC", "GP"],
    "BADMINTON_B": [10, "MPH", "IQ"],
    "BADMINTON_G": [10, "MPH", "IQ"],
    "HANDBALL_G": [22, "BBC", "YY"],
    "GROUP_EXERCISE_G": [17, "GYM / DANCE STUDIO", "CC"],
    "VOLLEYBALL_B": [12, "2CAG", "RT"],
    "VOLLEYBALL_G": [12, "2CAG", "RT"],
    "TABLE_TENNIS_B": [12, "AMPHI", "DK"],
    "TABLE_TENNIS_G": [11, "AMPHI", "DK"],
    "FRISBEE_G": [21, "HF", "CL"],
    "PICKLE_BALL_B": [10, "PS", "JT"],
    "PICKLE_BALL_G": [14, "PS", "JT"],
    "HANDBALL_B": [18, "GC", "JL"],
    "CHOICE_COUNT": [
        "Choice 1",
        "Choice 2",
        "Choice 3",
        "Choice 4",
        "Choice 5",
        "Choice 6",
        "Choice 7",
        "Choice 8",
    ],
}

mon0920 = {
    "TENNIS_B": [10, "TC", "VC"],
    "TENNIS_G": [10, "TC", "VC"],
    "HANDBALL_B": [22, "GC", "JL"],
    "BASKETBALL_B": [24, "BBC", "BF"],
    "LACROSSE_G": [24, "HF", "SK"],
    "PICKLE_BALL_B": [11, "PS", "JT"],
    "PICKLE_BALL_G": [9, "PS", "JT"],
    "TABLE_TENNIS_B": [14, "AMPHI", "CJ"],
    "TABLE_TENNIS_G": [11, "AMPHI", "CJ"],
    "FLOORBALL_G": [24, "ISH", "MO"],
    "VOLLEYBALL_B": [14, "2CAG", "MY"],
    "VOLLEYBALL_G": [12, "2CAG", "MY"],
    "GROUP_EXERCISE_G": [17, "GYM / DANCE STUDIO", "CC"],
    "FOOTBALL_B": [26, "MAIN FIELD 2", "SY"],
    "BADMINTON_B": [10, "MPH", "IQ"],
    "BADMINTON_G": [14, "MPH", "IQ"],
    "CHOICE_COUNT": [
        "Choice 1",
        "Choice 2",
        "Choice 3",
        "Choice 4",
        "Choice 5",
        "Choice 6",
        "Choice 7",
        "Choice 8",
    ],
}

mon1015 = {
    "LACROSSE_G": [22, "HF", "SK"],
    "HANDBALL_B": [16, "GC", "BF"],
    "TENNIS_B": [10, "TC", "SH"],
    "TENNIS_G": [10, "TC", "SH"],
    "PICKLE_BALL_B": [10, "2CAG", "MY"],
    "PICKLE_BALL_G": [14, "2CAG", "MY"],
    "FLOORBALL_B": [26, "ISH", "CL"],
    "CHOICE_COUNT": ["Choice 1", "Choice 2", "Choice 3", "Choice 4"],
}

tues0825 = {
    "FLOORBALL_B": [26, "ISH", "SH"],
    "HANDBALL_B": [26, "GC", "JL"],
    "TABLE_TENNIS_B": [16, "Amphi", "CL"],
    "TABLE_TENNIS_G": [10, "Amphi", "CL"],
    "FOOTBALL_B": [26, "HF", "BF"],
    "BADMINTON_B": [10, "MPH", "CC"],
    "BADMINTON_G": [12, "MPH", "CC"],
    "GROUP_EXERCISE_G": [16, "GYM / DANCE STUDIO", "JT"],
    "HANDBALL_G": [24, "BBC", "YY"],
    "VOLLEYBALL_B": [12, "2CAG", "RT"],
    "VOLLEYBALL_G": [12, "2CAG", "RT"],
    "TENNIS_B": [10, "TC", "VC"],
    "TENNIS_G": [10, "TC", "VC"],
    "FRISBEE_G": [26, "MAIN FIELD 1", "SY"],
    "STREET_NETBALL_G": [26, "STDM D", "DK"],
    "CHOICE_COUNT": [
        "Choice 1",
        "Choice 2",
        "Choice 3",
        "Choice 4",
        "Choice 5",
        "Choice 6",
        "Choice 7",
        "Choice 8",
    ],
}

tues0920 = {
    "TENNIS_B": [8, "TC", "VC"],
    "TENNIS_G": [12, "TC", "VC"],
    "FOOTBALL_B": [26, "MAIN FIELD 1", "XX"],
    "HOCKEY_B": [24, "HF", "GP"],
    "FRISBEE_B": [24, "MAIN FIELD 2", "SY"],
    "FLOORBALL_G": [24, "ISH", "SH"],
    "STREET_NETBALL_G": [22, "STDM D", "DK"],
    "TABLE_TENNIS_B": [12, "AMPHI", "BF"],
    "TABLE_TENNIS_G": [11, "AMPHI", "BF"],
    "BADMINTON_B": [12, "MPH", "CJ"],
    "BADMINTON_G": [12, "MPH", "CJ"],
    "VOLLEYBALL_B": [12, "2CAG", "RT"],
    "VOLLEYBALL_G": [10, "2CAG", "RT"],
    "HANDBALL_G": [23, "GC", "MY"],
    "GROUP_EXERCISE_G": [17, "GYM / DANCE STUDIO", "CC"],
    "TCHOUKBALL_G": [24, "PS", "SK"],
    "BASKETBALL_G": [24, "BBC", "IQ"],
    "CHOICE_COUNT": [
        "Choice 1",
        "Choice 2",
        "Choice 3",
        "Choice 4",
        "Choice 5",
        "Choice 6",
        "Choice 7",
        "Choice 8",
        "Choice 9",
        "Choice 10",
    ],
}

tues1015 = {
    "PICKLE_BALL_B": [10, "2CAG", "JT"],
    "PICKLE_BALL_G": [12, "2CAG", "JT"],
    "BADMINTON_B": [10, "MPH", "IQ"],
    "BADMINTON_G": [14, "MPH", "IQ"],
    "FIT_AND_FAB_G": [21, "GYM / DANCE STUDIO", "YY"],
    "FLOORBALL_B": [20, "ISH", "CL"],
    "TABLE_TENNIS_B": [8, "AMPHI", "JL"],
    "TABLE_TENNIS_G": [14, "AMPHI", "JL"],
    "CHOICE_COUNT": ["Choice 1", "Choice 2", "Choice 3", "Choice 4"],
}

thurs0825 = {
    "FLOORBALL_G": [26, "ISH", "SH"],
    "FOOTBALL_B": [24, "MAIN FIELD 1", "IQ"],
    "VOLLEYBALL_B": [13, "2CAG", "XX"],
    "VOLLEYBALL_G": [12, "2CAG", "XX"],
    "TENNIS_B": [8, "TC", "SY"],
    "TENNIS_G": [12, "TC", "SY"],
    "BASKETBALL_B": [26, "BBC", "BF"],
    "HANDBALL_G": [26, "GC", "JL"],
    "FRISBEE_G": [26, "MAIN FIELD 2", "YY"],
    "TABLE_TENNIS_B": [10, "AMPHI", "CJ"],
    "TABLE_TENNIS_G": [13, "AMPHI", "CJ"],
    "BADMINTON_B": [10, "MPH", "MY"],
    "BADMINTON_G": [14, "MPH", "MY"],
    "FRISBEE_B": [26, "HF", "GP"],
    "GROUP_EXERCISE_G": [17, "GYM / DANCE STUDIO", "CC"],
    "CHOICE_COUNT": [
        "Choice 1",
        "Choice 2",
        "Choice 3",
        "Choice 4",
        "Choice 5",
        "Choice 6",
        "Choice 7",
        "Choice 8",
    ],
}

thurs0920 = {
    "TOUCH_TAG_RUGBY_G": [24, "HF", "MO"],
    "TENNIS_B": [10, "TC", "VC"],
    "TENNIS_G": [10, "TC", "VC"],
    "FRISBEE_B": [22, "MAIN FIELD 1", "SK"],
    "VOLLEYBALL_B": [12, "2CAG", "CL"],
    "VOLLEYBALL_G": [12, "2CAG", "CL"],
    "FLOORBALL_G": [22, "ISH", "CC"],
    "BADMINTON_B": [10, "MPH", "MY"],
    "BADMINTON_G": [14, "MPH", "MY"],
    "TABLE_TENNIS_B": [10, "AMPHI", "DK"],
    "TABLE_TENNIS_G": [12, "AMPHI", "DK"],
    "PICKLE_BALL_B": [12, "BBC", "JT"],
    "PICKLE_BALL_G": [12, "BBC", "JT"],
    "HANDBALL_B": [16, "GC", "SH"],
    "CHOICE_COUNT": [
        "Choice 1",
        "Choice 2",
        "Choice 3",
        "Choice 4",
        "Choice 5",
        "Choice 6",
        "Choice 7",
    ],
}

fri0825 = {
    "FRISBEE_G": [26, "MAIN FIELD 3", "CC"],
    "BADMINTON_G": [24, "MPH", "CJ"],
    "BASKETBALL_G": [24, "BBC", "YY"],
    "STREET_NETBALL_G": [24, "STDM D", "RT"],
    "FOOTBALL_B": [22, "MAIN FIELD 1", "IQ"],
    "TOUCH_TAG_RUGBY_G": [26, "MAIN FIELD 2", "MO"],
    "FRISBEE_B": [24, "HF", "GP"],
    "FLOORBALL_B": [22, "ISH", "CL"],
    "TENNIS_B": [18, "TC", "SY"],
    "TABLE_TENNIS_B": [12, "AMPHI", "VC"],
    "TABLE_TENNIS_G": [10, "AMPHI", "VC"],
    "PICKLE_BALL_B": [8, "Parade Square", "JT"],
    "PICKLE_BALL_G": [15, "Parade Square", "JT"],
    "HANDBALL_B": [22, "GC", "SH"],
    "CHOICE_COUNT": [
        "Choice 1",
        "Choice 2",
        "Choice 3",
        "Choice 4",
        "Choice 5",
        "Choice 6",
        "Choice 7",
    ],
}

fri0920 = {
    "STREET_NETBALL_G": [20, "Stadium D", "DK"],
    "HANDBALL_G": [24, "BBC", "SH"],
    "TENNIS_B": [10, "TC", "BF"],
    "TENNIS_G": [10, "TC", "BF"],
    "FOOTBALL_B": [20, "Main Field 1", "XX"],
    "TOUCH_TAG_RUGBY_G": [24, "Main Field 2", "YY"],
    "HANDBALL_B": [18, "GC", "JL"],
    "BADMINTON_B": [11, "MPH", "MY"],
    "BADMINTON_G": [12, "MPH", "MY"],
    "LACROSSE_G": [23, "HF", "SK"],
    "CHOICE_COUNT": [
        "Choice 1",
        "Choice 2",
        "Choice 3",
        "Choice 4",
        "Choice 5",
        "Choice 6",
    ],
}

fri1015 = {
    "STREET_NETBALL_G": [22, "Stadium D", "RT"],
    "FRISBEE_B": [15, "Main Field 2", "CJ"],
    "FRISBEE_G": [11, "Main Field 2", "CJ"],
    "FOOTBALL_B": [26, "Main Field 1", "XX"],
    "TENNIS_B": [14, "TC", "IQ"],
    "TENNIS_G": [6, "TC", "IQ"],
    "HOCKEY_B": [20, "HF", "GP"],
    "GROUP_EXERCISE_G": [17, "GYM / DANCE STUDIO", "JT"],
    "CHOICE_COUNT": ["Choice 1", "Choice 2", "Choice 3", "Choice 4"],
}


# pip install selenium
# wget `curl -s https://api.github.com/repos/mozilla/geckodriver/releases/latest | grep browser_download_url | grep linux64 | cut -d '"' -f 4`
# export PATH="$PATH:/path/to/geckodriver/folder"
import json
from time import sleep
import os
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait

def create_virtual_display() -> Display:
    vdisplay = Display(visible=True, size=(1024, 768))
    vdisplay.start()
    return vdisplay

def create_browser() -> WebDriver:
    return webdriver.Firefox(executable_path="/home/soft/selenium_driver/geckodriver")

if __name__ == "__main__":
    vdisplay = create_virtual_display()
    driver = create_browser()
    waiter: WebDriverWait = WebDriverWait(driver, 30)

    output_file_cookie = os.environ.get("COOKIE_FILE")

    with open(output_file_cookie, "r") as cookie_file:
        cookies: dict = json.load(cookie_file)
    driver.get("https://www.xing.com")
    for each_cookie in cookies:
        driver.delete_cookie(each_cookie["name"])
        driver.add_cookie(each_cookie)

    url = 'https://www.xing.com/m/J9pTX3JeBaLh37FOtDRagG'
    page = driver.get(url)

    sleep(2)

    # waiter.until(expected_conditions.text_to_be_present_in_element((By.CSS_SELECTOR, "some_id"),"expected text"))
    # driver.delete_all_cookies()
    # driver.refresh()
    # driver.close()
    vdisplay.stop()


a, b = map(str, input().split())  # adaabc aababbc

result=[]
for i in range(len(b) - len(a) + 1): # 두 문자열 길이의 차이만큼 반복
    cnt=0

    for j in range(len(a)): # 반복문을 통해 b의 인덱스를 +i 해주면서 a의 문자열과 비교
        if a[j] != b[i+j]: # 다른 문자열이면 카운트
            cnt+=1

    result.append(cnt) # [3, 2]

print(min(result))


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

import torch.nn as nn

from src import frontends

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.sig = nn.Sigmoid()

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

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

        x = nn.MaxPool2d(2)(x)

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

        x = nn.MaxPool2d(2)(x)

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

        x = nn.MaxPool2d(2)(x)

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

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

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

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

        self.device = kwargs['device']

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

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

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

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

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

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


class Person(object):
    __slots__ = ('_name', '_age', '_gender')

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

    @property
    def name(self):
        return self._name

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, age):
        self._age = age

    def play(self):
        if self.age <= 16:
            print('%s在玩飞行棋.' % self._name)
        else:
            print('%s在玩斗地主.' % self._name)

def main():
    p1 = Person('jack', 12)
    p1.play()
    p1.age = 19
    p1.play()

    person = Person('王大锤', 22)
    person.play()
    person._gender = '男'
    person._is_gay = True

if __name__ == '__main__':
    main()


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

post_routes = Blueprint('posts', __name__)

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

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

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

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

    return {'Posts': all_posts}

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

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

    all_post = followed_posts

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

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

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

    return {'Posts': all_post}

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

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

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

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

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

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

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

    post = Post.query.get(post_id)

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

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

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

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

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

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

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


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

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

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

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

print(cnt)

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


# Taking input from the user for lower limit of the range.
lower=int(input("Enter the lower limit for the range: "))

# Taking input from the user for the uper limit of the range.
upper=int(input("Enter the upper limit for the range: "))

# Setting the range using For loop.
for i in range(lower,upper+1):
    # using if condition.
    if(i%2!=0):
        # using print statement to print the values.
        print(i)


# -*- coding: utf-8 -*-
"""
Created on Sun Mar  3 12:06:01 2019

@author: Tomas
"""

import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams.update({'font.size': 14})

df = pd.read_excel('C:/Users/Public/data/indexes_commodities_fitted.xlsx')
df2 = pd.read_excel('C:/Users/Public/data/fx_120mins_best_fit.xlsx')

a= df['profit'].cumsum()*100
b= df2['profit'].cumsum()*100

df['profit'] = df['profit'] +1
df2['profit']= df2['profit'] +1

#a = df['profit'].cumprod()*100 - 100
#b = df2['profit'].cumprod()*100 - 100

plt.figure(figsize=(13,9))
plt.title('Counter-Trader Returns Backtest [2018 Coinshares Internship]')
plt.plot(a,label='Indexes')
plt.plot(b,label='FX')
plt.xlabel('# trades [summer 2018]')
plt.ylabel('% returns [exluding fees]')
plt.legend()
plt.show()


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

# Create your views here.

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

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

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

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

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

	mehedi.save()

	return render(request, 'sindex.html')

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

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

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

	mehedi_customer.save()     #saving data in db

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

	return render(request, 'msp.html')


#!/usr/bin/python3
def check_types(err, type_list, *argv):
    ''' if none throws a different err msg, do a separate none check '''
    for i in argv:
        if i is None:
            raise TypeError(err)
        t = type(i)
        if t not in type_list:
            raise TypeError(err)
    return (True)

def print_square(size):
    ''' prints a square '''
    check_types("size must be an integer", [int], size)
    if size < 0:
        raise ValueError("size must be >= 0")
    for row in range(size):
        for col in range(size):
            print('#', end='')
        print('')


import pandas as pd
import numpy as np

data = {
   'Nome' : ['Alice', 'Jorge', 'Isabella'],
   'Idade' : [35, 25, 23]
}

df = pd.DataFrame(data)
print(df.describe().round(2).to_string()) #Retorna as principais medidas arredondadas

sd = pd.Series(data = [5.50, 7.56, 8.50], index = ['seg', 'terc', 'quar'])
print(sd.describe())

s = pd.Series(np.random.randint(0, 25, 7))
print(s)

series = pd.Series(data = [451, 627, 292, 95],
                   index = ['Fundamental completo',
                'Médio completo', 'Superior completo', 'Pós-graduação completa'])

print(series['Superior completo' : ].sum()) #REtorna a quantidade de pessoas com curso superior pra cima

series2 = pd.Series(data = [68, 93, 22, 0],
                   index = ['Fundamental completo',
                'Médio completo', 'Superior completo', 'Pós-graduação completa'])

serieResultante = series + series2
print(serieResultante.sum()) #Retorna a nova quantidade de inscritos

s = pd.Series(data = [2, 7, 5, 10, 6], index = ['Wilfred Abbie Harry Julia Carrie'.split()])
print (s[s> s.mean()].index)     #Nome dos alunos que tiraram notas acima da média


#KNN Algorithm
##############

import pandas as pd
import numpy as np

x1 = [5.3, 5.1, 7.2, 5.4, 5.1, 5.4, 7.4, 6.1, 7.3, 6.0, 5.8, 6.3, 5.1, 6.3, 5.5]
x2 = [3.7, 3.8, 3.0, 3.4, 3.3, 3.9, 2.8, 2.8, 2.9, 2.7, 2.8, 2.3, 2.5, 2.5, 2.4]
cls = ['Setosa', 'Verscicolor', 'Virginica', 'Setosa', 'Verscicolor', 'Setosa', 'Virginica', 'Verscicolor', 'Virginica', 'Verscicolor', 'Virginica', 'Setosa', 'Verscicolor', ' Virginica', 'Verscicolor']

#taking input from user
y1 = float(input("Enter the first point: "))
y2 = float(input("Enter the second point: "))

#finding distance from user input data and given x1 & x2 data & converting list into dataframe
d = []
for i in range(len(x1)):
           d.append((((y2 - y1)**2) + ((x2[i] - x1[i])**2))**0.5)
#print(d)
sr = pd.Series(x1)
sr1 = pd.Series(x2)
sr2 = pd.Series(d)
sr3 = pd.Series(cls)
d_set = {'X1':sr, 'X2':sr1, "Distance":sr2, "Class":sr3,}
d_set1 = pd.concat(d_set, axis = 1)
print("\nAfter finding distance from the above two points the table will be:\n")
print(d_set1)
print("--------------------------------------------------------------------------")

#printing dataframe in sorted manner
dset = {'X1':sr, 'X2':sr1, "Distance":sr2, "Class":sr3,}
dset1 = pd.concat(dset, axis=1)
dset2 = dset1.sort_values(by = ["Distance"])
print("\nAfter sorting the table will be:\n")
print(dset2)
print("--------------------------------------------------------------------------")

#assuming k value and finding the frequency of classes
k = int(input("Enter the k value:"))
CLS = []
for i in dset2.loc[:,"Class"]:
    CLS.append(i)
#print(CLS)
CLS1 = CLS[:k]
#print(CLS1)

#finding frequency of classes
n, n1, n2, = 0, 0, 0
for i in CLS1:
    if i == "Setosa":
        n += 1
    elif i== "Verscicolor":
        n1 += 1
    elif i== "Virginica":
        n2 += 1
    else:
        exit()
#print(n,n1,n2)
if (n != n1) and (n != n2):
    if (n > n1) and (n > n2):
        print("The nearest neighbour class is Setosa")
    elif (n1 > n) and (n1 > n2):
        print("The nearest neighbour class is Verscicolor")
    else:
        print("The nearest neighbour is Virginica")
elif (n == n1) or (n == n2):
    print("Neighbour classes having  same frequecy")
    if (n == n1):
        print("The nearest neighbour classes are Setosa and Verscicolor")
    elif (n1 == n2):
        print("The nearest neighbour classes are Verscicolor and Virginica")
    elif (n == n2):
        print("The nearest neighbour classes are Setosa and Virginica")
    else:
        print("Invalid input")
else:
    print("Invalid input")


from django.contrib import admin
from .models import Hireyoutuber
# Register your models here.

class HireyoutuberAdmin(admin.ModelAdmin):
    list_display = ['youtuber_name','first_name','email']
    list_display_links = ['youtuber_name']
    list_filter = ['youtuber_name']
admin.site.register(Hireyoutuber,HireyoutuberAdmin)


import os
import sys
import reframe as rfm
import reframe.utility.sanity as sn
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
                '../common')))  # noqa: E402
import sphexa.sanity as sphs
import sphexa.sanity_scorep as sphsscorep

# NOTE: jenkins restricted to 1 cnode
# NOTE: 3 steps minimum to avoid "delay timeout" error + cubeside >= 40
mpi_tasks = [2]
cubeside_dict = {2: 80, 20: 172}
steps_dict = {2: 3, 20: 3}
# cycles_dict = {2: 5000000}

# {{{ SphExaScorepCudaCheck
@rfm.parameterized_test(*[[mpi_task] for mpi_task in mpi_tasks])
class SphExaScorepCudaCheck(rfm.RegressionTest):
    # {{{
    '''
    This class runs the test code with Score-P (mpi+cuda):

    3 parameters can be set for simulation:

    :arg mpi_task: number of mpi tasks; the size of the cube in the 3D
         square patch test is set with a dictionary depending on mpitask,
         but cubesize could also be on the list of parameters,
    :arg steps: number of simulation steps.
    :arg cycles: sampling sources generate interrupts that trigger a sample.
         SCOREP_SAMPLING_EVENTS sets the sampling source:
         see $EBROOTSCOREMINP/share/doc/scorep/html/sampling.html .
         Very large values will produce unreliable performance report,
         very small values will have a large runtime overhead.
    '''
    # }}}

    def __init__(self, mpi_task):
        # {{{ pe
        self.descr = 'Tool validation'
        self.valid_prog_environs = ['PrgEnv-gnu']
        # self.valid_systems = ['daint:gpu', 'dom:gpu']
        self.valid_systems = ['*']
        self.maintainers = ['JG']
        self.tags = {'sph', 'hpctools', 'gpu'}
        # }}}

        # {{{ compile
        self.testname = 'sqpatch'
        self.tool = 'scorep'
        self.prebuild_cmds = ['module rm xalt', 'module list -t']
        tool_ver = '6.0'
        tc_ver = '20.08'
        self.tool_modules = {
            'PrgEnv-gnu': [f'Score-P/{tool_ver}-CrayGNU-{tc_ver}-cuda'],
        }
        self.build_system = 'Make'
        self.build_system.makefile = 'Makefile'
        self.build_system.nvcc = 'nvcc'
        self.build_system.cxx = 'CC'
        self.build_system.max_concurrency = 2
        self.sourcepath = f'{self.testname}.cpp'
        self.executable = f'./{self.testname}.exe'
        self.target_executable = 'mpi+omp+cuda'
        self.build_system.cxx = 'scorep --mpp=mpi --cuda --nocompiler CC'
        self.build_system.nvcc = 'scorep --cuda --nocompiler nvcc'
        self.build_system.options = [
            self.target_executable, f'MPICXX="{self.build_system.cxx}"',
            'SRCDIR=.', 'BUILDDIR=.', 'BINDIR=.', 'CXXFLAGS=-std=c++14',
            'CUDA_PATH=$CUDATOOLKIT_HOME',
            # The makefile adds -DUSE_MPI
        ]
        self.postbuild_cmds = [f'mv {self.target_executable}.app '
                               f'{self.executable}']
        # }}}

        # {{{ run
        ompthread = 1
        self.num_tasks = mpi_task
        self.cubeside = cubeside_dict[mpi_task]
        self.steps = steps_dict[mpi_task]
        # cycles = cycles_dict[mpi_task]
        self.name = \
            'sphexa_scorep+cuda_{}_{:03d}mpi_{:03d}omp_{}n_{}steps'. \
            format(self.testname, mpi_task, ompthread, self.cubeside,
                   self.steps)
        self.num_tasks_per_node = 1
        self.num_cpus_per_task = ompthread
        self.num_tasks_per_core = 1
        self.use_multithreading = False
        self.exclusive = True
        self.time_limit = '10m'
        self.variables = {
            'CRAYPE_LINK_TYPE': 'dynamic',
            'OMP_NUM_THREADS': str(self.num_cpus_per_task),
            'SCOREP_ENABLE_PROFILING': 'false',
            'SCOREP_ENABLE_TRACING': 'true',
            'SCOREP_CUDA_ENABLE': 'yes',
            'SCOREP_ENABLE_UNWINDING': 'true',
            # 'SCOREP_SAMPLING_EVENTS': 'perf_cycles@%s' % cycles,
            # 'SCOREP_SAMPLING_EVENTS': 'PAPI_TOT_CYC@1000000',
            # 'SCOREP_SAMPLING_EVENTS': 'PAPI_TOT_CYC@%s' % cycles,
            # export SCOREP_SAMPLING_EVENTS=PAPI_TOT_CYC@1000000
            # empty SCOREP_SAMPLING_EVENTS will profile mpi calls only:
            # ok: 'SCOREP_SAMPLING_EVENTS': '',
            # 'SCOREP_METRIC_PAPI': 'PAPI_TOT_INS,PAPI_TOT_CYC',
            # 'SCOREP_METRIC_RUSAGE': 'ru_maxrss',
            # 'SCOREP_TIMER': 'clock_gettime',
            # 'SCOREP_PROFILING_MAX_CALLPATH_DEPTH': '1',
            # 'SCOREP_VERBOSE': 'true',
            # 'SCOREP_TOTAL_MEMORY': '1G',
        }
        self.version_rpt = 'version.rpt'
        self.which_rpt = 'which.rpt'
        self.info_rpt = 'info.rpt'
        self.executable_opts = [
            f'-n {self.cubeside}', f'-s {self.steps}', '2>&1']
        self.prerun_cmds = [
            'module rm xalt',
            f'{self.tool} --version &> {self.version_rpt}',
            f'which {self.tool} &> {self.which_rpt}',
            'scorep-info config-summary &> %s' % self.info_rpt,
        ]
        # }}}

        # {{{ sanity
        self.sanity_patterns = sn.all([
            # check the job output:
            sn.assert_found(r'Total time for iteration\(0\)', self.stdout),
            # check the tool's version and configuration:
            sn.assert_true(sphsscorep.scorep_version(self)),
            sn.assert_true(sphsscorep.scorep_info_papi_support(self)),
            sn.assert_true(sphsscorep.scorep_info_perf_support(self)),
            sn.assert_true(sphsscorep.scorep_info_unwinding_support(self)),
            sn.assert_true(sphsscorep.scorep_info_cuda_support(self)),
        ])
        # }}}

        # {{{ performance
        # {{{ internal timers
        self.prerun_cmds += ['echo starttime=`date +%s`']
        self.postrun_cmds += ['echo stoptime=`date +%s`']
        # }}}

        # {{{ perf_patterns:
        basic_perf_patterns = sn.evaluate(sphs.basic_perf_patterns(self))
        self.perf_patterns = {**basic_perf_patterns}
        # }}}

        # {{{ reference:
        self.reference = sn.evaluate(sphs.basic_reference_scoped_d(self))
        # }}}
        # }}}

    # {{{ hooks
    @rfm.run_before('compile')
    def set_compiler_flags(self):
        self.modules += self.tool_modules[self.current_environ.name]
    # }}}


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

from td_lambda.q_learning import plot_cost_to_go, plot_running_avg

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if done:
            reward = -200

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

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

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

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

    return iters, totalreward

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

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

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

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

    plot_running_avg(totalrewards)


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

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

        return path(0,0)

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


"""
Given: Two DNA strings s and t (each of length at most 1 kbp).
Return: All locations of t as a substring of s.
"""

def find_motif_in_dna(data):
    strands = data.split()
    base = strands[0]
    sub = strands[1]

    locations = [i + 1 for i in range(0, len(base)) if sub == base[i:i + len(sub)]]

    return str(locations)


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

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

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

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

data_theta = []
data_phi = []

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

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

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

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

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

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

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

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

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

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

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

theta_diff_fig.show(renderer="browser")

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

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

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

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

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

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

phi_diff_fig.show(renderer="browser")


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

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

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

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

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

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

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

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

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

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


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 12:33:08 2020

@author: danbiderman
from terminal, run
python3 split_images.py --dataset_path="../../Video_Datasets/Sawtell-data"

assuming that a path to a folder is given.
and that within that folder, we have a config json file and a raw_images folder
"""

from pathlib import Path
import os
import cv2
import re
from tqdm import tqdm
import argparse
import json
import commentjson

parser = argparse.ArgumentParser()
parser.add_argument("--dataset_path", default=None, help="str with folder path")
args, _ = parser.parse_known_args()

def sorted_nicely(l):
    """ Sort the given iterable in the way that humans expect."""
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)", key)]
    return sorted(l, key=alphanum_key)

def split_images(
    raw_images, height_lims, width_lims, is_path=False, write_path=None,
):
    assert write_path is not None
    write_path = Path(write_path).resolve()
    write_path.mkdir(exist_ok=True, parents=True)

    views = len(width_lims)
    images_split = []
    path_images = []

    for v in range(views):
        view_dir = write_path / f"view_{v}"
        view_dir.mkdir(exist_ok=True, parents=True)

        images_split.append([])
        path_images.append([])

        for idx, i in tqdm(enumerate(raw_images)):
            if is_path:
                if "png" not in i or "jpg" not in i:
                    continue
                img = cv2.imread(os.path.join(raw_img_path, i), 0)
            else:
                img = i
            view_img = img[
                height_lims[v][0] : height_lims[v][1],
                width_lims[v][0] : width_lims[v][1],
            ]
            cv2.imwrite(str(view_dir / f"{idx}.png"), view_img)
            path_images[v].append(str(view_dir / f"{idx}.png"))
            images_split[v].append(view_img)

    return images_split, path_images

if __name__ == "__main__":
    dataset_path = Path(args.dataset_path).resolve()
    raw_img_path = os.path.join(dataset_path, "frames")  # was previously 'raw_images'

    config = commentjson.load(
        open(os.path.join(dataset_path, "image_settings.json"), "r")
    )

    height_lims = config["height_lims"]
    width_lims = config["width_lims"]
    views = len(width_lims)

    images = os.listdir(raw_img_path)
    if ".DS_Store" in images:
        images.remove(".DS_Store")
    images = sorted_nicely(images)
    split_images(images, height_lims, width_lims, False, write_images=True)