# Imports
import sys
import discord
from discord.ext import commands
from discord.utils import get
from random import shuffle
from youtube_search import YoutubeSearch
import pytube
import pafy
import youtube_dl
import time
from io import StringIO
import asyncio
from contextlib import redirect_stderr, redirect_stdout
from math import floor

# FFmpeg options that it will reconnect if timeout
ffmpeg_options = {
    'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
    'options': '-vn'
}

# YoutubeDL options
ydl_opts = {'format': 'bestaudio'}

# A small function which convert seconds to a time format
def timeconvert(sec:int):
    hour = floor(sec / 3600)
    if hour <= 9:
        hour = "0" + str(hour)
    hour = str(hour)
    min = floor(floor(sec % 3600) / 60)
    if min <= 9:
        min = "0" + str(min)
    min = str(min)
    sec = sec % 3600 % 60
    if sec <= 9:
        sec = "0" + str(sec)
    sec = str(sec)
    return str(hour + ":" + min + ":" + sec) # Return a string

# Next function which will be done when the music ends
def next(vc,guild,bot):
    if len(bot.playlist[guild.id]["queue"]) <= bot.playlist[guild.id]["order"]: # If it reach the end of the queue
        if bot.playlist[guild.id]["loop"]: # If loop is true
            bot.playlist[guild.id]["order"] = 0 # Back to the first track
        else: # If not looping
            bot.playlist[guild] = {"order" : 0, "np" : "", "queue" : [], "loop": False, "startime": None} # Reset the playlist
            return # Terminate the whole thing
    voice = get(vc, guild=guild) # Get the voice channel the user is in
    output = StringIO() # Prepare to resirect output
    err = StringIO()
    with redirect_stdout(output):
        with redirect_stderr(output): # Redirect output to output variable
            with youtube_dl.YoutubeDL(ydl_opts) as ydl: # Open YoutubeDL as ydl
                # Download the bytes of the song
                info = ydl.extract_info(bot.playlist[guild.id]["queue"][bot.playlist[guild.id]["order"]], download=False)
    # Get the time tick when music start
    bot.playlist[guild.id]["startime"] = floor(time.time())
    # Play the audio using FFmpeg
    with redirect_stderr(err):
        with redirect_stdout(output):
            voice.play(discord.FFmpegPCMAudio(info["url"],**ffmpeg_options), after=lambda e:next(vc, guild, bot))
    # Set now playing to the currently playing song
    bot.playlist[guild.id]["np"] = bot.playlist[guild.id]["queue"][bot.playlist[guild.id]["order"]]
    bot.playlist[guild.id]["order"] = bot.playlist[guild.id]["order"] + 1 # Order += 1

# A new class called sigma is ready to be imported as a cog
class sigma(commands.Cog): # Show that it is a discord cog object
    def __init__(self, bot): # Import the bot
        self.bot = bot # self.bot = bot
    # Join a voice channel ($join)
    @commands.guild_only()
    @commands.command(aliases=["connect"])
    async def join(self, ctx):
        await ctx.author.voice.channel.connect() # Connect to the voice channel where the user is
        # Set up a playlist object
        self.bot.playlist[ctx.guild.id] = {"order" : 0, "np" : "", "queue" : [], "loop": False, "startime": None}
        await ctx.message.add_reaction("☑") # React if success
    # Leave a voice channel ($leave)
    @commands.guild_only()
    @commands.command(aliases=["dc","disconnect","disco"])
    async def leave(self, ctx):
        await ctx.voice_client.disconnect() # Disconnect from the voice channel
        # Reset a playlist object
        self.bot.playlist[ctx.guild.id] = {"order" : 0, "np" : "", "queue" : [], "loop": False, "startime": None}
        await ctx.message.add_reaction("☑") # React if success
    # Loop the queue ($loopqueue)
    @commands.guild_only()
    @commands.command(aliases=["lq", "loop"])
    async def loopqueue(self, ctx):
        if self.bot.playlist[ctx.guild.id]["loop"]: # If loop is true
            self.bot.playlist[ctx.guild.id]["loop"] = False # loop = false
        else: # If not loop is true
            self.bot.playlist[ctx.guild.id]["loop"] = True # loop = true
        await ctx.message.add_reaction("🔁") # React if success
    # Show the queue ($queue)
    @commands.guild_only()
    @commands.command(aliases=["q"])
    async def queue(self, ctx, page = "NG"):
        if not len(self.bot.playlist[ctx.guild.id]["queue"]) == 0: # If the length of the queue is not 0
            try: # Try to do
                order1 = int(page) # If page value is valid
                order1 = order1 * 10 # Set the page value
            except: # If the page value is not valid
                # Set the page to where the track playing now is
                order1 = floor(int(self.bot.playlist[ctx.guild.id]["order"] - 1) / 10) * 10 + 10
            E = self.bot.playlist[ctx.guild.id]["queue"][int(order1 - 10):int(order1)] # Get the list of the range of the page
            con = "" # Declare a string object
            ro = order1 - 10
            for link in E: # List out all the links
                # Append the title and the duration together
                if ro == self.bot.playlist[ctx.guild.id]["order"] - 1:
                    con = con + "= " + str(ro) + ". " + self.bot.songdes[link]["title"] + " - " + timeconvert(floor(time.time() - self.bot.playlist[ctx.guild.id]["startime"])) + "/" + timeconvert(self.bot.songdes[link]["duration"]) + "\n"
                elif ro > self.bot.playlist[ctx.guild.id]["order"] - 1:
                    con = con + "* " + str(ro) + ". " + self.bot.songdes[link]["title"] + " - " + timeconvert(self.bot.songdes[link]["duration"]) + "\n"
                else:
                    con = con + "- " + str(ro) + ". " + self.bot.songdes[link]["title"] + " - " + timeconvert(self.bot.songdes[link]["duration"]) + "\n"
                ro = ro + 1
            # Add some decoration
            con = "\n[ Queue ]\n" + con + ""
        else: # If the length of the queue is 0
            con = "" # Needed cuz needed
            order1 = 10 # Needed cuz needed
        duration = 0 # Declare an integer
        for dir in self.bot.playlist[ctx.guild.id]["queue"]: # Get the whole duration of the playlist
            duration = int(duration) + int(floor(self.bot.songdes[dir]["duration"]))
        # Append the values together
        await ctx.send("```asciidoc\n" + con + "\nTotal duration: " + timeconvert(duration) + "\n" + "current page:" + str(order1 / 10) +"\nPosition:" + str(self.bot.playlist[ctx.guild.id]["order"] - 1) + "/" + str(len(self.bot.playlist[ctx.guild.id]["queue"])) + "\nloop:" + str(self.bot.playlist[ctx.guild.id]["loop"]) + "```")
    # Shuffle the queue ($shuffle)
    @commands.guild_only()
    @commands.command()
    async def shuffle(self, ctx):
        # Get the unplayed part of the queue
        cp = self.bot.playlist[ctx.guild.id]["queue"][int(self.bot.playlist[ctx.guild.id]["order"]):]
        shuffle(cp) # Shuffle the unplayed part of the queue
        # Append them together again
        self.bot.playlist[ctx.guild.id]["queue"][int(self.bot.playlist[ctx.guild.id]["order"]):] = cp
        await ctx.message.add_reaction("🔀") # React when succeed
    # Play a youtube audio or a playlist ($play <url>)
    @commands.guild_only()
    @commands.command()
    async def play(self, ctx, *,url:str):
        try: # Try to connect to the voice channel where the user is
            await ctx.author.voice.channel.connect()
            # Reset the playlist
            self.bot.playlist[ctx.guild.id] = {"order" : 0, "np" : "", "queue" : [], "loop": False, "startime": None}
        except: pass
        # If not connected in a voice channel
        if not get(ctx.bot.voice_clients, guild=ctx.guild).is_connected():
            raise Exception("Not connected to a voice channel") # Raise exception
        msg = await ctx.send(embed=discord.Embed( # Create a temperatory added embed
            title="Processing, please wait."
        ))
        try:
            plist = pytube.Playlist(url) # Get the playlist of the url
            timez = 0 # Declare an integer to count
        except:
            vid = pytube.YouTube(url) # Get the video of the url
            self.bot.playlist[ctx.guild.id]["queue"].append(url) # Append the url into the queue
            vid = pafy.new(url)
            self.bot.songdes[url] = {"title" : vid.title, "duration": int(vid.duration), "thumb": vid.thumb} # Get the title and the duration of the track
            voice_client = ctx.message.guild.voice_client # Get the voice client
            if not voice_client.is_playing() and not voice_client.is_paused(): # If the bot isn't playing anything
                next(self.bot.voice_clients, ctx.guild, self.bot) # Toggle the next function to start play music
            embed = discord.Embed( # Make the embed object
                title="Added track into queue",
                color=discord.Color.gold(),
                description="Added `" + vid.title + "` Into queue." # Tell user that the process is completed
            )
            # Set the thumbnail to the avatar of the video
            embed.set_thumbnail(url=vid.thumb)
        else:
            for URL in plist: # List all the link in the playlist
                vid = pafy.new(URL) # Get the video object
                self.bot.songdes[URL] = {"title" : vid.title, "duration": int(vid.length), "thumb": vid.thumb} # Get the title and the duration of the track
                self.bot.playlist[ctx.guild.id]["queue"].append(URL) # Append the links into the queue
                await msg.edit(embed=discord.Embed( # Edit the embed to prevent timeout error
                    title="Procesing, please wait.\nDownloaded:" + str(timez) # (And force it to response to commands)
                ))

                if not ctx.message.guild.voice_client.is_playing() and not ctx.message.guild.voice_client.is_paused(): # If the bot isn't playing anything
                    next(self.bot.voice_clients, ctx.guild, self.bot) # Toggle the next function to start play music
                timez = timez + 1 # timez =+ 1
            embed = discord.Embed( # Create an embed object
                title="Added playlist into queue",
                color=discord.Color.gold(), # Tell user that the process is completed
                description="Added " + str(len(plist)) + " tracks into queue\nName of playlist: `" + plist.title + "`"
            )
            # Set the thumbnail to the avatar of the first video
            embed.set_thumbnail(url=self.bot.songdes[self.bot.playlist[ctx.guild.id]["queue"][0]]["thumb"])
        await msg.edit(embed=embed) # Export the embed table
        await ctx.message.add_reaction("☑") # React if success
    # Show what is playing now ($nowplaying)
    @commands.guild_only()
    @commands.command(aliases=["np","nowplay","playingnow"])
    async def nowplaying(self, ctx):
        voice_client = ctx.message.guild.voice_client # Get the voice client
        if not voice_client.is_playing() and not voice_client.is_paused():
            raise Exception("Nothing playing now.")
        try: # Try to get the video url and youtube video object
            url = self.bot.playlist[ctx.guild.id]["queue"][self.bot.playlist[ctx.guild.id]["order"] - 1]
            des = self.bot.songdes[url]
            thumb = des["thumb"]
        except: # If it cannot
            raise Exception("The bot is not playing anything at the moment.") # Raise error
        ctime = floor(time.time()) # Get current time tick
        etime = floor(ctime - self.bot.playlist[ctx.guild.id]["startime"]) # Get the eliapsed time
        try:
            etime = floor(self.bot.playlist[ctx.guild.id]["pausetime"] - self.bot.playlist[ctx.guild.id]["startime"])
        except: pass
        barnum = int(round((etime / des["duration"]) * 40)) # Get the percentage
        i = 0 # Declare an integer
        bar = "" # Declare a string
        while i != 40: # Run for 41 times to get the progress bar
            if barnum < i:
                bar = bar + "-"
            elif barnum > i:
                bar = bar + "="
            else:
                bar = bar + ">"
            i = i + 1
        embed = discord.Embed( # Make an embed object
            title="Now Playing",
            color=discord.Color.gold(),
            description="[**" + des["title"] + "**](" + url + ")\n" + timeconvert(etime) + " / " + timeconvert(des["duration"]) + "\n`" + bar + "`"
        )
        # Set thumbnail to the avatar of the video
        embed.set_thumbnail(url=thumb)
        await ctx.send(embed = embed) # Export the embed object
    # Search for songs($search <arguments>)
    @commands.guild_only()
    @commands.command()
    async def search(self, ctx, *, stuffs: str):
        try: # Try to do
            await ctx.author.voice.channel.connect() # Connect to the voice channel where the user is
            # Reset the playlist
            self.bot.playlist[ctx.guild.id] = {"order" : 0, "np" : "", "queue" : [], "loop": False, "startime": None}
        except: pass
        # If not connected to voice channel
        if not get(ctx.bot.voice_clients, guild=ctx.guild).is_connected():
            raise Exception("Not connected to a voice channel") # Raise exception
        def check(m): # Define the check function
            return m.author == ctx.message.author
        result = YoutubeSearch(stuffs,max_results=10).to_dict() # Search the stuffs and export the results to dictionary
        con = "" # Declare a string
        i = 0 # Declare an integer
        for res in result: # List all the result
            con = con + str(i) + ". `" + str(res["title"]) + "` - " + str(res["duration"]) + "\n\n" # Append the results
            i = i + 1 # Count + 1
        embed = discord.Embed( # Create an embed object
            title="Search results of " + stuffs,
            url="http://tntprizz.zapto.org/dc",
            description=con,
            color=discord.Color.blue()
        )
        await ctx.send(embed=embed) # Export the embed object
        await ctx.send("Please select your option.") # Prompt user to insert an integer
        try: # Try to get the message
            resp = await self.bot.wait_for('message', check=check, timeout=20)
            opt = int(resp.content) # Get the number user seleted
        except TimeoutError: # If user cannot insert the number on time
            raise Exception("You cannot insert an integer within 20 seconds! Cancel operation") # Raise exception
        except ValueError: # If user don't insert an integer
            raise ValueError("This is not an integer! Cancel operation") # Raise exception
        if opt >= 10: # If option is larger than 9
            raise ValueError("You should insert an integer within 0 to 9! Cancel operation") # Raise exception
        url = "https://www.youtube.com/" + result[opt]["url_suffix"] # Get the video url
        vid = pafy.new(url) # Get the video object
        self.bot.songdes[url] = {"title" : vid.title, "duration": int(vid.length), "thumb": vid.thumb} # Get the title and the duration of the track
        self.bot.playlist[ctx.guild.id]["queue"].append(URL) # Append the links into the queue
        embed = discord.Embed( # Make an embed object
            title="Added track into queue",
            color=discord.Color.gold(),
            description="Added " + vid.title + " Into queue."
        )
        embed.set_thumbnail(url=vid.thumb) # Set thumbnail to video thumbnail
        voice_client = ctx.message.guild.voice_client # Get the voice client object
        if not voice_client.is_playing() and not voice_client.is_paused(): # If the voice client isn't playing
            next(self.bot.voice_clients, ctx.guild, self.bot) # Start playing song
        await ctx.send(embed=embed) # Export the embed object
        await ctx.message.add_reaction("☑") # React if success
    # Remove the track using the number of the song ($rmtrack <tracknum>)
    @commands.guild_only()
    @commands.command(aliases = ["rm", "deltrack"])
    async def rmtrack(self, ctx, tracknum : int):
        if tracknum < 0 or tracknum > len(self.bot.playlist[ctx.guild.id]["queue"]): # Check if the number inserted is valid
            raise Exception("Invalid track number") # Raise exception
        # Check if the tracknum is before the order or after the order
        if self.bot.playlist[ctx.guild.id]["order"] - 1 == tracknum:
            ctx.message.guild.voice_client.stop()
        if self.bot.playlist[ctx.guild.id]["order"] - 1 < tracknum:
            del self.bot.playlist[ctx.guild.id]["queue"][tracknum] # Delete the track
        else:
            self.bot.playlist[ctx.guild.id]["order"] = self.bot.playlist[ctx.guild.id]["order"] - 1 # Set order to -1
            del self.bot.playlist[ctx.guild.id]["queue"][tracknum] # Only delete the track
        await ctx.message.add_reaction("☑") # React if success
    # Skip to track ($skiptotrack <tracknum>)
    @commands.guild_only()
    @commands.command(aliases=["gototrack","jumptotrack","stt"])
    async def skiptotrack(self, ctx, tracknum: int):
        if tracknum < 0 or tracknum > len(self.bot.playlist[ctx.guild.id]["queue"]): # Check if the number inserted is valid
            raise Exception("Invalid track number") # Raise exception
        self.bot.playlist[ctx.guild.id]["order"] = tracknum # Set order to tracknum
        ctx.message.guild.voice_client.stop() # Stop the track to execute the next function
        await ctx.message.add_reaction("☑") # React if success
    # Pause the currently playing track ($pause)
    @commands.guild_only()
    @commands.command()
    async def pause(self, ctx):
        voice_client = ctx.message.guild.voice_client # Get the voice client
        self.bot.playlist[ctx.guild.id]["pausetime"] = time.time() # Get the time tick when the track paused
        voice_client.pause() # Pause the music
        await ctx.message.add_reaction("⏸") # React if success
    # Resume the paused track ($resume)
    @commands.guild_only()
    @commands.command()
    async def resume(self, ctx):
        voice_client = ctx.message.guild.voice_client # Get the voice client
        # Correcting the $nowplaying elipsed time
        self.bot.playlist[ctx.guild.id]["startime"] = self.bot.playlist[ctx.guild.id]["startime"] + (floor(time.time()) - floor(self.bot.playlist[ctx.guild.id]["pausetime"]))
        del self.bot.playlist[ctx.guild.id]["pausetime"] # Delete the time tick when the track paused
        voice_client.resume() # Resume the music
        await ctx.message.add_reaction("▶") # React if success
    # Stop the whole playlist ($stop)
    @commands.guild_only()
    @commands.command(aliases=["clear","cq"])
    async def stop(self, ctx):
        self.bot.playlist[ctx.guild.id] = {"order":0, "queue":[], "loop":False, "np":""} # Reset the playlist dictionary
        voice_client = ctx.message.guild.voice_client # Get the voice client
        voice_client.stop() # Stop the music
        await ctx.message.add_reaction("⏹") # React if success
    # Go to the last track(s) ($last [tracks])
    @commands.guild_only()
    @commands.command(aliases=["back"])
    async def last(self, ctx, tracks: int = 1):
        voice_client = ctx.message.guild.voice_client # Get the voice client
        if self.bot.playlist[ctx.guild.id]["order"] - tracks - 1 < 0: # If the order become smaller than 0
            raise IndexError("Cannot accept order value smaller than 0") # Raise exception
        # Set order to the modified order
        self.bot.playlist[ctx.guild.id]["order"] = self.bot.playlist[ctx.guild.id]["order"] - tracks - 1
        voice_client.stop() # Stop the player to let it execute the next function
        await ctx.message.add_reaction("⏮") # React if success
    # Skip the track(s) ($skip [tracks])
    @commands.guild_only()
    @commands.command(aliases=["next"])
    async def skip(self, ctx, tracks: int = 1):
        voice_client = ctx.message.guild.voice_client # Get the voice client
        # If the order become larger then the length of the queue
        if self.bot.playlist[ctx.guild.id]["order"] + tracks - 1 == len(self.bot.playlist[ctx.guild.id]["queue"]):
            raise IndexError("Cannot accept order value bigger than the length of the queue") # Raise exception
        # Set order to the modified order
        self.bot.playlist[ctx.guild.id]["order"] = self.bot.playlist[ctx.guild.id]["order"] + tracks - 1
        voice_client.stop() # Stop the player to let it execute the next function
        await ctx.message.add_reaction("⏭") # React if success

def setup(bot):
    bot.cmdlist["sigma"] = { # Import the manual list
        "intro": "Music player version 2",
        "join": "`join`\nConnect to the music channel the author is in\nAliases: `connect`",
        "leave": "`leave`\nDisconnect from the music channel\nAliases: `dc` `disco` `disconnect`",
        "loopqueue": "`loopqueue`\nToggle the loop boolean which will loop the queue\nAliases: `lq`",
        "shuffle": "`shuffle`\nShuffle the queue",
        "play": "`play <Youtube URL>`\nPlay the Youtube audio",
        "queue": "`queue [page]`\nShow out the queue\nAliases: `q`",
        "nowplaying": "`nowplaying`\nShow the currently playing track\nAliases: `np` `playingnow` `nowplay`",
        "search": "`search <args>`\nSearch the arguments from youtube and play the seleted audio",
        "pause": "`pause`\nPause the current track",
        "resume": "`resume`\nResume the paused track",
        "stop": "`stop`\nStop playing the whole queue\nAliases: `clear` `cq`",
        "skip": "`skip [tracks]`\nSkip the track(s)\nAliases: `next`",
        "last": "`last [tracks]`\nGo backward for a number of track(s)\nAliases: `back`",
        "rmtrack": "`rmtrack <tracknum>`\nRemove the track using the number\nAliases: `rm` `deltrack`",
        "skiptotrack": "`skiptotrack <tracknum>`\nSkip to the track using the number\nAliases: `gototrack` `jumptotrack` `stt`"
        }
    bot.add_cog(sigma(bot)) # Add cog into the bot


def scrape_fun(search_item):
    from bs4 import BeautifulSoup
    import requests
    name=search_item
    dicti={}
    req=requests.get('https://en.wikipedia.org/w/index.php?search=History+of+{}&title=Special%3ASearch&fulltext=1&ns0=1'.format(name))

    soup=BeautifulSoup(req.content,features="html.parser")

    all_results=soup.find_all("ul",{"class":"mw-search-results"})
    for val in all_results:
        a=val.find_all("a")
        for link in a:
            title=link['title']
            lin=link['href']
            dicti.__setitem__(title,lin)

    return dicti

def detailInfo(link):
    list_text=[]
    from bs4 import BeautifulSoup
    import requests

    url_link=(f"https://en.wikipedia.org{link}")

    request_agn=requests.get(url_link)
    soup2=BeautifulSoup(request_agn.content,features="html.parser")
    x=soup2.find_all("div",{"class":"mw-parser-output"})
    sel=soup2.select("p:nth-child(6)")
    if sel:
        for i in sel:
            first_para=i.text
            list_text.append(first_para)
    else:
        sel=soup2.select("p")

        for i in sel:
            first_para=i.text
            list_text.append(first_para)

    return list_text


import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
import pandas as pd
from torch.utils.data import Dataset,DataLoader
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

use_cuda = torch.cuda.is_available()
dataDir = "D:/TAU/EX1/EX1/Q2"
input_csv_dir = dataDir + "/iris.data.csv"

#hyperparameters
batch_size = 5
lr = 0.0002
num_epoch = 500

def parse_iris_input(data_dir):
    # read and pharse input data
    data = pd.read_csv(data_dir, names=['f1', 'f2', 'f3', 'f4', 'species'])
    # change string value to numeric
    data.loc[data['species'] == 'Iris-setosa', 'species'] = 0
    data.loc[data['species'] == 'Iris-versicolor', 'species'] = 1
    data.loc[data['species'] == 'Iris-virginica', 'species'] = 2
    data = data.apply(pd.to_numeric)
    return data
    f.close()

class IrisNetDataSet(Dataset):
    def __init__(self, x, y):
        self.len = x.shape[0]
        self.x_data = torch.Tensor(x).float()
        self.y_data = torch.Tensor(y).long()

    def __getitem__(self, index):
        return self.x_data[index,:], self.y_data[index]

    def __len__(self):
        return len(self.x_data)

class IrisNet(nn.Module):
    def __init__(self):
        super(IrisNet, self).__init__()
        self.fc1 = nn.Linear(4, 10)
        self.fc2 = nn.Linear(10, 3)

    def forward(self, x):
        x = self.fc1(x)
        x = self.requ(x)
        x = self.fc2(x)
        return x

    @staticmethod
    def requ(x):
        x = F.relu(x)
        x_2 = torch.mul(x, x)
        return x_2

def main():
    # read data and build
    data = parse_iris_input(input_csv_dir)
    # split to train and test
    X_train, X_test, y_train, y_test = train_test_split(data[data.columns[0:4]].values,
                                                        data.species.values, test_size=0.3)

    # split test to test and validation
    X_test, X_val, y_test, y_val = train_test_split(X_test,
                                                    y_test, test_size=0.5)
    X_test = Variable(torch.Tensor(X_test).float())
    X_val = Variable(torch.Tensor(X_val).float())
    y_test = Variable(torch.Tensor(y_test).long())
    y_val = Variable(torch.Tensor(y_val).long())

    if use_cuda:
        X_test = X_test.cuda()
        X_val = X_val.cuda()
        y_test = y_test.cuda()
        y_val = y_val.cuda()

    # build data loader
    dataSetTrain = IrisNetDataSet(X_train,y_train)
    train_loader = DataLoader(dataset=dataSetTrain, batch_size=batch_size, shuffle=True)

    # build net
    net = IrisNet()
    if use_cuda:
        net = net.cuda()
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(net.parameters(), lr)

    # train
    train_losses = []
    validation_losses=[]
    fig = plt.figure()
    for ep_n,epoch in enumerate(range(num_epoch)):
        epoch_train_loss = 0
        epoch_counter = 0
        for data in train_loader:
            optimizer.zero_grad()
            input, target = data
            input, target = Variable(input), Variable(target)
            if use_cuda:
                input = input.cuda()
                target = target.cuda()
            out = net(input)
            loss = criterion(out,target)
            epoch_counter += 1
            epoch_train_loss += loss
            loss.backward()
            optimizer.step()
        epoch_train_loss = epoch_train_loss.data.cpu().numpy()/epoch_counter
        train_losses.append(epoch_train_loss)
        # evaluate on validation set
        loss_validation = criterion(net(X_val),y_val)
        validation_losses.append(loss_validation.data.cpu().numpy())
        print('ephoch: %d loss: %f' %(ep_n,loss_validation.data.cpu().numpy()))

        plt.plot(train_losses,color= 'b')
        plt.plot(validation_losses, color='r')
        plt.xlabel('epoch', fontsize=16)
        plt.ylabel('loss', fontsize=16)
        plt.title('Training on Iris Data set')
        plt.legend(['training loss','validation loss'])
        plt.pause(0.01)

    # get prediction
    out = net(X_test)
    _, predicted = torch.max(out.data.cpu(), 1)
    # get accuration
    test_loss = criterion(out, y_test)
    print('test lost %f ' % test_loss)
    print('Accuracy of the network %d %%' % (100 * torch.sum(y_test.data.cpu() == predicted) / len(y_test)))
    fig.savefig('Q2_results.png')

main()


# Create a program that receives two strings on a single line separated by a single space.
# Then, it prints the sum of their multiplied character codes as follows: multiply str1[0] with str2[0] and add the
# result to the total sum, then continue with the next two characters.
# If one of the strings is longer than the other, add the remaining character codes to the total sum without multiplication.

first_string, second_string = input().split()

total_sum = 0

if len(first_string) > len(second_string):
    for index in range(len(second_string)):
        total_sum += ord(first_string[index]) * ord(second_string[index])

    for i in range(len(second_string), len(first_string)):
        total_sum += ord(first_string[i])

elif len(second_string) > len(first_string):
    for index in range(len(first_string)):
        total_sum += ord(second_string[index]) * ord(first_string[index])

    for i in range(len(first_string), len(second_string)):
        total_sum += ord(second_string[i])

else:
    for index in range(len(first_string)):
        total_sum += ord(second_string[index]) * ord(first_string[index])

print(total_sum)


from runner import Runner
from memory_manager_simulator import MemoryManagerSimulator
import unittest
from unittest.mock import patch

class TestRunner(unittest.TestCase):
    def test_constructor(self):
        simulator = MemoryManagerSimulator()
        runner = Runner(simulator)
        self.assertEqual(runner.simulator, simulator)

    def test_run(self):
        with patch('memory_manager_simulator.MemoryManagerSimulator') as mock:
            mocked_simulator = mock.return_value

            runner = Runner(mocked_simulator)

            runner.run("RESERVAR a b")
            mocked_simulator.reserve.assert_called_with(["a", "b"])

            runner.run("ASIGNAR c a")
            mocked_simulator.assign.assert_called_with(["c", "a"])

            runner.run("LIBERAR a")
            mocked_simulator.free.assert_called_with(["a"])

            runner.run("IMPRIMIR a")
            mocked_simulator.print.assert_called_with(["a"])

            self.assertEqual(runner.run(""), "unknown action: ")

            mocked_simulator.reserve.side_effect = Exception("reserve exception")
            self.assertEqual(runner.run("RESERVAR a b"), "reserve exception")

            with self.assertRaises(SystemExit, msg="should quit"):
                runner.run("SALIR")


import pygame
import random
import time

pygame.init()

height = 600
width = 800

clock = pygame.time.Clock()

y = -20
ly = 0.1

side = 20

gameDisplay = pygame.display.set_mode((width,height))
clock = pygame.time.Clock()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
blue = (0,0, 125)
green = (0,255,0)
brown = (255,183,25)
lred = (255,153,153)

a = (255,255,102)
b = (0,204,204)

held  = 0

img = pygame.image.load('back.png')
img2 = pygame.image.load('blue_block.png')
img3 = pygame.image.load('red_block.png')
img4 = pygame.image.load('flames.png')
img5 = pygame.image.load('gameover.png')
img6 = pygame.image.load('main.gif')

color =  brown
color1 = lred
color2 = green

radius1  = 70
radius2 = 40

font = pygame.font.SysFont(None,25)
font1 = pygame.font.SysFont(None,50)
font2 = pygame.font.SysFont(None,30)
sound=pygame.mixer.music.load("music.mp3")

def textobjects(text,color):
    textSurface = font.render(text, True, color)
    return textSurface
def message(msg,color,ydisplace):
    textSurf = textobjects(msg,color)
    textRect = textSurf.get_rect()
    textRect.center = (width/2),(height/2)+ydisplace
    gameDisplay.blit(textSurf, textRect)
def message1(msg,color,center):
    screen_text = font2.render(msg,True,color)
    gameDisplay.blit(screen_text,center)

gameExit = False
i = random.randrange(1,3)
def score(sc):
    text = font.render("score:"+str(sc),True,red)
    gameDisplay.blit(text,[0,5])
def score1(sc):
    text = font1.render("score:"+str(sc),True,red)
    gameDisplay.blit(text,[350,10])
def mes():
    text = font.render("press escape to pause",True,white)
    gameDisplay.blit(text,[0,20])

def game_intro():
    intro = True
    while intro:
        for event in pygame.event.get():

            x,y = pygame.mouse.get_pos()
            c = pygame.mouse.get_pressed()
            if (x >=330 and x <= 470) and (y>=430 and y <=570):
                color1 = red
                radius1 = 85
                if c[0]==1:
                    intro=False
                    return 1
            else:
                color1 = lred
                radius1 = 70
            if x >= 560 and x<= 640 and y >= 460 and y <= 540:

                color2 = green
                radius2 = 50
                if c[0]==1:
                    return 0
            else:
                color2 = b
                radius2 = 60

        gameDisplay.blit(img6,[0,0])
        pygame.draw.circle(gameDisplay,color2,[400,500],radius1,0)
        pygame.draw.circle(gameDisplay,color1,[600,500],radius2,0)

        message1("PLAY",blue,[380,500])
        message1("EXIT",blue,[580,500])

        pygame.display.update()
        clock.tick(15)

def gameover():
    game = True
    while game:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p:
                    return(1)
                if event.key == pygame.K_q:
                    return(0)
        gameDisplay.blit(img5,[0,0])
        score1(sc)
        pygame.display.update()
        clock.tick(15)

def pause():
    paused=True
    while paused == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_e:
                    paused = False
                if event.key == pygame.K_q:
                    gameover()

        message("PAUSED",white,-100)
        message("press E to continue or Q to quit",white,20)
        pygame.display.update()
        clock.tick(5)

sc = 0
pygame.mixer.music.play(-1)
def gameloop(ly,sc):
    i = random.randrange(1,3)
    gameExit = False

    k = random.randrange(1,4)
    if k == 1:
        randx = 384
        y = 70
    elif k == 2:
        randx = 150
        y = 90
    else:
        randx = 600
        y = 100

    side = 40

    held  = 0

    xp = randx
    yp =y

    while not gameExit:

            for event in pygame.event.get():
                    if event.type == pygame.QUIT:

                            gameExit = True
                            pygame.quit()
                            quit()

                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            pause()

                    xa,ya = pygame.mouse.get_pos()

                    b = pygame.mouse.get_pressed()
                    if xa > xp and xa < xp+40:
                            if ya > yp and ya < yp+40:
                                    if b[0] == 1 and event.type == pygame.MOUSEBUTTONDOWN:
                                            held = 1
                    if event.type == pygame.MOUSEBUTTONUP:
                            held = 0
                    if held == 1:
                            xp,yp = pygame.mouse.get_pos()

            if xp > -100 and xp < 60 and yp > 150 and yp < 350 and i%2 != 0:
                            xp = -1000

            elif xp > 740 and yp > 200 and yp < 350 and i%2 == 0:
                            xp = -1000

            if xp > -10 and yp >= 540:

                    gameExit = True
            if xp < 0:
                sc = sc + 1
                break

            if xp > 0 and xp < 60 and yp > 200 and yp < 350 and i%2 == 0:
                            gameExit = True

            if xp > 740 and yp > 200 and yp < 350 and i%2 != 0:
                            gameExit = True

            yp+=ly

            gameDisplay.blit(img,[0,0])
            gameDisplay.blit(img4,[0,450])
            gameDisplay.blit(img3,[xp,yp])
            if i%2 == 0:

                    gameDisplay.blit(img2,[xp,yp])

            score(sc)
            mes()
            pygame.display.update()

    if gameExit == True:
        return(0)
    else:
        return(1)

j = game_intro()
while i < 20 and j == 1:
    j=gameloop(i,sc)
    if j == 0:
        j = gameover()
        i = 0.9
        sc = 0
    else:
        sc = sc + 1
    i = i + 0.8

pygame.quit()
quit()


import logging
from collections import defaultdict
from decimal import Decimal

from src.api.base_service import BaseService
from src.api.transactions.repository import TransactionRepository
from src.core.db.models import OperationType
from src.domain.dto import AssetBalanceDTO, TransactionAssetDTO

logger = logging.getLogger(__name__)

class TransactionService(BaseService):
    def __init__(self):
        super().__init__()
        self.repository = TransactionRepository()

    def fill_transaction_log(
        self, assets: list[TransactionAssetDTO], user, operation_type: OperationType
    ):
        self.repository.fill_transaction_log_by_assets(
            user=user,
            assets=assets,
            operation_type=operation_type,
        )

    def get_assets_balance_from_transactions(self) -> list[AssetBalanceDTO]:
        logs = self.repository.get_transactions_by_user(self.repository.current_user)

        records = []
        ticker_to_total_balance = defaultdict(Decimal)

        for log in logs:
            if log.operation_type == OperationType.buy:
                ticker_to_total_balance[log.asset.ticker] += log.value
            else:
                ticker_to_total_balance[log.asset.ticker] -= log.value

        for ticker in ticker_to_total_balance:
            total = ticker_to_total_balance[ticker]
            records.append(AssetBalanceDTO(ticker=ticker, total=total))

        return records


import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main1():
    #create_task : 函数用来并发运行作为 asyncio 任务 的多个协程。
    task1 = asyncio.create_task(say_after(3, 'hello'))
    task2 = asyncio.create_task(say_after(2, 'world'))
    print(f"started at {time.strftime('%X')}")

    await task1
    await task2
    #await say_after(1, 'hello')

    print(f"finished at {time.strftime('%X')}")

'''
    可等待 对象有三种主要类型: 协程, 任务 和 Future.

'''
async def nested():
    return 42

async def main2():
    '''
            Python 协程属于 可等待 对象，因此可以在其他协程中被等待:
    :return:
    '''
    print(await nested())  # will print "42".

async def main3():
    '''
        任务 被用来设置日程以便 并发 执行协程:
            当一个协程通过 asyncio.create_task() 等函数被打包为一个 任务，该协程将自动排入日程准备立即运行
    :return:
    '''
    task = asyncio.create_task(nested())
    print(await task)

async def main4():
    '''
        Future 是一种特殊的 低层级 可等待对象，表示一个异步操作的 最终结果。
        当一个 Future 对象 被等待，这意味着协程将保持等待直到该 Future 对象在其他地方操作完毕。
        在 asyncio 中需要 Future 对象以便允许通过 async/await 使用基于回调的代码。
        通常情况下 没有必要 在应用层级的代码中创建 Future 对象。
        Future 对象有时会由库和某些 asyncio API 暴露给用户，用作可等待对象:
    :return:
    '''
    pass

async def main5():
    '''
    创建任务:
        asyncio.create_task(coro, *, name=None)
        将 coro 协程 打包为一个 Task 排入日程准备执行。返回 Task 对象。
        name 不为 None，它将使用 Task.set_name() 来设为任务的名称。
        该任务会在 get_running_loop() 返回的循环中执行，如果当前线程没有在运行的循环则会引发 RuntimeError。
        此函数 在 Python 3.7 中被加入。在 Python 3.7 之前，可以改用低层级的 asyncio.ensure_future() 函数。
    :return:
    '''
    pass

async def display_date():
    '''
    coroutine asyncio.sleep(delay, result=None, *, loop=None)
        阻塞 delay 指定的秒数。
        如果指定了 result，则当协程完成时将其返回给调用者。
        sleep() 总是会挂起当前任务，以允许其他任务运行。
        Deprecated since version 3.8, will be removed in version 3.10: loop 形参。
        以下协程示例运行 5 秒，每秒显示一次当前日期:
    :return:
    '''
    import datetime
    loop = asyncio.get_running_loop()
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

'''
    并发运行任务
'''
async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({i})...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")

async def main6():
    '''
    awaitable asyncio.gather(*aws, loop=None, return_exceptions=False)
        并发 运行 aws 序列中的 可等待对象。
        如果 aws 中的某个可等待对象为协程，它将自动作为一个任务加入日程。
        如果所有可等待对象都成功完成，结果将是一个由所有返回值聚合而成的列表。结果值的顺序
            与 aws 中可等待对象的顺序一致。
        如果 return_exceptions 为 False (默认)，所引发的首个异常会立即传播给等待 gather()
            的任务。aws 序列中的其他可等待对象 不会被取消 并将继续运行。
        如果 return_exceptions 为 True，异常会和成功的结果一样处理，并聚合至结果列表。
        如果 gather() 被取消，所有被提交 (尚未完成) 的可等待对象也会 被取消。
        如果 aws 序列中的任一 Task 或 Future 对象 被取消，它将被当作引发了 CancelledError 一
            样处理 -- 在此情况下 gather() 调用 不会 被取消。这是为了防止一个已提交的
            Task/Future 被取消导致其他 Tasks/Future 也被取消
            :return:
    '''
    await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )

'''超时'''
async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main7():
    '''
    coroutine asyncio.wait_for(aw, timeout, *, loop=None)
        等待 aw 可等待对象 完成，指定 timeout 秒数后超时。
        如果 aw 是一个协程，它将自动作为任务加入日程。
        timeout 可以为 None，也可以为 float 或 int 型数值表示的等待秒数。如果 timeout 为 None，则等待直到完成。
        如果发生超时，任务将取消并引发 asyncio.TimeoutError.
        要避免任务 取消，可以加上 shield()。
        函数将等待直到目标对象确实被取消，所以总等待时间可能超过 timeout 指定的秒数。
        如果等待被取消，则 aw 指定的对象也会被取消。
    :return:
    '''
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except asyncio.TimeoutError:
        print('timeout!')

'''来自其他线程的日程安排'''

if __name__ == '__main__':
    asyncio.run(main7())


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone
from django.utils.timezone import utc
import datetime

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Event',
            fields=[
                ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)),
                ('title', models.CharField(max_length=200)),
                ('weekly_meeting', models.BooleanField(default=True)),
                ('activities', models.TextField(blank=True)),
                ('start', models.DateTimeField(blank=True, default=django.utils.timezone.now)),
                ('end', models.DateTimeField(blank=True, default=datetime.datetime(2015, 9, 2, 23, 26, 46, 835310, tzinfo=utc))),
                ('uod_cadets', models.CharField(max_length=2, choices=[('PT', 'PT'), ('BD', 'BDU'), ('CA', 'Class A'), ('CB', 'Class B'), ('CC', 'Class C')], default='BD')),
                ('uod_staff', models.CharField(max_length=2, choices=[('PT', 'PT'), ('BD', 'BDU'), ('CA', 'Class A'), ('CB', 'Class B'), ('CC', 'Class C')], default='BD')),
                ('uod_senior', models.CharField(max_length=2, choices=[('PT', 'PT'), ('BD', 'BDU'), ('CA', 'Class A'), ('CB', 'Class B'), ('CC', 'Class C')], default='BD')),
            ],
        ),
    ]


#!/usr/bin/python

xpos = 0
zpos = 0
count = 0
tracker = 0
#pathtodata="./ny30/ny3409_DTM_1M.asc"
pathtodata="SU31.asc"
outfile = "lake_map.obj"

####File stuff

datafile = open(pathtodata)
outfile = open(outfile, 'w')
########set obj file header

outfile.write("#OBJ file create by ASCii grid to obj convertor\n")
outfile.write("#\n")
outfile.write("g map\n\n\n")

########

while datafile.readline():
        count += 1 # count > 6
        if count > 6 and count <=1006: #1000x1000 Ascii Grid data.
                temp=[]
                blarg = datafile.readline()
                temp = blarg.split()
                for num in range (0, len(temp)):
                #for num in range (0, 100):
                        tracker+=1
                #        xpos = xpos + 1
                        pointheight = 80 - float(temp[num])
                        vector = "v " + ' ' +  str(num) + ' ' + str(pointheight) + ' ' + str(xpos)
                        outfile.write(vector + '\n')
                        if count <= 504 and num < 999 and num > 2:
                                fthing = "f " + str(tracker) + ' ' + str(tracker + 1) + ' ' + str(tracker - 1) + ' ' + str(tracker + 998) + ' ' + str(tracker + 999) + ' ' + str(tracker + 1000) + ' ' + str(tracker + 1001)
                                outfile.write(fthing + '\n')
                #xpos = 0

        print (xpos)

        xpos += 1

datafile.close()
outfile.close()


import pymysql
import time
import Adafruit_ADS1x15
import random
#import testrelay

def mapping(val, valmin, valmax, newvalmin, newvalmax):
    return (val-valmin) * (newvalmax - newvalmin) / (valmax - valmin) + newvalmin

adc = Adafruit_ADS1x15.ADS1115()
arrayLength = 100
phArray = [0.0] * arrayLength
index = 0

ecArray = [0.0] * arrayLength

phValue = 0.0
ecValue = 0.0
compensation = 1
GAIN = 1

while True:
    phArray[index] = adc.read_adc(1, gain = GAIN)
    ecArray[index] = adc.read_adc(0, gain = GAIN)
    #print("pre")
    #print(phArray[index])
    phArray[index] = mapping(phArray[index], 0, 32767, 0, 4096)
    ecArray[index] = mapping(ecArray[index], 0, 32767, 0, 4096)
    #print("post")
    #print(phArray[index])
    index += 1
    if index == arrayLength:
        index = 0

        voltagePH = (sum(phArray)/arrayLength)/1000
        phValue = 3.5 * voltagePH

        voltageEC = (sum(ecArray)/arrayLength)
        #print("voltage")
        #print(voltagePH)
        #print("coefficient")
        coefficientVol = float(voltageEC/1.0)
        #print(coefficientVol)
        if coefficientVol < 150:
            #no solution
            print("no solution")
        elif coefficientVol > 3300:
            #out of range
            print("out of range")
        elif coefficientVol <= 448 and coefficientVol > 150:
            ecValue = 6.84 * coefficientVol - 64.32
        elif coefficientVol <= 1457 and coefficientVol > 448:
            ecValue = 6.98 * coefficientVol - 127
        else:
            ecValue = 5.3 * coefficientVol + 2278
        #ecValue /= 1000
        ecValue = ecValue / compensation / 1000.0
        print("ph = %.2f" % phValue)
        print("ec = %.2f" % ecValue)
        '''
while True:
    phStr = (6.3 + random.uniform(0.0,0.4) -0.2)#str(round(phValue,2))
    ecStr = (1.4 + random.uniform(0.0,0.4) -0.2)##str(round(ecValue,2))

    phStr = "%.2f"%phStr
    ecStr = "%.2f"%ecStr
        #print(phStr)
    db = pymysql.connect("localhost","root","009564","Status" )
    cursor = db.cursor()

    sql = "UPDATE ecphCurrent SET ec = " + ecStr + ", ph = " + phStr + ", time = NOW() WHERE ID > 0"

    try:
       cursor.execute(sql)
       db.commit()
       print("finish")
    except:
        db.rollback()
        print("fail")

    db.close()

        #history db
    hdb = pymysql.connect("localhost","root","009564","Status" )
    cursor2 = hdb.cursor()
    sql = "INSERT INTO ecphHistory (id, time, ec, ph) VALUES (NULL, CURRENT_TIMESTAMP, "+ ecStr +", "+ phStr +")"
    try:
       cursor2.execute(sql)
       hdb.commit()
    #   print("finish2")

    except:
        hdb.rollback()
        #print("fail2")

    hdb.close()
        '''


"""
In a two-dimensional array (the length of each one-dimensional array is
the same), each row is sorted in ascending order from left to right, and
each column is sorted in ascending order from top to bottom. Please
complete a function, enter a two-dimensional array and an integer to
determine whether the array contains the integer.
"""

# 整体思路
# 1.题意是在一个二维数组中寻找一个target,然而该二维数组有个特点，行列都是依次递增
# 2.根据二维数组的特点，可以想到一个思路：从数组的左下角开始遍历，
# 如果小于该数字那么就往上走，如果大于该数字那么就往右走(参考大佬的思路)
# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        rows = len(array) - 1
        cols = len(array[0]) - 1
        i = rows
        j = 0
        while j <= cols and i >= 0:
            if target < array[i][j]:
                i -= 1
            elif target > array[i][j]:
                j += 1
            else:
                return True
        return False

A = [[1,3,4],
     [2,5,8],
     [3,6,9]]
target = 5
B = Solution().Find(target,A)
print(B)


# -*- coding: utf-8 -*-
from numpy import convolve, ndarray, ones
from pandas import Series
from pandas_ta._typing import Array, DictLike, Int
from pandas_ta.maps import Imports
from pandas_ta.utils import np_prepend, v_offset, v_pos_default
from pandas_ta.utils import v_series, v_talib

try:
    from numba import njit
except ImportError:
    def njit(_): return _

@njit
def np_sma(x: Array, n: Int):
    """https://github.com/numba/numba/issues/4119"""
    result = convolve(ones(n) / n, x)[n - 1:1 - n]
    return np_prepend(result, n - 1)

# SMA: Alternative Implementations
# @njit
# def np_sma(x: np.ndarray, n: int):
#     result = np.convolve(x, np.ones(n), mode="valid") / n
#     return np_prepend(result, n - 1)

# @njit
# def np_sma(x: np.ndarray, n: int):
#     csum = np.cumsum(x, dtype=float)
#     csum[n:] = csum[n:] - csum[:-n]
#     result = csum[n - 1:] / n
#     return np_prepend(result, n - 1)

def sma(
    close: Series, length: Int = None, talib: bool = None,
    offset: Int = None, **kwargs: DictLike
) -> Series:
    """Simple Moving Average (SMA)

    The Simple Moving Average is the classic moving average that is the
    equally weighted average over its length.

    Sources:
        https://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/simple-moving-average-sma/

    Args:
        close (pd.Series): Series of 'close's
        length (int): It's period. Default: 10
        talib (bool): If TA Lib is installed and talib is True, Returns
            the TA Lib version. Default: True
        offset (int): How many periods to offset the result. Default: 0

    Kwargs:
        adjust (bool): Default: True
        presma (bool, optional): If True, uses SMA for initial value.
        fillna (value, optional): pd.DataFrame.fillna(value)
        fill_method (value, optional): Type of fill method

    Returns:
        pd.Series: New feature generated.
    """
    # Validate
    length = v_pos_default(length, 10)
    if "min_periods" in kwargs and kwargs["min_periods"] is not None:
        min_periods = int(kwargs["min_periods"])
    else:
        min_periods = length
    close = v_series(close, max(length, min_periods))

    if close is None:
        return

    mode_tal = v_talib(talib)
    offset = v_offset(offset)

    # Calculate
    if Imports["talib"] and mode_tal and length > 1:
        from talib import SMA
        sma = SMA(close, length)
    else:
        np_close = close.values
        sma = np_sma(np_close, length)
        sma = Series(sma, index=close.index)

    # Offset
    if offset != 0:
        sma = sma.shift(offset)

    # Fill
    if "fillna" in kwargs:
        sma.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        sma.fillna(method=kwargs["fill_method"], inplace=True)

    # Name and Category
    sma.name = f"SMA_{length}"
    sma.category = "overlap"

    return sma


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 27 20:02:48 2017

@author: davi
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import sys; sys.path.append('../')
from pyooopt import EvolutionaryAlgorithm
from pyooopt.cost_functions import ContinuousFunction

np.random.seed(0)

function = ContinuousFunction()
ecosystem = EvolutionaryAlgorithm('min',function.venkataraman,20,2,[-5,5])
optimizer_results =ecosystem.evolve(.8,.1,10)

###PLOTTING
x1 = np.linspace(-5, 5, 100)
x2 = np.linspace(-5, 5, 100)
X = np.array(np.meshgrid(x1, x2))
z = function.venkataraman(X)

for i, generation in enumerate(optimizer_results['solutions']):
    plt.figure()
    plt.contour(x1,x2,z,np.arange(-3.3, 3.5, .25).tolist(),cmap='jet')
    plt.scatter(generation[:,0],generation[:,1],c=[0,0,0],zorder=1e+3)
    plt.savefig('generation'+str(i)+'.jpg')

#Create .gif
os.system('convert -delay 20 -loop 0 *.jpg images/evolution.gif')
os.system('rm *.jpg')


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

import io
def sprint(*args, **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, file=sio)
    return sio.getvalue()

tab1=open("tab1.csv","w")
header="node_class,system,Code,test,cores,nodes,tpn,size,Metric"
tab1.write(header+"\n")
# In[ ]:
def test4(a,b,c,d):
# this can happen if the code runs out of memory
# here we just replace the messages with a ?
    try:
      float(a)
    except :
      a="?"
    try:
      float(b)
    except :
      b="?"
    try:
      float(c)
    except :
      c="?"
    try:
      float(d)
    except :
      d="?"
    return (a,b,c,d)

#set the title for this output
title="Standard,Reference,As-is code"
if not('get_ipython' in dir()) :
    from sys import argv
    if len(argv) > 1 :
        title=""
        for x in argv[1:] :
            title=title+" "+x
        title=title[1:]
#print(title)
[node_class,system,optimization]=title.split(",")
indat="rawdat"
f=open(indat,"r")
dat=f.readlines()
val=open(indat+".val","w")
tmp=""
for l in dat:
    if l.find("Running") == 0 :
        if len(tmp) > 0:
            val.write("At least one test did not call MPI_Finalize - validation failed\n")
            val.write(tmp+"\n")
            tmp=l.strip()
        else:
            tmp=l.strip()
    if len(tmp) > 0  and  l.find("Final") > 0:
        val.write(tmp+"\t"+l)
        tmp=""
if len(tmp) > 0:
        val.write("At least one test did not call MPI_Finalize - validation failed")

val.close()
#Clean up our data, remove comments and blank lines
cleaned=[]
for d in dat:
    if len(d.strip()) > 0:
        if d[0] != "#" :
            cleaned.append(d)
dat=cleaned

# Group tests for different sizes on a single line
single=True
dosplit=True

#Set delim to either tab or comma
delim=","
#delim="\t"

# In[ ]:

tests=['Pingpong']
maxhead="t[usec]"
for test in tests:
    lines=[]
    k=0
    # find the lines that mark the beginning of a test
    for l in dat:
        n=l.find("Running "+test)
        if n > -1:
            lines.append(k)
        k=k+1
    cases=[2,3]
    if single :
        print("node_class","system","optimization","test","cores","nodes","tpn","size",maxhead,"b","c","d","e","f","g",sep=delim)
    else:
        pass
    for i in lines :
        head=dat[i].split()
        cores=head[3]
        nodes=head[5]
        tpn=head[9]
        for case in cases :
                res=dat[i+case]
                res=res.split()
                # this sould not happen, maybe the job crashed
                if len(res) < 3:
                    print("error,")
                    break
                try:
                    size=res[0]
                    max=res[2]
                except:
                    print("error,")
                    break
                if single:
                    if case == cases[0] :
                        cores,nodes,tpn,size=test4(cores,nodes,tpn,size)
                        print(node_class,system,optimization,test,cores,nodes,tpn,size,max,-1,-1,-1,-1,-1,-1,sep=delim)
                        xout=sprint("%s,%s,%s,%s,%s,%s,%s,%s,%s" % (node_class,system,optimization,test,cores,nodes,tpn,size,max))
                        tab1.write(xout)
                    else:
                        cores,nodes,tpn,size=test4(cores,nodes,tpn,size)
                        print(node_class,system,optimization,test,cores,nodes,tpn,size,max,-1,-1,-1,-1,-1,-1,sep=delim)
                        xout=sprint("%s,%s,%s,%s,%s,%s,%s,%s,%s" % (node_class,system,optimization,test,cores,nodes,tpn,size,max))
                        tab1.write(xout)
                else:
                    pass

# In[ ]:
if dosplit : print()

tests=['Barrier']
for test in tests:
    lines=[]
    k=0
    # find the lines that mark the beginning of a test
    for l in dat:
        n=l.find("Running "+test)
        if n > -1:
            lines.append(k)
        k=k+1
    print("node_class","system","optimization","test","cores","nodes","tpn","t_max[usec]","a","b","c","d","e","f","g",sep=delim)
    for i in lines :
            head=dat[i].split()
            cores=head[3]
            nodes=head[5]
            tpn=head[9]
            res=dat[i+2]
            #print(res)
            res=res.split()
            res=res[2]
            #(cores,nodes,tpn,size)=test4(cores,nodes,tpn,size)
            print(node_class,system,optimization,test,cores,nodes,tpn,res,-1,-1,-1,-1,-1,-1,-1,sep=delim)
            xout=sprint("%s,%s,%s,%s,%s,%s,%s,%s,%s" % (node_class,system,optimization,test,cores,nodes,tpn," ",res))
            tab1.write(xout)

# In[ ]:

if dosplit : print()

tests="Alltoall Allgather Allreduce Sendrecv Exchange Uniband Biband"
tests=tests.split()

for test in tests:
    maxhead="t_max[usec]"
    if test == "Uniband" :
        maxhead="Msg/sec"
    if test == "Biband" :
        maxhead="Msg/sec"
    #if you run more cases this line will need to be changed
    cases=[2,3,4,5]
    #print(test)
    lines=[]
    k=0
    # find the lines that mark the beginning of a test
    for l in dat:
        n=l.find("Running "+test)
        if n > -1:
            lines.append(k)
        k=k+1
    #print(lines)
    if single :
        buf=sprint("node_class","system","optimization","test","cores","nodes","tpn","size",maxhead,sep=delim,end=delim)
        buf.rstrip(",")
        for case in cases[1:]:
            buf=buf+sprint("size",maxhead,sep=delim,end=delim)
        buf=buf.rstrip(",")
        print(buf)
    else:
        pass
    for i in lines :
        head=dat[i].split()
        cores=head[3]
        nodes=head[5]
        tpn=head[9]
        for case in cases :
                #print("where",i,i+case)
                res=dat[i+case]
                #print("res",res)
                res=res.split()
                # this sould not happen, maybe the job crashed
                if len(res) < 4:
                    print("error,")
                    break
                try:
                    #print(res)
                    size=res[0]
                    max=res[3]
                    if test.find("band") > 0 :
                        max=res[3]
                except:
                    print("error,")
                    break
                if single:
                    if case == cases[0] :
                        cores,nodes,tpn,size=test4(cores,nodes,tpn,size)
                        if size == "?" : max="?"
                        buf=sprint(node_class,system,optimization,test,cores,nodes,tpn,size,max,sep=delim,end=delim)
                        xout=sprint("%s,%s,%s,%s,%s,%s,%s,%s,%s" % (node_class,system,optimization,test,cores,nodes,tpn,size,max))
                        tab1.write(xout)
                    else:
                        size,max,d1,d2=test4(size,max,"1","1")
                        if size == "?" : max="?"
                        buf=buf+sprint(size,max,sep=delim,end=delim)
                        xout=sprint("%s,%s,%s,%s,%s,%s,%s,%s,%s" % (node_class,system,optimization,test,cores,nodes,tpn,size,max))
                        tab1.write(xout)
                    if case == cases[-1]:
                        buf=buf.rstrip(",")
                        print(buf)
                else:
                    pass
    if dosplit : print()


#
#
#

from __future__ import absolute_import, division, print_function, \
    unicode_literals

from collections import defaultdict
from os import listdir, makedirs
from os.path import isdir, isfile, join
import logging

from ..record import Record
from ..yaml import safe_load, safe_dump
from .base import BaseProvider

class YamlProvider(BaseProvider):
    '''
    Core provider for records configured in yaml files on disk.

    config:
        class: octodns.provider.yaml.YamlProvider
        # The location of yaml config files (required)
        directory: ./config
        # The ttl to use for records when not specified in the data
        # (optional, default 3600)
        default_ttl: 3600
        # Whether or not to enforce sorting order on the yaml config
        # (optional, default True)
        enforce_order: True
    '''
    SUPPORTS_GEO = True
    SUPPORTS_DYNAMIC = True
    SUPPORTS_ROOT_NS = True
    SUPPORTS = set(('A', 'AAAA', 'ALIAS', 'CAA', 'CNAME', 'MX', 'NAPTR', 'NS',
                    'PTR', 'SSHFP', 'SPF', 'SRV', 'TXT'))

    def __init__(self, id, directory, default_ttl=3600, enforce_order=True,
                 *args, **kwargs):
        self.log = logging.getLogger('{}[{}]'.format(
            self.__class__.__name__, id))
        self.log.debug('__init__: id=%s, directory=%s, default_ttl=%d, '
                       'enforce_order=%d', id, directory, default_ttl,
                       enforce_order)
        super(YamlProvider, self).__init__(id, *args, **kwargs)
        self.directory = directory
        self.default_ttl = default_ttl
        self.enforce_order = enforce_order
        self.manage_root_ns = True

    def _populate_from_file(self, filename, zone, lenient):
        with open(filename, 'r') as fh:
            yaml_data = safe_load(fh, enforce_order=self.enforce_order)
            if yaml_data:
                for name, data in yaml_data.items():
                    if not isinstance(data, list):
                        data = [data]
                    for d in data:
                        if 'ttl' not in d:
                            d['ttl'] = self.default_ttl
                        record = Record.new(zone, name, d, source=self,
                                            lenient=lenient)
                        zone.add_record(record, lenient=lenient)
            self.log.debug(
                '_populate_from_file: successfully loaded "%s"', filename)

    def populate(self, zone, target=False, lenient=False):
        self.log.debug('populate: name=%s, target=%s, lenient=%s', zone.name,
                       target, lenient)

        if target:
            # When acting as a target we ignore any existing records so that we
            # create a completely new copy
            return False

        before = len(zone.records)
        filename = join(self.directory, '{}yaml'.format(zone.name))
        self._populate_from_file(filename, zone, lenient)

        self.log.info('populate:   found %s records, exists=False',
                      len(zone.records) - before)
        return False

    def _apply(self, plan):
        desired = plan.desired
        changes = plan.changes
        self.log.debug('_apply: zone=%s, len(changes)=%d', desired.name,
                       len(changes))
        # Since we don't have existing we'll only see creates
        records = [c.new for c in changes]
        # Order things alphabetically (records sort that way
        records.sort()
        data = defaultdict(list)
        for record in records:
            d = record.data
            d['type'] = record._type
            if record.ttl == self.default_ttl:
                # ttl is the default, we don't need to store it
                del d['ttl']
            if record._octodns:
                d['octodns'] = record._octodns
            data[record.name].append(d)

        # Flatten single element lists
        for k in data.keys():
            if len(data[k]) == 1:
                data[k] = data[k][0]

        if not isdir(self.directory):
            makedirs(self.directory)

        self._do_apply(desired, data)

    def _do_apply(self, desired, data):
        filename = join(self.directory, '{}yaml'.format(desired.name))
        self.log.debug('_apply:   writing filename=%s', filename)
        with open(filename, 'w') as fh:
            safe_dump(dict(data), fh)

def _list_all_yaml_files(directory):
    yaml_files = set()
    for f in listdir(directory):
        filename = join(directory, '{}'.format(f))
        if f.endswith('.yaml') and isfile(filename):
            yaml_files.add(filename)
    return list(yaml_files)

class SplitYamlProvider(YamlProvider):
    '''
    Core provider for records configured in multiple YAML files on disk.

    Behaves mostly similarly to YamlConfig, but interacts with multiple YAML
    files, instead of a single monolitic one. All files are stored in a
    subdirectory matching the name of the zone (including the trailing .) of
    the directory config. The files are named RECORD.yaml, except for any
    record which cannot be represented easily as a file; these are stored in
    the catchall file, which is a YAML file the zone name, prepended with '$'.
    For example, a zone, 'github.com.' would have a catch-all file named
    '$github.com.yaml'.

    A full directory structure for the zone github.com. managed under directory
    "zones/" would be:

    zones/
      github.com./
        $github.com.yaml
        www.yaml
        ...

    config:
        class: octodns.provider.yaml.SplitYamlProvider
        # The location of yaml config files (required)
        directory: ./config
        # The ttl to use for records when not specified in the data
        # (optional, default 3600)
        default_ttl: 3600
        # Whether or not to enforce sorting order on the yaml config
        # (optional, default True)
        enforce_order: True
    '''

    # Any record name added to this set will be included in the catch-all file,
    # instead of a file matching the record name.
    CATCHALL_RECORD_NAMES = ('*', '')

    def __init__(self, id, directory, *args, **kwargs):
        super(SplitYamlProvider, self).__init__(id, directory, *args, **kwargs)

    def _zone_directory(self, zone):
        return join(self.directory, zone.name)

    def populate(self, zone, target=False, lenient=False):
        self.log.debug('populate: name=%s, target=%s, lenient=%s', zone.name,
                       target, lenient)

        if target:
            # When acting as a target we ignore any existing records so that we
            # create a completely new copy
            return False

        before = len(zone.records)
        yaml_filenames = _list_all_yaml_files(self._zone_directory(zone))
        self.log.info('populate:   found %s YAML files', len(yaml_filenames))
        for yaml_filename in yaml_filenames:
            self._populate_from_file(yaml_filename, zone, lenient)

        self.log.info('populate:   found %s records, exists=False',
                      len(zone.records) - before)
        return False

    def _do_apply(self, desired, data):
        zone_dir = self._zone_directory(desired)
        if not isdir(zone_dir):
            makedirs(zone_dir)

        catchall = dict()
        for record, config in data.items():
            if record in self.CATCHALL_RECORD_NAMES:
                catchall[record] = config
                continue
            filename = join(zone_dir, '{}.yaml'.format(record))
            self.log.debug('_apply:   writing filename=%s', filename)
            with open(filename, 'w') as fh:
                record_data = {record: config}
                safe_dump(record_data, fh)
        if catchall:
            # Scrub the trailing . to make filenames more sane.
            dname = desired.name[:-1]
            filename = join(zone_dir, '${}.yaml'.format(dname))
            self.log.debug('_apply:   writing catchall filename=%s', filename)
            with open(filename, 'w') as fh:
                safe_dump(catchall, fh)


#-*-coding:UTF-8-*-
__author__ = 'fxf'

import subprocess,sys
import time
from PyQt4 import QtGui, QtCore
from Screencap import Ui_Screencap

class GetScreencap(QtGui.QWidget,Ui_Screencap):

	def __init__(self,parent=None):
		QtGui.QWidget.__init__(self,parent)
		self.setupUi(self)
		self.num = 0
		self.connect(self.acceptButton,QtCore.SIGNAL("clicked()"),self.on_savecap_clicked)
		self.connect(self.choiceButton,QtCore.SIGNAL("clicked()"),self.on_savefile_clicked)
		self.connect(self.CanelButton,QtCore.SIGNAL("clicked()"),self.on_canel_clicked)
		self.connect(self.installApkLine,QtCore.SIGNAL("returnPressed()"),self.on_savecap_clicked)

	def on_savefile_clicked(self):
		dlg = QtGui.QFileDialog()
		filename = dlg.getSaveFileName(self,'SaveUrl','/','PNG(*.png)')
		self.installApkLine.setText(filename)

	def on_canel_clicked(self):
		self.installApkLine.clear()
		sys.exit()

	def on_savecap_clicked(self):
		p = subprocess.Popen("adb get-state", shell = True,stdout = subprocess.PIPE)
		pi = p.communicate()
		if "unknown" in pi[0]:
			warningWindow = QtGui.QWidget()
			QtGui.QMessageBox.information(warningWindow,u"Error",u"ADB Disconnect")
		else:
			self.acceptButton.setEnabled(False)
			filename = self.installApkLine.text()
			if filename == "":
				filename = "Screencap"
			if '.png' in filename:
				pass
			else:
				filename = str(filename) + '.png'
			sdcardUrl = "/sdcard/fdroidscreencap.png"
			subprocess.call(str("adb shell screencap -p "+sdcardUrl),shell=True)
			subprocess.call(str("adb pull " + sdcardUrl + " " + filename),shell=True)
			self.acceptButton.setEnabled(True)
			if str(self.num) in filename:
				self.installApkLine.setText(filename.split(str(self.num))[0] + str(self.num + 1) + '.png')
			else:
				self.installApkLine.setText(filename.split('.')[0] + str(self.num +1) + '.png')
			self.num += 1

if __name__ == '__main__':
	import sys
	app = QtGui.QApplication(sys.argv)
	FDroidTools = GetScreencap()
	FDroidTools.show()
	sys.exit(app.exec_())


import matplotlib.pyplot as plt

def ASSIGNMENT(new_list, i, old_list, j):
    new_list[i] = old_list[j]

def mergeSort(list_to_sort_by_merge):
    if (
        len(list_to_sort_by_merge) > 1
        and not len(list_to_sort_by_merge) < 1
        and len(list_to_sort_by_merge) != 0
    ):
        mid = len(list_to_sort_by_merge) // 2
        left = list_to_sort_by_merge[:mid]
        right = list_to_sort_by_merge[mid:]

        mergeSort(left)
        mergeSort(right)

        l = 0
        r = 0
        i = 0

        while l < len(left) and r < len(right):
            if left[l] <= right[r]:
                ASSIGNMENT(new_list=list_to_sort_by_merge, i=i, old_list=left, j=l)
                l += 1
            else:
                ASSIGNMENT(new_list=list_to_sort_by_merge, i=i, old_list=right, j=r)
                r += 1
            i += 1

        while l < len(left):
            list_to_sort_by_merge[i] = left[l]
            l += 1
            i += 1

        while r < len(right):
            list_to_sort_by_merge[i] = right[r]
            r += 1
            i += 1

def plotting(lst):
    fig,(ax1,ax2) = plt.subplots(figsize=(10,5),ncols=2)
    fig.suptitle("Comparison", fontsize=20)
    x = range(len(lst))

    ax1.set_title("before mergesort",fontsize=20)
    ax1.bar(x, lst,color="navy")
    ax1.set_xlabel("index", fontsize=20)
    ax1.set_ylabel("value", fontsize=20)

    mergeSort(lst)
    ax2.bar(x,lst,color="crimson")
    ax2.set_title("after mergesort",fontsize=20)
    ax2.set_xlabel("index", fontsize=20)
    ax2.sharey(ax1)
    plt.show()

my_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
plotting(my_list)


from telegram import Bot
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler

bot = Bot(token='5983595001:AAEtJeQFlSpBTE4RBEGBben9kjzaJYVUEc0')
updater = Updater(token='5983595001:AAEtJeQFlSpBTE4RBEGBben9kjzaJYVUEc0')
dispahather = updater.dispatcher

A = 0
# B = 1

def start(update, context):
    context.bot.send_message(update.effective_chat.id, 'Введите текст для форматирования')
    return A

def filter_text(update, context):
    text = update.message.text
    f = list(text.split())
    print(type(text))
    n = 'абв'
    value = ' '.join(filter(lambda x: n not in x, f))
    context.bot.send_message(update.effective_chat.id, f'Готовый текст: {value}')

    return ConversationHandler.END

def cancel(update, context):
    context.bot.send_message(update.effective_chat.id, 'Прощай!')

start_handler = CommandHandler('start', start)
message_handler = MessageHandler(Filters.text, filter_text)
# message_weather_handler = MessageHandler(Filters.text, weather)
message_cancel_handler = MessageHandler(Filters.text, cancel)

conv_handler = ConversationHandler(entry_points=[start_handler],
                                   states={A: [message_handler]},
                                    fallbacks=[message_cancel_handler])

# dispahather.add_handler(start_handler)
dispahather.add_handler(conv_handler)
# dispahather.add_handler(message_handler)
# dispahather.add_handler(message_weather_handler)
# dispahather.add_handler(message_cancel_handler)

updater.start_polling()
updater.idle()


import random
import numpy as np

from models import TransitionModel,ObservationModel,StateModel

#
# Add your Robot Simulator here
#Perfrom simulation here ?

class RobotSim:
    def __init__(self, pose:(int, int, int)):
        self.__x = pose[0]
        self.__y = pose[1]
        self.__head = pose[2]

    def update_pos(self, direction):
        directionVector = [(-1,0),(0,1),(1,0),(0,-1)]
        newDirection = directionVector[direction]
        self.__x += newDirection[0]
        self.__y += newDirection[1]
        self.__head = direction
        return self.__x,self.__y,self.__head

#
# Add your Filtering approach here (or within the Localiser, that is your choice!)
# FIlter here ?
class HMMFilter:
    def __init__(self, om):
        print('Hello World')
        self.__om = om

    # Calculate the new probability distribution

    def forward_filter(self, sensor_position, T_transp, f):
        r = None
        if sensor_position != None:
            r = sensor_position

        O = self.__om.get_o_reading(r)
        f_new = np.dot(O, np.dot(T_transp, f))
        best_state = None
        best_proba = -1
        for i in range(len(f_new)):
            if f_new[i] > best_proba:
                best_proba = f_new[i]
                best_state = i

        return f_new/np.sum(f_new), best_state


import time
from connection import Connection
class Validacion:
    def validaCredito(self, cve_usuario, status):
        try:
            res = []
            operacion = False
            msg = 'No se pudo actualizar el registro'
            cur = Connection()
            data = [status, cve_usuario]
            query = 'update solicitudes ' \
                        'set status = :1 ' \
                        'where cve_usuario = :2 and fecha = (select max(fecha) from solicitudes)'
            operacion = cur.executeQuery(query, data)
            if operacion:
                msg = 'Se ha dado respuesta de la solicitud'

        except Exception as ex:
            print('Error en base')
            print(ex)
        finally:
            res.append({
                'operacion': operacion,
                'msg': msg
            })
            print(res)
        return res


import image_encryption.Logistic.log.logisticKey as key   # Importing the key generating function
import numpy as np
import cv2

# Accepting an image
# path = str(input('Enter the path of image\n'))

def log_enc(path):
    image = cv2.imread(path)
    # name = str(input('Enter name:\n'))
    # Displaying the image

    # Generating dimensions of the image
    height = image.shape[0]
    width = image.shape[1]
    print(height, width)

    # Generating keys
    # Calling logistic_key and providing r value such that the keys are pseudo-random
    # and generating a key for every pixel of the image
    generatedKey = key.logistic_key(0.01, 3.95, height*width)
    # print(generatedKey)

    # Encryption using XOR
    z = 0

    # Initializing the encrypted image
    encryptedImage = np.zeros(shape=[height, width, 3], dtype=np.uint8)

    # Substituting all the pixels in original image with nested for
    for i in range(height):
        for j in range(width):
            # USing the XOR operation between image pixels and keys
            encryptedImage[i, j] = image[i, j].astype(int) ^ generatedKey[z]
            z += 1

    # Displaying the encrypted image

    # Decryption using XOR
    z = 0

    # Initializing the decrypted image
    decryptedImage = np.zeros(shape=[height, width, 3], dtype=np.uint8)

    # Substituting all the pixels in encrypted image with nested for
    for i in range(height):
        for j in range(width):
            # USing the XOR operation between encrypted image pixels and keys
            decryptedImage[i, j] = encryptedImage[i, j].astype(int) ^ generatedKey[z]
            z += 1

    # Displaying the decrypted image
    cv2.imwrite("home/static/home/result/Recovered.jpg", decryptedImage)
    cv2.imwrite("home/static/home/result/enc.jpg", encryptedImage)


def nck(n, k, mod):
    if k < 0:
        return 0
    sum = 1
    nci = 1
    for i in range(1, k+1):
        nci = (nci * (n - i + 1))%mod
        nci = (nci*pow(i, mod-2, mod)) %mod
        sum = (sum + nci) % mod

    sum %= mod
    return sum

def fin(n, k, mod):
    if k > n//2:
        sum = pow(2, n, mod) - nck(n, n-k-1, mod)
    else:
        sum = nck(n, k, mod)
    return sum

def main():
    mod = 10**9 + 7
    (n, k) = map(int, input().split())
    arr = list(map(int, input().split()))
    d = {}
    count = 0
    for i in arr:
        if i in d:
            d[i] += 1
        else:
            count += 1
            d[i] = 1
    print(count)
    print(fin(count, k, mod))

if __name__ == '__main__':
    main()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
        if(root == None):
            return False
        x_info = []
        y_info = []
        d = 0
        parent = None

        self.depthfirst(root,x,y,0,None,x_info,y_info)
        return(x_info[0][0]==y_info[0][0] and x_info[0][1]!=y_info[0][1])

    def depthfirst(self,root,x,y,d,parent,x_info,y_info):
        if(root == None):
            return None
        if(root.val == x):
            x_info.append((d,parent))
        if(root.val == y):
            y_info.append((d,parent))

        self.depthfirst(root.left,x,y,d+1,root,x_info,y_info)
        self.depthfirst(root.right,x,y,d+1,root,x_info,y_info)


from keras.preprocessing import image
from PIL import Image
import keras.applications.inception_v3 as inception_v3
import pandas as pd
import numpy as np
import os

print('confidence encodeing start...')

image_files = [x.path for x in os.scandir('./data/images/')]
inception_model = inception_v3.InceptionV3(weights='imagenet')

def classify_inception(image_path):
    try:
        img = image.load_img(image_path, target_size=(224, 224))
    except (OSError, IOError):
        return [0,0,0.5]
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = inception_v3.preprocess_input(x)
    preds = inception_model.predict(x)
    return inception_v3.decode_predictions(preds, top=1)[0][0]

def image_id_from_path(path):
    return path.split('/')[3].split('.')[0]

inception_conf = [[image_id_from_path(x), classify_inception(x)[2]] for x in image_files]
confidence = pd.DataFrame(inception_conf, columns=['image', 'image_confidence'])
confidence.to_csv('./encoded_image.csv')


import timeit

from rlskyjo.game.sample_game import sample_run
from rlskyjo.game.skyjo import SkyjoGame

def test_sample_game():
    sample_run(games=1, verbose=1, config={"num_players": 3})
    sample_run(games=500)

def test_render():
    game = SkyjoGame()
    game.render_actions()
    game.render_table()
    game.render_player(0)
    game.render_player(player_id=0, render_cards_open=True)
    [game.render_action_explainer(action_int) for action_int in range(0, 26)]

def test_timing():
    sample_run(games=1, verbose=0, config={"num_players": 3})
    time_2500_games = timeit.timeit(
        'sample_run(games=2500, verbose=0, config={"num_players": 3})',
        number=1,
        globals={"sample_run": sample_run},
    )
    print(time_2500_games)
    assert time_2500_games < 180, (
        f"took longer then 180 seconds ({time_2500_games})"
        " to process 2500 games. common is around 20s"
    )


import typing

import serial

from PyQt5.QtCore import QThread, pyqtSignal, QObject

class TemperatureReader(QThread):
    temperature = pyqtSignal(str)

    def __init__(self, port_number: str, parent: typing.Optional[QObject] = ...) -> None:
        super(TemperatureReader, self).__init__(parent)

        self.serial = serial.Serial(
            port=port_number,
            baudrate=9600,
            parity=serial.PARITY_ODD,
            stopbits=serial.STOPBITS_TWO,
            bytesize=serial.SEVENBITS
        )
        self.scanning = True

    def run(self) -> None:

        while self.scanning:
            try:
                data = self.serial.readline().decode('utf-8')
                temp = float(data.strip('\n\r'))

                self.temperature.emit(f"Suhu: {temp} °C")
            except Exception:
                pass


#!/usr/bin/env python3
"""Example."""
import json

import numpy as np
import pyproj

import pysurfex

from_json = json.load(
    open(
        "/home/trygveasp/revision_control/pysurfex/examples/domains/met_nordic.json", "r"
    )
)
geo = pysurfex.get_geo_object(from_json)

wanted_lon = 10.0
nx = 120
wanted_lat = 60.0
ny = 100

earth = 6.37122e6
proj_string = (
    "+proj=lcc +lat_0="
    + str(geo.xlat0)
    + " +lon_0="
    + str(geo.xlon0)
    + " +lat_1="
    + str(geo.xlat0)
    + " +lat_2="
    + str(geo.xlat0)
    + " +units=m +no_defs +R="
    + str(earth)
)

proj = pyproj.CRS.from_string(proj_string)
wgs84 = pyproj.CRS.from_string("EPSG:4326")

xv, yv = np.meshgrid(geo.x, geo.y)
lons, lats = pyproj.Transformer.from_crs(proj, wgs84, always_xy=True).transform(xv, yv)

print(lons.shape)
print(lats.shape)

x0 = np.empty([geo.nimax])
y0 = np.empty([geo.njmax])
for i in range(0, geo.nimax):
    x0[i] = float(geo.x[i]) - (0.5 * ((float(nx) - 1.0) * geo.xdx))

for j in range(0, geo.njmax):
    y0[j] = float(geo.y[j]) - (0.5 * ((float(ny) - 1.0) * geo.xdy))

x0v, y0v = np.meshgrid(x0, y0)
lonc, latc = pyproj.Transformer.from_crs(proj, wgs84, always_xy=True).transform(x0v, y0v)
for i in range(0, geo.nimax):
    for j in range(0, geo.njmax):
        if abs(lonc[j][i] - wanted_lon) < 0.01 and abs(latc[j][i] - wanted_lat) < 0.01:
            print(
                "Possible subset centre points",
                i,
                j,
                xv[j, i],
                lonc[j][i],
                yv[j, i],
                latc[j][i],
            )


import inspect
import logging
import re
import typing
from abc import ABC
from dataclasses import dataclass
from enum import Enum
from pathlib import Path

from ..utils.artifacts import serialize_parameter

try:
    from types import NoneType
except ImportError:
    # types.NoneType is only available from python >=3.10
    NoneType = type(None)
from typing import Optional, Dict, List, Union, Literal, TypeVar, Callable, Type, Any

logger = logging.getLogger(__name__)

class Kwargs:
    pass

def _get_plugin_method_full_name(func):
    from giskard.ml_worker.testing.registry.registry import plugins_root

    path_parts = list(Path(inspect.getfile(func)).relative_to(plugins_root).with_suffix("").parts)
    path_parts.insert(0, "giskard_plugins")
    if "__init__" in path_parts:
        path_parts.remove("__init__")
    path_parts.append(func.__name__)
    return ".".join(path_parts)

def create_test_function_id(func):
    try:
        from giskard.ml_worker.testing.registry.registry import plugins_root

        # is_relative_to is only available from python 3.9
        is_relative = Path(inspect.getfile(func)).relative_to(plugins_root)
    except ValueError:
        is_relative = False
    if is_relative:
        full_name = _get_plugin_method_full_name(func)
    else:
        full_name = f"{func.__module__}.{func.__name__}"
    return full_name

class SupportedModelTypes(Enum):
    CLASSIFICATION = "classification"
    REGRESSION = "regression"
    TEXT_GENERATION = "text_generation"

ModelType = Union[SupportedModelTypes, Literal["classification", "regression", "text_generation"]]

class SupportedColumnTypes(Enum):
    NUMERIC = "numeric"
    CATEGORY = "category"
    TEXT = "text"

ColumnType = Union[SupportedColumnTypes, Literal["numeric", "category", "text"]]

class SavableMeta:
    uuid: Optional[str]

    def __init__(self, uuid: Optional[str] = None):
        self.uuid = uuid

    def to_json(self):
        return {"uuid": self.uuid}

    @classmethod
    def from_json(cls, json):
        obj = cls()
        obj.init_from_json(json)
        return obj

    def init_from_json(self, json: Dict[str, Any]):
        self.uuid = json["uuid"]

@dataclass
class ModelMeta:
    name: Optional[str]
    description: Optional[str]
    model_type: SupportedModelTypes
    feature_names: List[str]
    classification_labels: List[str]
    classification_threshold: float
    loader_module: str
    loader_class: str

@dataclass
class DatasetMeta:
    name: Optional[str]
    target: str
    column_types: Dict[str, str]
    column_dtypes: Dict[str, str]
    number_of_rows: int
    category_features: Dict[str, List[str]]

@dataclass
class FunctionArgument:
    name: str
    type: str
    default: any
    optional: bool
    argOrder: int

class CallableMeta(SavableMeta, ABC):
    code: str
    name: str
    display_name: str
    module: str
    doc: str
    module_doc: str
    tags: List[str]
    version: Optional[int]
    full_name: str
    type: str
    args: Dict[str, FunctionArgument]

    def __init__(
        self,
        callable_obj: Union[Callable, Type] = None,
        name: Optional[str] = None,
        tags: List[str] = None,
        version: Optional[int] = None,
        type: str = None,
    ):
        self.version = version
        self.type = type
        self.name = name
        self.tags = tags
        self.code = None
        self.display_name = None
        self.module = None
        self.doc = None
        self.module_doc = None
        self.full_name = None
        self.args = None

        if callable_obj:
            from giskard.ml_worker.testing.registry.registry import get_object_uuid

            self.full_name = create_test_function_id(callable_obj)
            func_uuid = get_object_uuid(callable_obj)
            super(CallableMeta, self).__init__(func_uuid)

            callable_obj.__module__.rpartition(".")
            func_doc = self.extract_doc(callable_obj)

            self.code = self.extract_code(callable_obj)
            self.name = callable_obj.__name__
            self.display_name = name or callable_obj.__name__
            self.module = callable_obj.__module__
            self.doc = func_doc
            self.module_doc = self.extract_module_doc(func_doc)
            self.tags = self.populate_tags(tags)

            parameters = self.extract_parameters(callable_obj)

            self.args = {
                parameter.name: FunctionArgument(
                    name=parameter.name,
                    type=extract_optional(parameter.annotation).__qualname__,
                    optional=parameter.default != inspect.Parameter.empty,
                    default=serialize_parameter(parameter.default),
                    argOrder=idx,
                )
                for idx, parameter in enumerate(parameters.values())
                if name != "self"
            }

    def extract_parameters(self, callable_obj):
        if inspect.isclass(callable_obj):
            parameters = list(inspect.signature(callable_obj.__init__).parameters.values())[1:]
        else:
            parameters = list(inspect.signature(callable_obj).parameters.values())

        return parameters

    @staticmethod
    def extract_module_doc(func_doc):
        return inspect.getmodule(func_doc).__doc__.strip() if inspect.getmodule(func_doc).__doc__ else None

    def populate_tags(self, tags=None):
        tags = [] if not tags else tags.copy()

        if self.name == "<lambda>":
            tags.append("lambda")
        elif self.full_name.partition(".")[0] == "giskard":
            tags.append("giskard")
        else:
            tags.append("custom")
        return tags

    def extract_code(self, callable_obj):
        code = None
        try:
            code = inspect.getsource(callable_obj)
        except Exception as e:
            logger.info(f"Failed to extract test function code {self.full_name}: %s" % e)
        return code

    @staticmethod
    def extract_doc(func):
        if func.__doc__:
            func_doc, _, args_doc = func.__doc__.partition("\n\n\n")
            func_doc = re.sub(r"\n[ \t\n]+", r"\n", func_doc.strip())
        else:
            func_doc = None
        return func_doc

    def to_json(self):
        return {
            "uuid": self.uuid,
            "name": self.name,
            "display_name": self.display_name,
            "module": self.module,
            "doc": self.doc,
            "module_doc": self.module_doc,
            "code": self.code,
            "tags": self.tags,
            "type": self.type,
            "args": [
                {
                    "name": arg.name,
                    "type": arg.type,
                    "default": arg.default,
                    "optional": arg.optional,
                    "argOrder": arg.argOrder,
                }
                for arg in self.args.values()
            ]
            if self.args
            else None,
        }

    def init_from_json(self, json: Dict[str, Any]):
        super().init_from_json(json)
        self.name = json["name"]
        self.display_name = json["displayName"]
        self.module = json["module"]
        self.doc = json["doc"]
        self.module_doc = json["moduleDoc"]
        self.code = json["code"]
        self.tags = json["tags"]
        self.version = json["version"]
        self.type = json["type"]
        self.args = (
            {
                arg["name"]: FunctionArgument(
                    name=arg["name"],
                    type=arg["type"],
                    default=arg["defaultValue"],
                    optional=arg["optional"],
                    argOrder=arg["argOrder"],
                )
                for arg in json["args"]
            }
            if json["args"]
            else None
        )

def __repr__(self) -> str:
    return f"CallableMeta: {self.module}.{self.name}"

class TestFunctionMeta(CallableMeta):
    debug_description: str

    def __init__(
        self,
        callable_obj: Union[Callable, Type] = None,
        name: Optional[str] = None,
        tags: List[str] = None,
        debug_description: str = None,
        version: Optional[int] = None,
        type: str = None,
    ):
        super().__init__(callable_obj, name, tags, version, type)
        self.debug_description = debug_description

    def extract_parameters(self, callable_obj):
        parameters = unknown_annotations_to_kwargs(CallableMeta.extract_parameters(self, callable_obj))

        return {p.name: p for p in parameters}

    def to_json(self):
        json = super().to_json()
        return {
            **json,
            "debug_description": self.debug_description,
        }

    def init_from_json(self, json: Dict[str, Any]):
        super().init_from_json(json)
        self.debug_description = json["debug_description"] if "debug_description" in json.keys() else None

class DatasetProcessFunctionType(Enum):
    CLAUSES = "CLAUSES"
    CODE = "CODE"

class DatasetProcessFunctionMeta(CallableMeta):
    cell_level: bool
    column_type: Optional[str]
    process_type: DatasetProcessFunctionType
    clauses: List[Dict[str, Any]]

    def __init__(
        self,
        callable_obj: Union[Callable, Type] = None,
        name: Optional[str] = None,
        tags: List[str] = None,
        version: Optional[int] = None,
        type: str = None,
        process_type: DatasetProcessFunctionType = DatasetProcessFunctionType.CODE,
        cell_level: bool = False,
        clauses: Optional[List[Dict[str, Any]]] = None,
    ):
        super(DatasetProcessFunctionMeta, self).__init__(callable_obj, name, tags, version, type)
        self.cell_level = cell_level
        self.process_type = process_type
        self.clauses = clauses or list()

        if cell_level:
            if inspect.isclass(callable_obj):
                parameters = list(inspect.signature(callable_obj.__init__).parameters.values())[1:]
            else:
                parameters = list(inspect.signature(callable_obj).parameters.values())
            self.column_type = parameters[0].annotation.__qualname__
        else:
            self.column_type = None

    def extract_parameters(self, callable_obj):
        parameters = unknown_annotations_to_kwargs(CallableMeta.extract_parameters(self, callable_obj)[1:])

        return {p.name: p for p in parameters}

    def to_json(self):
        json = super().to_json()
        return {
            **json,
            "cellLevel": self.cell_level,
            "columnType": self.column_type,
            "processType": self.process_type.value,
            "clauses": self.clauses,
        }

    def init_from_json(self, json: Dict[str, Any]):
        super().init_from_json(json)
        self.cell_level = json["cellLevel"]
        self.column_type = json["columnType"]
        self.process_type = DatasetProcessFunctionType[json["processType"]]
        self.clauses = json["clauses"]

DT = TypeVar("DT")
SMT = TypeVar("SMT", bound=SavableMeta)

def unknown_annotations_to_kwargs(parameters: List[inspect.Parameter]) -> List[inspect.Parameter]:
    from giskard.models.base import BaseModel
    from giskard.datasets.base import Dataset
    from giskard.ml_worker.testing.registry.slicing_function import SlicingFunction
    from giskard.ml_worker.testing.registry.transformation_function import TransformationFunction

    allowed_types = [str, bool, int, float, BaseModel, Dataset, SlicingFunction, TransformationFunction]
    allowed_types = allowed_types + list(map(lambda x: Optional[x], allowed_types))

    has_kwargs = any(
        [param for param in parameters if not any([param.annotation == allowed_type for allowed_type in allowed_types])]
    )

    parameters = [
        param for param in parameters if any([param.annotation == allowed_type for allowed_type in allowed_types])
    ]

    if has_kwargs:
        parameters.append(inspect.Parameter(name="kwargs", kind=4, annotation=Kwargs))

    return parameters

def extract_optional(field):
    if typing.get_origin(field) is Union and NoneType in typing.get_args(field):
        return Union[tuple([arg for arg in typing.get_args(field) if arg is not None and arg is not NoneType])]
    else:
        return field

class ComparisonType(Enum):
    IS = "IS"
    IS_NOT = "IS_NOT"
    CONTAINS = "CONTAINS"
    DOES_NOT_CONTAINS = "DOES_NOT_CONTAINS"
    STARTS_WITH = "STARTS_WITH"
    ENDS_WITH = "ENDS_WITH"
    IS_EMPTY = "IS_EMPTY"
    IS_NOT_EMPTY = "IS_NOT_EMPTY"

@dataclass
class ComparisonClauseDTO:
    columnName: str
    comparisonType: ComparisonType
    columnDtype: str
    value: Optional[str]


"""
"""

import struct
from .fec import SkylinkError

__all__ = [
    "encode_golay24",
    "decode_golay24",
    "encode_golay24_bytes",
    "decode_golay24_bytes",
    "GolayUncorrectable"
]

N = 12
H = ( 0x8008ed, 0x4001db, 0x2003b5, 0x100769, 0x80ed1, 0x40da3,
      0x20b47,  0x1068f,  0x8d1d,   0x4a3b,   0x2477,  0x1ffe )

def parity(v: int) -> int:
    """
    Calculate the parity
    Ref: http://p-nand-q.com/python/algorithms/math/bit-parity.html
    """
    v ^= v >> 1
    v ^= v >> 2
    v = (v & 0x11111111) * 0x11111111
    return (v >> 28) & 1

def popcount(i: int) -> int:
    """
    https://stackoverflow.com/questions/407587/python-set-bits-count-popcount
    """
    assert 0 <= i < 0x100000000
    i = i - ((i >> 1) & 0x55555555)
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
    return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24

def encode_golay24(data: int) -> int:
    """
    """
    data &= 0xfff
    s = 0
    for i in range(N):
        s <<= 1
        s |= parity(H[i] & data)
    return ((0xFFF & s) << N) | data

class GolayUncorrectable(SkylinkError):
    pass

class Step8(SkylinkError):
    pass

def decode_golay24(data: int) -> int:
    """
    Decode
    """

    try:
        # Step 1. s = H*r
        s = 0
        for i in range(N):
            s <<= 1
            s |= parity(H[i] & data)

        # Step 2. if w(s) <= 3, then e = (s, 0) and go to step 8
        if popcount(s) <= 3:
            e = s
            e <<= N
            raise Step8()

        # Step 3. if w(s + B[i]) <= 2, then e = (s + B[i], e_{i+1}) and go to step 8
        for i in range(12):
            if popcount(s ^ (H[i] & 0xfff)) <= 2:
                e = s ^ (H[i] & 0xfff)
                e <<= N
                e |= 1 << (N - i - 1)
                raise Step8()

        # Step 4. compute q = B*s
        q = 0
        for i in range(12):
            q <<= 1
            q |= parity((H[i] & 0xfff) & s)

        # Step 5. If w(q) <= 3, then e = (0, q) and go to step 8
        if popcount(q) <= 3:
            e = q
            raise Step8()

        # Step 6. If w(q + B[i]) <= 2, then e = (e_{i+1}, q + B[i]) and got to step 8
        for i in range(12):
            if popcount(q ^ (H[i] & 0xfff)) <= 2:
                e = 1 << (2 * N - i - 1)
                e |= q ^ (H[i] & 0xfff)
                raise Step8()

        # Step 7. r is uncorrectable
        raise GolayUncorrectable()

    except Step8:

        # Step 8. c = r + e
        return (data ^ e) & 0xFFF

def encode_golay24_bytes(v: int) -> bytes:
    """ Encode integer using Golay24 coding and return it as bytes """
    return struct.pack(">I", encode_golay24(v))[1:]

def decode_golay24_bytes(b: bytes) -> int:
    """ Decode Golay24 coded bytes and return it as integer. """
    return decode_golay24(struct.unpack(">I", b"\x00" + b[:3])[0])

if __name__ == "__main__":
    #
    # Short unit test
    #

    data = 200

    r = encode_golay24(data)
    print(f"encoded   {r:06x}")

    r ^= (256|4|1)
    print(f"corrupted {r:06x}")

    rn = decode_golay24(r)
    print(f"decoded   {rn:06x}")


sum = 0
count = 0
end_input = False
while not end_input:
    try:
        n = int(input("Enter an integer:"))
        if n > 0:
           sum = sum + n
           count = count + 1
           avg = sum / count
        elif avg == 0:
            exit()
        else:
            break
    except ValueError:
        print("Please enter a valid integer")
print(f"Average is {avg}")