# Exercise: Build a model that returns the log-softmax as the output and calculate the loss using the negative log
# likelihood loss. Note that for nn.LogSoftmax and F.log_softmax you'll need to set the dim keyword argument
# appropriately. dim=0 calculates softmax across the rows, so each column sums to 1, while dim=1 calculates across the
# columns so each row sums to 1. Think about what you want the output to be and choose dim appropriately.

import torch
from torch import nn
import torch.nn.functional as F
from torchvision import datasets, transforms

# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.5, ), (0.5, )),
                              ])

# Download and load the training data
trainset = datasets.MNIST('MNIST_data\\', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

# Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
                      nn.ReLU(),
                      nn.Linear(128, 64),
                      nn.ReLU(),
                      nn.Linear(64, 10),
                      nn.LogSoftmax(dim=1)) # dim=1 logs corresponds to columns instead of rows

# Define the loss
criterion = nn.NLLLoss()

### Run this to check your work
# Get our data
images, labels = next(iter(trainloader))
# Flatten images
images = images.view(images.shape[0], -1)

# Forward pass, get our logits
log_ps = model(images)
# Calculate the loss with the logits and the labels
loss = criterion(log_ps, labels)

print(loss)


#!/usr/bin/python
# -*- coding: UTF-8 -*-

"""
 Created by qijianpeng on 2018/10/13.
 Email: jianpengqi@126.com
"""
import os
import pandas as pd
import numpy as np
import math
import sys
from texttable import Texttable

class DataUtil(object):
  """
  提供数据相关的工具方法
  """
  @staticmethod
  def loadData(dataDirStr=os.path.dirname(__file__) + "/../../../data", dataUser=None):
      """
      使用Pandas包加载数据，参考：http://www.gregreda.com/2013/10/26/using-pandas-on-the-movielens-dataset/
      Args:
        `dataDir`: 数据集文件夹位置。绝对路径。
      Returns:
        `users, ratings, movies, full, Rm`:
           `users`: 用户信息的DataFrame, 索引: ['user_id', 'age', 'sex', 'occupation', 'zip_code']
           `ratings`: 用户与电影评分DataFrame, 索引: ['user_id', 'movie_id', 'rating', 'unix_timestamp']
           `movies`: 电影信息DataFrame，['movie_id', 'title', 'release_date', 'video_release_date', 'imdb_url']
           `full`: 所有电影join操作后的DataFrame, `(users join in ratings on user_id) join in  movies on movie_id`.
           `Rm`: 评分矩阵（下标都是从0开始），为了便于计算，由DataFrame转换而来。每一行代表一个用户对所有item的评分记录，每一列代表一个item被所有用户评分的记录。

      :param dataDir: datasets directory. Default is `<project_working_root>/data`
      :return `users, ratings, movies, full, Rm`: `users, ratings, movies` are DataFrames generated by `pandas`,
                                              `Rm` is rating matrix.(one row per user).
      """
      dataDir = os.path.abspath(dataDirStr)
      # pass in column names for each CSV
      u_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code']
      users = pd.read_csv(dataDir + '/ml-100k/u.user', sep='|', names=u_cols)

      # Loading user ratings.
      r_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']
      _dataUser = dataDir + '/ml-100k/ua.base'
      if(dataUser != None):
        _dataUser = dataUser
      ratings = pd.read_csv(_dataUser, sep='\t', names=r_cols)

      # the movies file contains columns indicating the movie's genres
      # let's only load the first five columns of the file with usecols
      m_cols = ['movie_id', 'title', 'release_date', 'video_release_date', 'imdb_url']
      movies = pd.read_csv(dataDir + '/ml-100k/u.item', sep='|', names=m_cols, usecols=range(5))

      movie_ratings = pd.merge(movies, ratings)
      full = pd.merge(movie_ratings, users)
      # We only need numeric matrix, pivot full data into pure rating matrix.(one row per user)
      # Converts data into rating matrix like bellow:
      #    m1 m2 m3 .... mN
      # u1  2  1  0  ...  2
      # u2  3  0  2  ...  4
      # u3  4  3  0  ...  5
      # ..     ...
      # uM  4  3  0  ...  5
      Rm = full.pivot(index='user_id', columns='movie_id', values='rating').fillna(0).values
      return users, ratings, movies, full, Rm

  @staticmethod
  def loadUserTestingData(dataDirStr=os.path.dirname(__file__) + "/../../../data", dataFile="/ml-100k/ua.test"):
    dataPath = os.path.abspath(dataDirStr) + dataFile
    r_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']
    ratings = pd.read_csv(dataPath, sep='\t', names=r_cols)
    # Converts to dict. {user_i: {item_j:ratings}}
    res = {}
    for index, row in ratings.iterrows():
      user_id = row['user_id']
      movie_id = row['movie_id']
      rating = row['rating']
      if res.has_key(user_id):
        pass
      else:
        res[user_id] = {}
      res[user_id][movie_id] = rating
    return res
# from ustb.cf.utils.cfutils import MatrixUtil, DataUtil
# ratings = DataUtil.loadUserTestingData(dataDirStr='/Users/qijianpeng/Documents/git/cfs/data', dataFile='/ml-100k/ua.test')

class MatrixUtil(object):
  """
  提供矩阵运算的工具方法
  """
  @staticmethod
  def dot_and(V1, V2):
    """计算同时存在元素值的点乘积，可认为两个矩阵相同位置都存在数值的计数
    `0`表示不存在，非`0`表示存在
    Suppose:
    V1 = [1, 2, 3, 0, 2]
         [2, 3, 0, 1, 0]
    V2 = [0, 1]
         [0, 1]
         [1, 2]
         [2, 5]
         [3, 0]'

    `dot_and(V1, V2)` returns number of common positive elements matrix:
    V = [2, 1]
        [1, 3].
    :param V1: N*M matrix
    :param V2: M*K matrix
    :return: matrix computed by dot_and way.
    """
    _V1 = (V1 > 0).astype(np.int)
    _V2 = (V2 > 0).astype(np.int)
    return np.dot(_V1, _V2)


import psycopg2

import warnings
warnings.filterwarnings('ignore')

import sys

# setting path
sys.path.append('.')

from connection import create_db_connection

def execute_sql(conn, sql):
    # Create a new cursor
    try:
        cur = conn.cursor()
        cur.execute(sql)
        updated_rows = cur.rowcount
        # Commit the changes to the database
        conn.commit()
        # Close cursor
        cur.close()
        return updated_rows
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
        #logging.error(error)
        return None

sql1 = """
        INSERT INTO public.hse_analytics_mape
        ( type_id,
          created_at,
          created_by)
        VALUES(1, '2022-12-02 00:00:00', 'PYTHON');

        INSERT INTO public.hse_analytics_mape
        ( type_id,
          created_at,
          created_by)
        VALUES(2, '2022-12-02 00:00:00', 'PYTHON');

       """

# Add the arguments to the parser
#ap = argparse.ArgumentParser()
#ap.add_argument("-y", "--year", required=True, help="Year data to truncate")

# Connect to database
# Exit program if not connected to database
conn = create_db_connection(section='postgresql_ml_hse_skk')
if conn == None:
    exit()
else:
    updated_rows = execute_sql(conn, sql1)
    if updated_rows != None:
        print("Initial rows has been inserted")


import math
from turtle import Turtle,Screen
import turtle as t
from prettytable import PrettyTable
import random
import colorgram
tur=Turtle()
sc=Screen()
tur.speed("fastest")
t.colormode(255)

def colour():
    r=random.randint(40,255)
    b=random.randint(40,255)
    g=random.randint(40,255)
    return (r,b,g)
# { this is polygon project
# def draw(sides):
#     for i in range(sides):
#        tur.forward(50)
#        tur.right(angle)
#        print(angle)
# sides=2
# for _ in range(50):
#     tur.color(colour())

#     sides+=1
#     angle=360/sides
#     draw(sides)

# }

#{ this is random walk project
# l1=[0,90,180,270]

# def random_walk():
#     for _ in range(150):
#         tur.forward(45)
#         tur.color(colour())
#         tur.pensize(10)
#         tur.setheading(random.choice(l1))

# random_walk()

#}

# {
# def spiral(k):
#  for _ in range(math.floor(360/k)):
#   tur.circle(110)
#   tur.color(colour())

#   cur_heading=tur.heading()
#   tur.setheading(cur_heading+k)
#   tur.speed("fastest")

# spiral(10)
# }

#dots game
# l2=[]
# colors=colorgram.extract("/Users/dattasandeepchoragudi/python/turtle/hirst.jpeg",20)
# for color in colors:
#     r=color.rgb.r
#     b=color.rgb.b
#     g=color.rgb.g
#     tup=(r,b,g)
#     l2.append(tup)

# tur.penup()
# tur.hideturtle()
# tur.setheading(225)
# tur.forward(300)
# tur.setheading(0)
# num=10

# for i in range(1,num+1):

#   for _ in range(10):
#    tur.forward(50)
#    tur.dot(23,random.choice(l2))

#   if num%10==0:
#     tur.setheading(90)
#     tur.forward(50)
#     tur.setheading(180)
#     tur.forward(500)
#     tur.setheading(0)

#turtle race
sc.setup(width=500,height=400)

guess=sc.textinput(title="Make your bet",prompt="Which turtle will win the race?")

a=Turtle(shape="turtle")
b=Turtle(shape="turtle")
c=Turtle(shape="turtle")
d=Turtle(shape="turtle")
e=Turtle(shape="turtle")
f=Turtle(shape="turtle")
g=Turtle(shape="turtle")

l=[a,b,c,d,e,f,g]
c=["violet","indigo","blue","green","yellow","orange","red"]
k=150
for _ in range(7):
    l[_].penup()
    l[_].goto(x=-240,y=k)
    l[_].color(c[_])
    k-=50

if guess:
    is_on=True

while is_on:
 for i in l:
    if i.xcor()>230:
        is_on=False
        win=i.pencolor()
        if win==guess:
            print(f"You have won!{win} turtle won thw race")
        else:
            print(f"You have lost!{win} turtle won thw race")

    i.forward(random.randint(0,15))

# a.goto(x=-240,y=150)
# b.goto(x=-240,y=100)
# c.goto(x=-240,y=50)
# d.goto(x=-240,y=0)
# e.goto(x=-240,y=-50)
# f.goto(x=-240,y=-100)

sc.exitonclick()

# table=PrettyTable()
# print(table)
# table.add_column("Pokemon Name",["Pikachu","Eevee","Calyrex"])
# table.add_column("Type",["Electric","Normal","Fairy"])
# table.align="r"

# print(table)


import pytest

from pyshell.arg.checker.argchecker import ArgChecker
from pyshell.arg.checker.default import DefaultChecker
from pyshell.arg.checker.integer import IntegerArgChecker
from pyshell.arg.checker.list import ListArgChecker
from pyshell.system.parameter.context import ContextParameter
from pyshell.system.parameter.environment import EnvironmentParameter
from pyshell.system.setting.context import CONTEXT_DEFAULT_CHECKER
from pyshell.system.setting.context import ContextGlobalSettings
from pyshell.system.setting.context import ContextLocalSettings
from pyshell.system.setting.context import ContextSettings
from pyshell.utils.constants import SETTING_PROPERTY_CHECKER
from pyshell.utils.constants import SETTING_PROPERTY_CHECKERLIST
from pyshell.utils.constants import SETTING_PROPERTY_DEFAULTINDEX
from pyshell.utils.constants import SETTING_PROPERTY_INDEX
from pyshell.utils.constants import SETTING_PROPERTY_READONLY
from pyshell.utils.constants import SETTING_PROPERTY_REMOVABLE
from pyshell.utils.constants import SETTING_PROPERTY_TRANSIENT
from pyshell.utils.constants import SETTING_PROPERTY_TRANSIENTINDEX
from pyshell.utils.exception import ParameterException

class TestContextLocalSettingsWithContextParameter(object):
    """
        This class uses ContextLocalSettings but the goal is to test the
        parent class ContextSettings
    """

    # setIndex with correct value
    def test_localSettings3(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(2)
        settings.tryToSetIndex(1)
        assert c.getSelectedValue() == 1
        settings.setIndex(2)
        assert c.getSelectedValue() == 2

    # setIndex with incorrect value
    def test_localSettings4(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,),
                             settings=settings)
        settings.tryToSetDefaultIndex(2)
        settings.tryToSetIndex(1)
        assert c.getSelectedValue() == 1
        with pytest.raises(ParameterException):
            settings.setIndex(23)

    # setIndex with invalid value
    def test_localSettings5(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,),
                             settings=settings)
        settings.tryToSetDefaultIndex(2)
        settings.tryToSetIndex(1)
        assert c.getSelectedValue() == 1
        with pytest.raises(ParameterException):
            settings.setIndex("plop")

    # setIndex with valid value and readonly
    def test_localSettings6(self):
        settings = ContextLocalSettings(read_only=True,
                                        checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)

        assert c.getSelectedValue() == 0
        settings.setIndex(2)
        assert c.getSelectedValue() == 2

    # tryToSetIndex with correct value
    def test_localSettings7(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(2)
        assert c.getSelectedValue() == 0
        settings.tryToSetIndex(3)
        assert c.getSelectedValue() == 3

    # tryToSetIndex with incorrect value
    def test_localSettings8(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(2)
        assert c.getSelectedValue() == 0
        settings.tryToSetIndex(23)
        assert c.getSelectedValue() == 0

    # tryToSetIndex with invalid value
    def test_localSettings9(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(2)
        assert c.getSelectedValue() == 0
        settings.tryToSetIndex("plop")
        assert c.getSelectedValue() == 0

    # tryToSetIndex with incorrect value and default value recomputing
    def test_localSettings10(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(2)
        settings.tryToSetIndex(1)
        assert c.getSelectedValue() == 1
        settings.default_index = 45
        settings.tryToSetIndex(80)
        assert c.getSelectedValue() == 1

    # tryToSetIndex with valid value and readonly
    def test_localSettings11(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(2)
        settings.setReadOnly(True)

        assert c.getSelectedValue() == 0
        settings.tryToSetIndex(3)
        assert c.getSelectedValue() == 3

    # tryToSetIndex, create a test to set default_index
    def test_localSettings12(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(1)
        settings.tryToSetIndex(3)
        assert c.getSelectedValue() == 3
        EnvironmentParameter.setValue(c, (11, 22, 33,))
        settings._setValuesSize(3)
        settings.tryToSetIndex(23)
        assert c.getSelectedValue() == 22

    def test_tryToSetIndexWithInvalidIndexAndCorruptedDefaults(self):
        settings = ContextSettings(checker=None)
        settings._setValuesSize(5)
        settings.index = 66
        settings.default_index = 23
        settings.tryToSetIndex(45)

        assert settings.getIndex() is 0
        assert settings.getDefaultIndex() is 0

    # test valid index
    def test_contextConstructor5(self):
        c = ContextParameter(value=(0, 1, 2, 3,))
        c.settings.tryToSetIndex(1)
        assert c.settings.getIndex() == 1

    # test invalid index
    def test_contextConstructor6(self):
        c = ContextParameter(value=(0, 1, 2, 3,))
        c.settings.tryToSetIndex(23)
        assert c.settings.getIndex() == 0

    # setSelectedValue with a valid value
    def test_localSettings13(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        c = ContextParameter(value=("aa", "bb", "cc", "dd",),
                             settings=settings)
        assert c.getSelectedValue() == "aa"
        c.setSelectedValue("cc")
        assert c.getSelectedValue() == "cc"

    # setSelectedValue with a valid value but inexisting
    def test_localSettings14(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        c = ContextParameter(value=("aa", "bb", "cc", "dd",),
                             settings=settings)
        assert c.getSelectedValue() == "aa"
        with pytest.raises(ParameterException):
            c.setSelectedValue("ee")

    # setSelectedValue with an invalid value
    def test_localSettings15(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        c = ContextParameter(value=("aa", "bb", "cc", "dd",),
                             settings=settings)
        assert c.getSelectedValue() == "aa"
        with pytest.raises(ParameterException):
            c.setSelectedValue(object())

    # setSelectedValue with valid value and readonly
    def test_localSettings16(self):
        settings = ContextLocalSettings(read_only=True,
                                        checker=DefaultChecker.getString())
        c = ContextParameter(value=("aa", "bb", "cc", "dd",),
                             settings=settings)
        assert c.getSelectedValue() == "aa"
        c.setSelectedValue("cc")
        assert c.getSelectedValue() == "cc"

    # setDefaultIndex with correct value
    def test_localSettings17(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",),
                         settings=settings)
        settings.tryToSetDefaultIndex(2)
        assert settings.getDefaultIndex() == 2
        settings.setDefaultIndex(1)
        assert settings.getDefaultIndex() == 1

    # setDefaultIndex with incorrect value
    def test_localSettings18(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",),
                         settings=settings)
        settings.tryToSetDefaultIndex(2)
        with pytest.raises(ParameterException):
            settings.setDefaultIndex(23)

    # setDefaultIndex with invalid value
    def test_localSettings19(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",),
                         settings=settings)
        settings.tryToSetDefaultIndex(2)
        with pytest.raises(ParameterException):
            settings.setDefaultIndex("plop")

    # setDefaultIndex with valid value and readonly
    def test_localSettings20(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",),
                         settings=settings)
        settings.tryToSetDefaultIndex(2)
        settings.setReadOnly(True)
        with pytest.raises(ParameterException):
            settings.setDefaultIndex(1)

    # tryToSetDefaultIndex with correct value
    def test_localSettings21(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",),
                         settings=settings)
        settings.tryToSetDefaultIndex(2)
        assert settings.getDefaultIndex() == 2
        settings.tryToSetDefaultIndex(1)
        assert settings.getDefaultIndex() == 1

    # tryToSetDefaultIndex with incorrect value
    def test_localSettings22(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",),
                         settings=settings)
        settings.tryToSetDefaultIndex(2)
        assert settings.getDefaultIndex() == 2
        settings.tryToSetDefaultIndex(100)
        assert settings.getDefaultIndex() == 2

    # tryToSetDefaultIndex with invalid value
    def test_localSettings23(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",),
                         settings=settings)
        settings.tryToSetDefaultIndex(2)
        assert settings.getDefaultIndex() == 2
        settings.tryToSetDefaultIndex("toto")
        assert settings.getDefaultIndex() == 2

    # tryToSetDefaultIndex with valid value and readonly
    def test_localSettings24(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",),
                         settings=settings)
        settings.tryToSetDefaultIndex(2)
        settings.setReadOnly(True)
        with pytest.raises(ParameterException):
            settings.tryToSetDefaultIndex(1)

    # tryToSetDefaultIndex, create a test to set default_index to zero
    def test_localSettings25(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getInteger())
        c = ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(3)
        assert settings.getDefaultIndex() == 3
        EnvironmentParameter.setValue(c, (11, 22, 33,))
        settings._setValuesSize(3)
        settings.tryToSetDefaultIndex(23)
        assert settings.getDefaultIndex() == 0

    # test valid default index
    def test_contextConstructor7(self):
        c = ContextParameter(value=(0, 1, 2, 3,))
        c.settings.tryToSetDefaultIndex(1)
        assert c.settings.getDefaultIndex() == 1

    # test invalid default index
    def test_contextConstructor8(self):
        c = ContextParameter(value=(0, 1, 2, 3,))
        c.settings.tryToSetDefaultIndex(42)
        assert c.settings.getDefaultIndex() == 0

    # test both invalid index AND invalid default index
    def test_contextConstructor9(self):
        c = ContextParameter(value=(0, 1, 2, 3,))
        c.settings.tryToSetDefaultIndex(42)
        c.settings.tryToSetIndex(23)
        assert c.settings.getDefaultIndex() == 0
        assert c.settings.getIndex() == 0

    # test reset
    def test_localSettings26(self):
        settings = ContextLocalSettings(checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",), settings=settings)
        settings.tryToSetDefaultIndex(2)
        settings.tryToSetIndex(1)
        assert settings.getDefaultIndex() == 2
        assert settings.getIndex() == 1
        settings.reset()
        assert settings.getDefaultIndex() == 2
        assert settings.getIndex() == 2

    # test getProperties
    def test_localSettings27(self):
        settings = ContextLocalSettings(removable=False)
        ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(3)
        settings.tryToSetIndex(2)
        settings.setReadOnly(True)
        props = {SETTING_PROPERTY_REMOVABLE: False,
                 SETTING_PROPERTY_READONLY: True,
                 SETTING_PROPERTY_CHECKER: 'any',
                 SETTING_PROPERTY_CHECKERLIST: True,
                 SETTING_PROPERTY_DEFAULTINDEX: 3}
        assert settings.getProperties() == props

    def test_cloneWithoutSource(self):
        s = ContextLocalSettings(checker=DefaultChecker.getInteger())
        ContextParameter(value=(0, 1, 2, 3,), settings=s)
        s.setDefaultIndex(2)
        s.setIndex(1)

        sc = s.clone()

        assert isinstance(sc, ContextLocalSettings)
        assert s is not sc
        assert hash(s) != hash(sc)  # because of the indexes
        assert sc.getDefaultIndex() == 0
        assert sc.getIndex() == 0
        assert sc.values_size == 0

class TestContextSettingsWithoutContextParameter(object):

    def test_setValuesSize(self):
        settings = ContextSettings(checker=None)
        settings._setValuesSize(23)
        assert settings.values_size is 23

    def test_isValidIndexNotAnInt(self):
        settings = ContextSettings(checker=None)
        settings._setValuesSize(5)
        assert not settings._isValidIndex("toto")

    def test_isValidIndexValidMinusInt(self):
        settings = ContextSettings(checker=None)
        settings._setValuesSize(5)
        assert not settings._isValidIndex(-20)
        assert not settings._isValidIndex(-6)

    def test_isValidIndexInvalidMinusInt(self):
        settings = ContextSettings(checker=None)
        settings._setValuesSize(5)
        assert settings._isValidIndex(-5)
        assert settings._isValidIndex(-1)

    def test_isValidIndexInvalidPositivIt(self):
        settings = ContextSettings(checker=None)
        settings._setValuesSize(5)
        assert not settings._isValidIndex(8000)
        assert not settings._isValidIndex(5)

    def test_isValidIndexValidPositivInt(self):
        settings = ContextSettings(checker=None)
        settings._setValuesSize(5)
        assert settings._isValidIndex(4)
        assert settings._isValidIndex(0)

    # None checker
    def test_contextConstructor1(self):
        settings = ContextSettings(checker=None)
        assert settings.isListChecker()
        assert settings.getChecker().getMinimumSize() == 1
        assert settings.getChecker().getMaximumSize() is None

        sub_checker = settings.getChecker().checker
        assert sub_checker.__class__.__name__ == ArgChecker.__name__
        assert isinstance(sub_checker, ArgChecker)

    # arg checker
    def test_contextConstructor2(self):
        settings = ContextSettings(checker=DefaultChecker.getInteger())
        assert settings.isListChecker()
        assert settings.getChecker().getMinimumSize() == 1
        assert settings.getChecker().getMaximumSize() is None

        assert isinstance(settings.getChecker().checker, IntegerArgChecker)

    # arg checker with min size of 0
    def test_contextConstructor2b(self):
        with pytest.raises(ParameterException):
            checker = ArgChecker(minimum_size=0, maximum_size=0)
            ContextSettings(checker=checker)

    # list checker + #list checker with size not adapted to context
    def test_contextConstructor3(self):
        lt = ListArgChecker(DefaultChecker.getInteger(), 3, 27)
        settings = ContextSettings(checker=lt)
        assert settings.isListChecker()
        assert settings.getChecker().getMinimumSize() == 1
        assert settings.getChecker().getMaximumSize() == 27
        assert isinstance(settings.getChecker().checker, IntegerArgChecker)

    def test_setCheckerNoneWithoutPreviousChecker(self):
        settings = ContextSettings()
        checker = settings.getChecker()

        settings.setChecker(checker=None)

        checker2 = settings.getChecker()

        assert checker is checker2

    def test_setCheckerNoneWithPreviousChecker(self):
        original_checker = ListArgChecker(DefaultChecker.getString())
        settings = ContextSettings(checker=original_checker)
        checker = settings.getChecker()
        assert checker is original_checker

        settings.setChecker(checker=None)

        checker2 = settings.getChecker()

        assert checker is not checker2
        assert checker2 is CONTEXT_DEFAULT_CHECKER

    def test_setCheckerNotAList(self):
        settings = ContextSettings()
        checker = DefaultChecker.getString()
        settings.setChecker(checker=checker)
        assert settings.isListChecker()
        assert settings.getChecker().checker is checker

    def test_setCheckerListWithMinSizeBiggerThanZero(self):
        settings = ContextSettings()
        original_checker = ListArgChecker(checker=DefaultChecker.getString(),
                                          minimum_size=14,
                                          maximum_size=56)
        settings.setChecker(original_checker)

        new_checker = settings.getChecker()

        assert new_checker is original_checker
        assert new_checker.getMinimumSize() == 1
        assert new_checker.getMaximumSize() == 56

    def test_setCheckerListWithItemLargerThanOne(self):
        settings = ContextSettings()
        original_sub_checker = ArgChecker()
        original_sub_checker.setSize(minimum_size=5, maximum_size=5)
        original_checker = ListArgChecker(checker=original_sub_checker,
                                          minimum_size=5)
        with pytest.raises(ParameterException):
            settings.setChecker(original_checker)

    def test_setCheckerArgLargerThanOne(self):
        settings = ContextSettings()
        original_checker = ArgChecker()
        original_checker.setSize(minimum_size=5, maximum_size=5)

        with pytest.raises(ParameterException):
            settings.setChecker(original_checker)

    def test_setListCheckerTrue(self):
        settings = ContextSettings()
        assert settings.isListChecker()
        settings.setListChecker(True)
        assert settings.isListChecker()

    def test_setListCheckerFalse(self):
        settings = ContextSettings()
        assert settings.isListChecker()
        with pytest.raises(ParameterException):
            settings.setListChecker(False)
        assert settings.isListChecker()

    def test_cloneWithoutSource(self):
        zs = ContextSettings(checker=DefaultChecker.getInteger())
        zsc = zs.clone()

        assert isinstance(zsc, ContextSettings)
        assert zs is not zsc
        assert hash(zs) == hash(zsc)
        assert zs.getChecker() is zsc.getChecker()
        assert zsc.values_size == 0

class TestContextLocalSettingsWithoutContextParameter(object):
    def test_constructor1(self):
        lcs = ContextLocalSettings(read_only=False, removable=False)
        assert not lcs.isReadOnly()
        assert not lcs.isRemovable()

    def test_constructor2(self):
        lcs = ContextLocalSettings(read_only=True, removable=True)
        assert lcs.isReadOnly()
        assert lcs.isRemovable()

    def test_setTransientIndex(self):
        lcs = ContextLocalSettings()
        assert lcs.isTransientIndex()
        with pytest.raises(ParameterException):
            lcs.setTransientIndex(False)
        assert lcs.isTransientIndex()

    def test_cloneWithoutSource(self):
        s = ContextLocalSettings(checker=DefaultChecker.getInteger())
        sc = s.clone()

        assert isinstance(sc, ContextLocalSettings)
        assert s is not sc
        assert hash(s) == hash(sc)
        assert sc.values_size == 0

    def test_getGlobalFromLocal(self):
        checker = DefaultChecker.getInteger()
        ls = ContextLocalSettings(read_only=True,
                                  removable=False,
                                  checker=checker)

        gs = ls.getGlobalFromLocal()

        assert type(gs) is ContextGlobalSettings
        assert gs.isReadOnly()
        assert not gs.isRemovable()
        assert gs.getChecker() is ls.getChecker()

class TestContextGlobalSettingsWithContextParameter(object):

    # test transientIndex
    def test_contextConstructor10(self):
        settings = ContextGlobalSettings(transient_index=False)
        ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetIndex(2)
        assert not settings.isTransientIndex()
        props = {SETTING_PROPERTY_REMOVABLE: True,
                 SETTING_PROPERTY_READONLY: False,
                 SETTING_PROPERTY_TRANSIENT: False,
                 SETTING_PROPERTY_CHECKER: 'any',
                 SETTING_PROPERTY_CHECKERLIST: True,
                 SETTING_PROPERTY_TRANSIENTINDEX: False,
                 SETTING_PROPERTY_DEFAULTINDEX: 0,
                 SETTING_PROPERTY_INDEX: 2}
        assert settings.getProperties() == props

    def test_contextConstructor10b(self):
        settings = ContextGlobalSettings(transient_index=True)
        ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetIndex(2)
        assert settings.isTransientIndex()
        props = {SETTING_PROPERTY_REMOVABLE: True,
                 SETTING_PROPERTY_READONLY: False,
                 SETTING_PROPERTY_TRANSIENT: False,
                 SETTING_PROPERTY_CHECKER: 'any',
                 SETTING_PROPERTY_CHECKERLIST: True,
                 SETTING_PROPERTY_TRANSIENTINDEX: True,
                 SETTING_PROPERTY_DEFAULTINDEX: 0}
        assert settings.getProperties() == props

    # __init__ test each properties, True
    def test_globalSettings1(self):
        settings = ContextGlobalSettings(read_only=True,
                                         removable=True,
                                         transient=True,
                                         transient_index=True,
                                         checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",), settings=settings)
        assert settings.isReadOnly()
        assert settings.isRemovable()
        assert settings.isTransient()
        assert settings.isTransientIndex()

    # __init__ test each properties, False
    def test_globalSettings2(self):
        settings = ContextGlobalSettings(read_only=False,
                                         removable=False,
                                         transient=False,
                                         transient_index=False,
                                         checker=DefaultChecker.getString())
        ContextParameter(value=("aa", "bb", "cc", "dd",), settings=settings)
        assert not settings.isReadOnly()
        assert not settings.isRemovable()
        assert not settings.isTransient()
        assert not settings.isTransientIndex()

    # test getProperties not transient index
    def test_globalSettings6(self):
        settings = ContextGlobalSettings(transient_index=False)
        ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(3)
        settings.tryToSetIndex(2)
        props = {SETTING_PROPERTY_REMOVABLE: True,
                 SETTING_PROPERTY_READONLY: False,
                 SETTING_PROPERTY_TRANSIENT: False,
                 SETTING_PROPERTY_CHECKER: 'any',
                 SETTING_PROPERTY_CHECKERLIST: True,
                 SETTING_PROPERTY_TRANSIENTINDEX: False,
                 SETTING_PROPERTY_DEFAULTINDEX: 3,
                 SETTING_PROPERTY_INDEX: 2}
        assert settings.getProperties() == props

    # test getProperties transient index
    def test_globalSettings7(self):
        settings = ContextGlobalSettings(transient_index=True)
        ContextParameter(value=(0, 1, 2, 3,), settings=settings)
        settings.tryToSetDefaultIndex(3)
        settings.tryToSetIndex(2)
        props = {SETTING_PROPERTY_REMOVABLE: True,
                 SETTING_PROPERTY_READONLY: False,
                 SETTING_PROPERTY_TRANSIENT: False,
                 SETTING_PROPERTY_CHECKER: 'any',
                 SETTING_PROPERTY_CHECKERLIST: True,
                 SETTING_PROPERTY_TRANSIENTINDEX: True,
                 SETTING_PROPERTY_DEFAULTINDEX: 3}
        assert settings.getProperties() == props

    def test_cloneWithoutSource(self):
        s = ContextGlobalSettings(checker=DefaultChecker.getInteger())
        s.setTransientIndex(True)
        ContextParameter(value=(0, 1, 2, 3,), settings=s)
        s.setDefaultIndex(2)
        s.setIndex(1)

        sc = s.clone()

        assert isinstance(sc, ContextGlobalSettings)
        assert s is not sc
        assert hash(s) != hash(sc)  # because of the indexes
        assert sc.getDefaultIndex() == 0
        assert sc.getIndex() == 0
        assert sc.values_size == 0
        assert s.isTransientIndex()

class TestContextGlobalSettingsWithoutContextParameter(object):
    # test setTransientIndex in readonly mode
    def test_globalSettings3(self):
        settings = ContextGlobalSettings(read_only=True,
                                         checker=DefaultChecker.getString())
        with pytest.raises(ParameterException):
            settings.setTransientIndex(True)

    # test setTransientIndex with invalid bool
    def test_globalSettings4(self):
        settings = ContextGlobalSettings(checker=DefaultChecker.getString())
        with pytest.raises(ParameterException):
            settings.setTransientIndex("plop")

    # test setTransientIndex with valid bool
    def test_globalSettings5(self):
        settings = ContextGlobalSettings(checker=DefaultChecker.getString())
        assert not settings.isTransientIndex()
        settings.setTransientIndex(True)
        assert settings.isTransientIndex()

    def test_cloneWithoutSource(self):
        s = ContextGlobalSettings(checker=DefaultChecker.getInteger())
        s.setTransientIndex(True)
        sc = s.clone()

        assert isinstance(sc, ContextGlobalSettings)
        assert s is not sc
        assert hash(s) == hash(sc)
        assert sc.values_size == 0
        assert sc.isTransientIndex()

    def test_getLocalFromGlobal(self):
        checker = DefaultChecker.getInteger()
        gs = ContextGlobalSettings(read_only=True,
                                   removable=False,
                                   transient=True,
                                   transient_index=True,
                                   checker=checker)

        ls = gs.getLocalFromGlobal()

        assert type(ls) is ContextLocalSettings
        assert ls.isReadOnly()
        assert not ls.isRemovable()
        assert ls.getChecker() is gs.getChecker()


'''
in degree array
Kahn's Algorithm
'''

from collections import deque

def _get_adj_list(n, edges):
    adj_list = [[] for _ in range(n)]
    in_degree = [0] * n
    for from_v, to_v in edges:
        adj_list[from_v].append(to_v)
        in_degree[to_v] += 1
    return adj_list, in_degree

def topo_sort_bfs(n, edges):
    adj_list, in_degree = _get_adj_list(n, edges)
    result = []
    queue = deque()
    _fill_queue(queue, in_degree)
    while queue:
        current = queue.popleft()
        result.append(current)
        _update_indegree(current, adj_list, in_degree)
        _fill_queue(queue, in_degree)
    if _is_cycle_present(in_degree):
        return []
    else:
        return result

def _is_cycle_present(in_degree):
    for num in in_degree:
        if num >= 0:
            return True
    return False

def _update_indegree(vertex, adj_list, in_degree):
    for adj_vertex in adj_list[vertex]:
        in_degree[adj_vertex] -= 1

def _fill_queue(queue, in_degree):
    for idx in range(len(in_degree)):
        if in_degree[idx] == 0:
            queue.append(idx)
            in_degree[idx] -= 1

n = 6
edges = [[5, 0], [4, 0], [5, 2], [4, 1], [2, 3], [3, 1]]
print(topo_sort_bfs(n, edges))

# cycle
n = 4
edges = [[0, 1], [1, 2], [2, 3], [3, 1]]
print(topo_sort_bfs(n, edges))


import argparse
import sys

parser = argparse.ArgumentParser(
        description="Train a RL net to play in an OpenAI Gym environment.",
        allow_abbrev=False
    )
parser.add_argument("-p", "--parameters", help="Path to JSON parameters file.")
parser.add_argument("--offline_train", action='store_true')
raw_args = sys.argv[1:]
args = parser.parse_args(raw_args)
print(raw_args)
print(args)


import cv2
import numpy as np
import matplotlib.pyplot as plt
im=cv2.imread('ff.jpg')
h,w,c=im.shape

rim=np.zeros([h,w,3])
gim=np.zeros([h,w,3])
bim=np.zeros([h,w,3])

for i in range (h):
    for j in range(w):
        for k in range(3):
            rim[i][j][k]=im[i][j][2]
            gim[i][j][k]=im[i][j][1]
            bim[i][j][k]=im[i][j][0]

rim = rim.astype(np.uint8)
gim = gim.astype(np.uint8)
bim = bim.astype(np.uint8)

fig = plt.figure(figsize=(18, 18))
pltX = 1
pltY = 4
fig.add_subplot(pltX, pltY, 1)
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.title(" ORIGINAL IMAGE ")

fig.add_subplot(pltX, pltY, 2)
plt.imshow(cv2.cvtColor(rim,cv2.COLOR_BGR2RGB ))
plt.axis('off')
plt.title(" RED CHANNEL IMAGE ")
fig.add_subplot(pltX, pltY, 3)
plt.imshow(cv2.cvtColor(gim,cv2.COLOR_BGR2RGB ))
plt.axis('off')
plt.title(" GREEN CHANNEL IMAGE ")
fig.add_subplot(pltX, pltY, 4)
plt.imshow(cv2.cvtColor(bim,cv2.COLOR_BGR2RGB ))
plt.axis('off')
plt.title(" BLUE CHANNEL IMAGE ")
fig.show()
fig.waitforbuttonpress()


# 1. Python raises an exception on an error
# 2. An exception is an event that can modify the flow of control of the program
# 3. The default exception handler is to stop the program and print an error message

# Default Exception Handler
def fetcher(obj, index):
    return obj[index]

x = 'spam'
print(fetcher(x, 3))
# Raises IndexError
# print(fetcher(x, 4))
print()

# Catching Exceptions
try:
    fetcher(x, 4)
except IndexError:
    print('got exception')
print()

def catcher():
    try:
        fetcher(x, 4)
    except IndexError:
        print('got exception')
    print('continuing')
catcher()
print()

# Raising Exceptions
try:
    raise IndexError
except IndexError:
    print('got exception')

# Uncaught exceptions are propagated to the top-level default handler
#raise IndexError

# assert can be used to trigger (conditional) exceptions too
#assert False, 'Nobody expects the Spanish Inquisition!'
print()

# User-Defined Exceptions
class AlreadyGotOne(Exception):
    pass

def grail():
    raise AlreadyGotOne()

try:
    grail()
except AlreadyGotOne:
    print('got an exception')
print()

class Career(Exception):
    def __str__(self):
        return 'So I became a waiter...'

#raise Career()

# Termination Actions
try:
    fetcher(x, 3)
finally:
    print('after fetch')
print()

def after():
    try:
        fetcher(x, 3)
    finally:
        print('after fetch')
    print('after try?')
after()

with open('resources/lumberjack.txt', 'w') as f:
    f.write('The larch!\n')
print('file written')


class Payload(object):
    def __init__(self, number: int, shortName: str, field: int):
        self.number = number
        self.shortName = shortName
        self.field = field

class ScoringResponse(object):
    def __init__(self, updateTime: int, updateType: str, payload: Payload):
        self.updateTime = updateTime
        self.updateType = updateType
        self.payload = payload


from persuasion4good.tasks.finetune import FinetuningTask
from conftest import spark
from fixtures.fixtures import (
    feature_engineering_task,
    export_dataset_task,
    get_data_task,
    config,
    csv_rows
)

def test_module():

    task = FinetuningTask()
    assert task


#
# @rajp
#

from utils import *

def latency ():
    # Step 4 of 5: Compare model latencies
    SETUP_CODE = '''
import os
import sys
cwd = os.getcwd()
sys.path.insert(0, cwd+"/../intro/")
checkpoint = "model_20221108_223519_epoch=9.pth"
import torch
from lab5 import LeNet5
device = torch.device("cpu")
model_fp32 = LeNet5().to(device)
model_fp32.load_state_dict(torch.load(cwd+"/../intro/"+checkpoint))
model_int8 = torch.quantization.quantize_dynamic(model=model_fp32,
                        qconfig_spec={torch.nn.Conv2d, torch.nn.AvgPool2d, torch.nn.Linear},
                        dtype=torch.qint8)
some_input = torch.rand(1, 3, 32, 32)
    '''
    TEST_CODE = '''
model_fp32.forward(some_input)
    '''
    TEST_CODE_INT8 = '''
model_int8.forward(some_input)
    '''

    time_fp32 = timeit.repeat(setup=SETUP_CODE, stmt=TEST_CODE_INT8, repeat=3, number=10000)
    time_int8 = timeit.repeat(setup=SETUP_CODE, stmt=TEST_CODE_INT8, repeat=3, number=10000)

    print("time_fp32: ", time_fp32)
    print("time_int8: ", time_int8)
    print("\n{0:.2f} times faster".format(time_fp32[1]/time_int8[1]))

def ptdq():
    """ post training dynamic quantization
    https://pytorch.org/tutorials/recipes/recipes/dynamic_quantization.html
    https://pytorch.org/tutorials/advanced/dynamic_quantization_tutorial.html
    """
    global cwd, checkpoint

    # Step 1 of 5: Setup
    model_fp32 = LeNet5().to(device)
    model_fp32.load_state_dict(torch.load(cwd+"/../intro/"+checkpoint))
    print_model_parameters(model_fp32)
    # torch summary only works on GPU an with current version of pytorch, dynamic quant does not work on gpu
    #torchsummary.summary(model_fp32, (3,32,32))

    # Step 2 of 5: Quantization
    model_int8 = torch.quantization.quantize_dynamic(model=model_fp32,
                        qconfig_spec={torch.nn.Conv2d, torch.nn.AvgPool2d, torch.nn.Linear},
                        dtype=torch.qint8)
    print_model_parameters(model_int8)

    # Step 3 of 5: Compare model sizes
    size_fp32 = print_model_size(model_fp32, label="model_fp32")
    size_int8 = print_model_size(model_int8, label="model_int8")
    print("\n{0:.2f} times smaller".format(size_fp32/size_int8))
    return (model_fp32, model_int8)

if __name__ == "__main__":
    (model_fp32, model_int8) = ptdq()

    (trainDataSet, trainDataLoader, testDataSet, testDataLoader, classes) = load_data("./../intro/data/cifar10/", writer=None)

    latency()

    (vloss_fp32, acc_fp32) = accuracy(model_fp32, testDataLoader, withLoss=True)
    (vloss_int8, acc_int8) = accuracy(model_int8, testDataLoader, withLoss=True)
    print ("LOSSES:   Model-1: ", vloss_fp32, "Model-2: ", vloss_int8)
    print ("ACCURACY: Model-1: ", acc_fp32, "Model-2: ", acc_int8)

    """
        LOSSES:   Model-1:  tensor(3284.2734, grad_fn=<AddBackward0>) Model-2:  tensor(3282.9954)
        ACCURACY: Model-1:  0.5942000000000001 Model-2:  0.5920000000000001
    """


#This script returns the future value of an investment, calculated using compound interest.

#Set Inputs
presentValue = float((input("Enter the initial investment value:")))
rate = float(input("Enter the interest rate according to the period of compounding (i.e. 0.02):"))
numberOfPeriods = int(input("Enter the number of periods for the investment:"))

#Calc
#FV = (PV * (1+i)ˆn)
futureValue = presentValue * (1 + rate) ** numberOfPeriods

#Return
print(futureValue)


import os
import sys
import unreal

def _get_iograft_python_dir():
    major_version = sys.version_info[0]
    minor_version = sys.version_info[1]
    return "python{}{}".format(major_version, minor_version)

def _get_iograft_environment_name():
    # First try to get the environment name from the IOGRAFT_ENV environment
    # variable.
    environment_name = os.getenv("IOGRAFT_ENV")
    if environment_name is not None:
        return environment_name

    # Otherwise, get the name from the Unreal settings.
    environment_name = unreal.IograftBPLibrary.get_iograft_environment_name()
    return environment_name

def initialize_iograft():
    iograft_root = unreal.IograftBPLibrary.get_iograft_install_root()
    if not iograft_root or not os.path.exists(iograft_root):
        unreal.log_error("iograft install root not set in settings."
                         " Cannot initialize iograft.")
        return

    # Ensure iograft modules are on PYTHONPATH
    python_dir = _get_iograft_python_dir()
    iograft_python_path = os.path.join(iograft_root, python_dir)
    if iograft_python_path not in sys.path:
        sys.path.append(iograft_python_path)

    # Get the environment name to initialize iograft with.
    environment_name = _get_iograft_environment_name()
    if not environment_name:
        unreal.log_error("iograft environment name is not set. Cannot"
                         " initialize iograft.")
        return

    unreal.log(
        "Initializing iograft with environment: '{}'".format(environment_name))

    import iograft
    try:
        iograft.InitializeEnvironment(environment_name)
    except KeyError as e:
        unreal.log_warning(
            "Failed to initialize iograft environment: '{}': {}".format(
                                                        environment_name, e))

    # Initialize the CoreEngine for executing nodes interactively inside
    # Unreal. Importing the core engine module here registers the iograft
    # engine classes.
    import iograft_core_engine

initialize_iograft()


import torch.optim as optim
import numpy as np
from pyemd import emd
import torch.nn as nn
from scipy.spatial.distance import cdist
from sklearn.neighbors import kneighbors_graph
import torch.nn.functional as F
import sys
sys.path.append('..')
import torch
from contrast.losses import KNNOverlapLoss, CKALoss, PredictionLoss, ConfidenceLoss

def kl_div_loss(P, Q):
    # Check if the input contains NaN, infinity, or very large values
    if not torch.isfinite(P).all() or not torch.isfinite(Q).all() or not torch.max(torch.abs(P)).item() < np.finfo(np.float32).max or not torch.max(torch.abs(Q)).item() < np.finfo(np.float32).max:
        # Replace NaN, infinity, or very large values with zeros
        P[~torch.isfinite(P) | (torch.abs(P) >= np.finfo(np.float32).max)] = 0
        Q[~torch.isfinite(Q) | (torch.abs(Q) >= np.finfo(np.float32).max)] = 0

    kl_divergence = torch.sum(P * torch.log(P / Q))

    # Calculate KL divergence between Q and P
    kl_divergence += torch.sum(Q * torch.log(Q / P))

    # Return the average KL divergence
    return kl_divergence.mean()

def gaussian_kernel(x1, x2, sigma=1.0):
    x1 = x1.unsqueeze(1)  # shape: (n1, 1, d)
    x2 = x2.unsqueeze(0)  # shape: (1, n2, d)
    dist = torch.sum((x1 - x2) ** 2, dim=-1)  # shape: (n1, n2)
    return torch.exp(-dist / (2 * sigma ** 2))

def mmd_loss(x1, x2, kernel=gaussian_kernel, sigma=1.0):
    n1, n2 = x1.size(0), x2.size(0)

    k11 = kernel(x1, x1, sigma=sigma).sum() / (n1 * (n1 - 1))
    k22 = kernel(x2, x2, sigma=sigma).sum() / (n2 * (n2 - 1))
    k12 = kernel(x1, x2, sigma=sigma).sum() / (n1 * n2)

    return k11 + k22 - 2 * k12

def earth_movers_distance(X, Y, k=5):
    X, Y = X.detach().numpy(), Y.detach().numpy()

    # Compute KNN graphs
    X_knn_graph = kneighbors_graph(X, k, mode='distance')
    Y_knn_graph = kneighbors_graph(Y, k, mode='distance')

    # Convert to dense NumPy arrays
    X_knn_matrix = X_knn_graph.toarray()
    Y_knn_matrix = Y_knn_graph.toarray()

    # Calculate the EMD between the KNN distance matrices
    distance_matrix = cdist(X_knn_matrix, Y_knn_matrix)
    first_histogram = np.ones(X_knn_matrix.shape[0]) / X_knn_matrix.shape[0]
    second_histogram = np.ones(Y_knn_matrix.shape[0]) / Y_knn_matrix.shape[0]

    loss = emd(first_histogram, second_histogram, distance_matrix)
    loss_tensor = torch.tensor(loss, requires_grad=True)

    return loss_tensor

def frobenius_norm_loss(predicted, target):
    return torch.norm(predicted - target, p='fro') / predicted.numel()

def prediction_loss(trans_X, Y):

    target_output = tar_provider.get_pred(TAR_EPOCH, Y.detach().numpy())
    # tar_output = self.get_pred(self.TAR_EPOCH, adjusted_input, self.tar_provider.content_path, self.tar_model)
    ref_output = tar_provider.get_pred(TAR_EPOCH, trans_X.detach().numpy())

    loss_ref_output = F.mse_loss(torch.tensor(ref_output), torch.tensor(target_output))
    loss_Rep = F.mse_loss(trans_X, Y)

    # loss = loss_tar_output + loss_Rep + self.alpha_for_pred_ref * loss_ref_output
    loss =  loss_Rep + 1 * loss_ref_output
    return loss

# Define hyperparameters
num_epochs = 10
batch_size = 100
learning_rate = 1e-4

# Define the loss function and the optimizer
criterion = nn.MSELoss()
optimizer = optim.Adam(autoencoder.parameters(), lr=learning_rate,weight_decay=1e-5)

alpha = 1 # weight for topological loss, adjust this according to your requirements

autoencoder = SimpleAutoencoder(input_dim,output_dim)
########### load pre autoencoder
checkpoint = torch.load("/home/yifan/projects/deepdebugertool/DLVisDebugger/AlignVisAutoEncoder/checkpoints/cak_1v1.pth")
autoencoder.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])

######### train sample + generated boundary sample's => input  #############
from AlignVisAutoEncoder.data_loader import DataLoaderInit

indicates = np.random.choice(np.arange(50000), size=5000, replace=False)

input_X = np.concatenate((ref_provider.train_representation(REF_EPOCH)[indicates], ref_features[indices]),axis=0)
input_Y = np.concatenate((tar_provider.train_representation(TAR_EPOCH)[indicates], tar_features[indices]),axis=0)
data_loader_b = DataLoaderInit(input_X, input_Y, batch_size)
dataloader_b = data_loader_b.get_data_loader()

# Training loop
for epoch in range(num_epochs):
    # Initialize a list to store the predictions of unlabelled data
    unlabelled_preds = []
    for data_X, data_Y in dataloader_b: # Assuming you have a DataLoader instance with paired data (X, Y)
        # Zero the gradients
        optimizer.zero_grad()

        # Forward pass (encoding Y and decoding to X's space)
        transformed_Y = autoencoder.encoder(data_Y)
        recon_X = autoencoder.decoder(transformed_Y)
        transformed_X = autoencoder.decoder(data_X)

        ##### knn loss
        knn_overlap_loss = KNNOverlapLoss(k=15)

        knn_loss_encoder = knn_overlap_loss(input=transformed_Y, target=data_Y)

        knn_loss_decoder = knn_overlap_loss(input=recon_X, target=data_Y)

        # knn_loss = knn_overlap_loss(input=transformed_X, target=data_Y)
        ###### make ref' s distribution like tar
        mmd_loss_v = mmd_loss(recon_X,data_Y)
        # dis_loss = 0

        loss_f_decoder = knn_loss_decoder
        loss_f_encoder = knn_loss_encoder

        pred_loss = prediction_loss(recon_X, data_Y)

        #### CKA loss
        cka_loss_f = CKALoss(gamma=None, alpha=1e-8)
        cka_loss = cka_loss_f(data_Y,transformed_Y,recon_X)

        loss = loss_f_decoder + loss_f_encoder + pred_loss + cka_loss + 20 * mmd_loss_v

        # Backward pass
        loss.backward()

        # Update the weights
        optimizer.step()

    # Print the loss for each epoch
    print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}, Loss decoder: {loss_f_decoder.item():.4f},Loss encoder: {loss_f_encoder.item():.4f},pred_loss,{pred_loss.item():.4f},CKA,{cka_loss.item():.4f},mmd_loss:{mmd_loss_v}')

torch.save({
    'epoch': TAR_EPOCH,
    'model_state_dict': autoencoder.state_dict(),
    'optimizer_state_dict': optimizer.state_dict(),
    'loss': loss
}, "/home/yifan/projects/deepdebugertool/DLVisDebugger/AlignVisAutoEncoder/checkpoints/drop_only_boundary.pth")


import re
import socket
import threading

from FFmpegVideoCapture import FFmpegVideoCapture

from lorenzo.VideoStream import VideoStream

class XiaoYiActionCamera:
    STREAM_URL = 'rtsp://%s:554/live'

    DEFAULT_IP_ADDRESS = '192.168.42.1'
    DEFAULT_PORT = 7878

    DEFAULT_STREAM_WIDTH = 640
    DEFAULT_STREAM_HEIGHT = 480

    def __init__(
            self,
            ip_address=DEFAULT_IP_ADDRESS,
            stream_width=DEFAULT_STREAM_WIDTH,
            stream_height=DEFAULT_STREAM_HEIGHT
    ):
        self.ip_address = ip_address
        self.stream_width = stream_width
        self.stream_height = stream_height

    def open_stream(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.connect((self.ip_address, XiaoYiActionCamera.DEFAULT_PORT))

        server.send(b'{"msg_id":257,"token":0}')

        data = str(server.recv(512))
        while "rval" not in data:
            data = str(server.recv(512))
        token = re.findall('"param": (.+) }', data)[0]

        stop_stream = bytes('{"msg_id":260,"token":%s}' % token, encoding='ascii')
        server.send(stop_stream)

        start_stream = bytes('{"msg_id":259,"token":%s,"param":"none_force"}' % token, encoding='ascii')
        server.send(start_stream)

        def drain_camera_socket():
            ignored = server.recv(512)
            while ignored:
                ignored = server.recv(512)

        drain = threading.Thread(target=drain_camera_socket, args=())
        drain.setDaemon(True)
        drain.start()

        return VideoStream(FFmpegVideoCapture(
            XiaoYiActionCamera.STREAM_URL % self.ip_address,
            self.stream_width,
            self.stream_height,
            'bgr24'
        ))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 22 18:50:27 2018

@author: victor
"""
import numpy as np
import matplotlib.pyplot as plt

'''
DESCRIPTION

PrimeGen TAKES IN A POSITIVE NUMBER, n, AND GENERATES ALL THE PRIMES BETWEEN 1
AND n, INCLUDING n, AND CHECKS IF IT IS A PRIME USING PrimeCheck1. PrimeGen2
DOES THE SAME BUT WITH PrimeCheck2.

PrimeCheck1 TAKES IN A REAL NUMBER, someN, AND CHECKS IF IT IS A PRIME BY BRUTE
FORCE. PrimeCheck2 DOES THE SAME BUT UP TO THE SQUARE ROOT OF someN. HERE'S
THE PROOF:

https://stackoverflow.com/questions/5811151/why-do-we-check-up-to-the-
square-root-of-a-prime-number-to-determine-if-it-is-pr

PARAMETERS FOR...

PrimeCheck
    someN - LITERALLY SOME INTEGER. IT TAKES ANY INTEGER AND CHECKS WHETHER
    IT IS A PRIME OR NOT. SINCE WE ALREADY CHECK IF SAID NUMBER'S BIGGER THAN 1

    opt_p_check - THIS IS A BOOLEAN. IF IT'S TRUE, OR NOT IN AT ALL, THEN IT'LL
    USE THE OPTIMIZED METHOD. OTHERWISE, IT USES THE REGULAR METHOD.

PrimeGen
    n - THIS NUMBER IS OUR UP-TO VALUE TO CHECK FOR PRIMES.

    opt_p_check - THIS IS A BOOLEAN INPUT. TRUE BY DEFAULT, IT'LL USE
    PrimeCheck2. ELSE, IT'LL USE PrimeCheck1.

PrimePlot
    SAME AS PrimeGen

DESCRIPTION
'''

# HELPER FUNCTIONS

def PrimeCheck(someN, opt_p_check=True):
    if opt_p_check:
        up_to = int(np.sqrt(someN)) + 1
    else:
        up_to = someN
    for kk in range(2, up_to):
        if someN % kk == 0:
            return False
    return True

# HELPER FUNCTIONS

# TABLE OF CONTENTS --------------------------------------------------------- #
#   1
#       1.1
#       1.2

# TABLE OF CONTENTS --------------------------------------------------------- #

# CONTENT ------------------------------------------------------------------- #
#   1
#       1.1

# CONTENT ------------------------------------------------------------------- #

def PrimeGen(n, opt_p_check=True):
    if n < 2:
        strg = 'Prime numbers are natural numbers greater than 1.'
        print(strg)
        return 0
    if n == 2:
        return [2]
    primeLst = [2]
    for ii in range(3, n + 1, 2):
        if PrimeCheck(ii, opt_p_check):
            primeLst.append(ii)
    return primeLst

def PrimePlot(n, opt_p_check=True, rtrn_bool=False):
    primeLst = PrimeGen(n, opt_p_check)
#                        +--> FROM THE VALUE 1...
#                        |           +--> TO SIZE OF LIST...
#                       _|_ _________|________
    nthPrime = np.arange(1, len(primeLst) + 1)
    plt.plot(nthPrime, primeLst)
    plt.grid()
    plt.ylabel('Prime')
    plt.xlabel('Index of prime')
    plt.title('Prime plot')
    if rtrn_bool:
        return primeLst


from lxml import html

xx_uri = "http://www.cwl.gov.cn/kjxx/ssq/kjgg/"
data_uri = "http://www.cwl.gov.cn/cwl_admin/kjxx/findDrawNotice?name=ssq&issueCount=200"
custom_xx_uri = "http://www.cwl.gov.cn/cwl_admin/kjxx/findDrawNotice?name=ssq&issueCount=&issueStart=&issueEnd=&dayStart=2017-10-24&dayEnd=2018-10-24&pageNo="
class SSQ:

    def __init__(self):
        self.url = xx_uri
        self.html = html.parse(self.url)

    def getitem(self, path, *args):
        return self.tree.xpath(path.format(*args))

    # def get


from __future__ import print_function
from flask import jsonify, request, Response, json, g
from orlo.app import app
from orlo import queries
from orlo.exceptions import InvalidUsage
from orlo.user_auth import token_auth
from orlo.orm import db, Release, Package, PackageResult, ReleaseNote, \
    ReleaseMetadata, Platform
from orlo.util import validate_request_json, create_release, \
    validate_release_input, validate_package_input, fetch_release, \
    create_package, fetch_package, stream_json_list, str_to_bool, is_uuid
from orlo.user_auth import conditional_auth

__author__ = 'alforbes'

"""
Note - the /packages/ endpoint is very alpha, it is not part of the usual
release workflow and intended for utilitarian uses such as debugging and
fixing errors.
"""

@app.route('/packages', methods=['GET'])
@app.route('/packages/<package_id>', methods=['GET'])
def get_packages(package_id=None):
    """
    Return a list of packages to the client

    :param package_id:
    :return:
    """

    booleans = ('rollback', )

    if package_id:  # Simple, just fetch one package
        if not is_uuid(package_id):
            raise InvalidUsage("Package ID given is not a valid UUID")
        query = queries.get_package(package_id)
    else:  # Bit more complex
        # Flatten args, as the ImmutableDict puts some values in a list when
        # expanded
        args = {
            'limit': 100
        }
        for k in request.args.keys():
            if k in booleans:
                args[k] = str_to_bool(request.args.get(k))
            else:
                args[k] = request.args.get(k)
        query = queries.build_query(Package, **args)

    # Execute eagerly to avoid confusing stack traces within the Response on
    # error
    db.session.execute(query)

    if query.count() == 0:
        response = jsonify(message="No packages found", packages=[])
        return response, 404

    return Response(stream_json_list('packages', query),
                    content_type='application/json')


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

## No Python 2, em vez da função input(), utilizamos a função raw_input() para pegar a entrada do usuário como string
## AF_INET -> IPv4, AF_INET6 -> IPv6
## SOCK_STREAM -> TCP, SOCK_DGRAM -> UDP

## Imports
import socket
import time

## Funções
def keep():
    while True:
        try:
            b = int(input("digite 0 para cancelar e 1 para continuar : "))
            if b < 2:
                break
            print("caracter inválido!")
        except:
            print("caracter inválido!")
            print("encerrando operação...")
            b = 0
            break
    return b

def ipdoor():
    i = input("IP : ")
    if i == "":
        i = "127.0.0.1"
        print('IP definido: 127.0.0.1')
    elif len(ip) > 15:
        i = "127.0.0.1"
        print('IP definido: 127.0.0.1')
    elif len(ip) < 7:
        i = "127.0.0.1"
        print('IP definido: 127.0.0.1')
    try:
        d = int(input("Porta : "))
    except:
        d = 12345
        print('Porta definida : 12345')
    if d > 56000 or d < 1024:
        d = 12345
        print('Porta definida : 12345')
    return i, d

## Main
ip, door = ipdoor()
print('Tentando conectar no IP {0} Porta {1}...'.format(ip,door))

mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysocket.bind((ip, door))
mysocket.listen(1)
connection, address = mysocket.accept()
print('Conectado com',address)
while True:
    name = input('Nome do arquivo : ')
    if name == '':
        name = 'hino.txt'
        print('Nome do arquivo : hino.txt')
    try:
        arq = open(name)
        print('Arquivo aberto!')
        time.sleep(1)
        texto = arq.read()
        palavras = texto.split()
        for i in palavras:
            print(i)
        #bug = 0
        #for i in palavras:
            connection.send(i.encode('utf-8')) # connection.sendto(i.encode('ascii')) => bug=0 connection.sendall(i.encode('ascii')) => bug=5
        #    bug += 1
        arq.close()
    except:
        print("Não foi possível abrir o arquivo")
        print('bug no ciclo : ',bug)
    b = keep()
    if b == 0:
        break
print("fechando conexão...")
connection.close()
mysocket.close()
print('conexões fechadas!')


from brl_gym.experts.expert import Expert
from brl_gym.wrapper_envs.wrapper_lightdark import BayesLightDark
import numpy as np

class LightDarkExpert(Expert):
    def __init__(self):
        env = BayesLightDark()
        obs_dim = env.env.observation_space.low.shape[0]
        bel_dim = env.estimator.belief_space.low.shape[0]
        super(LightDarkExpert, self).__init__(obs_dim, bel_dim)

    def action(self, inputs, infos=None):
        if len(inputs.shape) == 1:
            inputs = inputs.reshape(1, -1)

        obs, bel = self._split_inputs(inputs)
        # Ignore obs. Bel has all the necessary information
        dist_to_goal = bel[:, :2]
        #dist_to_goal /= np.linalg.norm(dist_to_goal, axis=1).reshape(-1,1)
        #dist_to_goal *= 0.5

        # Straight to the MLE goal
        return dist_to_goal

    def __call__(self, inputs):
        return self.action(inputs)
if __name__ == "__main__":
    import numpy as np
    env = BayesLightDark()
    expert = LightDarkExpert()
    obs = env.reset()
    for _ in range(100):
        print()
        action = expert.action(obs)
        print("goal  ", env.env.goal)
        print("self  ", env.env.x)
        print("dir   ", np.around(env.env.goal - env.env.x,2))
        print("obs   ", np.around(obs,2))
        print("action", np.around(action,2))
        obs, _, _, info = env.step(action[0])


import datetime

import pytz
from django.shortcuts import render
from uk_improv_guide.models.team import Team, get_team_by_id

def team(request, id: int):
    now = pytz.utc.localize(datetime.datetime.now())
    this_team: Team = get_team_by_id(id)
    title = f"Team: {this_team.name}"
    events = this_team.event_set.all().order_by("start_time")
    players = this_team.players.all()

    future_events = [e for e in events if e.start_time > now]
    past_events = [e for e in events if e.start_time <= now]

    return render(
        request,
        "team.html",
        {
            "title": title,
            "team": this_team,
            "events": future_events,
            "past_events": past_events,
            "players": players,
            "og_subject": this_team,
        },
    )


from bluesky import core, stack
from bluesky.navdatabase import Navdatabase
import bluesky as bs
import numpy as np

def init_plugin():
    # Addtional initilisation code
    # Configuration parameters
    e = GroundNavdatabase()
    config = {
        # The name of your plugin
        'plugin_name': 'GROUNDNAVDATABASE',
        # The type of this plugin. For now, only simulation plugins are possible.
        'plugin_type': 'sim',
    }

    return config

class GroundNavdatabase(core.Entity):
    def __init__(self):
        super(GroundNavdatabase, self).__init__()

    @stack.command
    def defwpt2(self, name: 'txt', lat: float, lon: float, wptype: 'txt'):
        if name.upper() in bs.navdb.wpid:
            i = bs.navdb.wpid.index(name.upper())

            bs.navdb.wplat[i] = lat
            bs.navdb.wplon[i] = lon
            bs.scr.addnavwpt(name.upper(), lat, lon)
        else:
            bs.navdb.wpid.append(name.upper())
            bs.navdb.wplat = np.append(bs.navdb.wplat, lat)
            bs.navdb.wplon = np.append(bs.navdb.wplon, lon)

            if wptype == None:
                bs.navdb.wptype.append("")
            else:
                bs.navdb.wptype.append(wptype)

            bs.navdb.wpelev.append(0.0)  # elevation [m]
            bs.navdb.wpvar.append(0.0)  # magn variation [deg]
            bs.navdb.wpfreq.append(0.0)  # frequency [kHz/MHz]
            bs.navdb.wpdesc.append("Custom waypoint")  # description

            # Update screen info
            bs.scr.addnavwpt(name.upper(), lat, lon)

        return True, name.upper() + " added to navdb."


from tkinter import *

"""
Here everything is a widget, similar to GTK
The main widget that should always be created is called root
"""

root = Tk()

# This adds a title to the window
root.title("Hello")

myLabel = Label(root,text="Hello World!") # creating a label widget

"""
Now we want to put the label into the main window
"""

myLabel.pack() # pack the widget into the window depending on its size

"""
Now we will need to create an event loop so as to detect mouse
and keyboard events and also make the window stay
"""

root.mainloop()


# Databricks notebook source
# MAGIC %md
# MAGIC # Example Notebook
# MAGIC This is a description of the Notebook

# COMMAND ----------

# MAGIC %md
# MAGIC ## Read a data file
# MAGIC Read and display a CSV from DBFS.

# COMMAND ----------

df = spark.read.csv("/FileStore/uszips.csv",
                    header="true",
                    inferSchema="true")
display(df)

# COMMAND ----------

df.createOrReplaceTempView('temp')

# COMMAND ----------

# MAGIC %sql
# MAGIC SELECT * FROM temp

# COMMAND ----------

# MAGIC %sql
# MAGIC SELECT `state_id` AS `state`,COUNT(`zip`) AS `nzips`
# MAGIC FROM temp
# MAGIC WHERE `state_id` NOT IN ('AS','GU','MP','PR','VI')
# MAGIC GROUP BY `state`
# MAGIC ORDER BY `nzips`

# COMMAND ----------

# MAGIC %sql
# MAGIC SELECT `state_id` AS `state`,SUM(`population`) AS `population`
# MAGIC FROM temp
# MAGIC WHERE `state_id` NOT IN ('AS','GU','MP','PR','VI')
# MAGIC GROUP BY `state`


#   wap to reverse the word of odd index in a string
def revWord():
    str="hello hi bye"
    words=str.split()
    odd=[]
    for i in range(len(words)):
        if i%2==0:
            s=words[i]
            odd.append(s[::-1])
        else:
            odd.append(words[i])
    print(odd)
revWord()


import util as u

import os
from os.path import join

import numpy as np
import pandas as pd

from skimage.transform import resize
from skimage.morphology import label
from keras.models import model_from_json

import argparse
parser = argparse.ArgumentParser('U-Net for TGS Salt Identification')
parser.add_argument('-n', '--name', dest='name', type=str, default='u-net')
parser.add_argument('-t', '--threshold', dest='tval', type=float, default=0.5)
parser.add_argument('-cs', '--cumsum', dest='cs', action='store_true')
parser.add_argument('-g', '--gray', dest='gray', action='store_true')
parser.add_argument('-sn', '--sub_name', dest='sub_name', type=str, default='sub')
args = parser.parse_args()

u.set_gray(args.gray)
u.set_cs(args.cs)
name = args.name

with open(join('models', name, 'model.json')) as f:
	json = f.read()
model = model_from_json(json)
model.load_weights(join('models', name, 'model.h5'))

num_chan = model.layers[0].input_shape[-1]
if num_chan == 3:
	u.set_gray(False)
	u.set_cs(False)
elif num_chan == 2:
	u.set_cs(True)
else:
	u.set_cs(False)

"""
Perform RLE on a connected component of a mask
:param x: the image to encode
"""
def rle_encoding_for_comp(x):
	# I stole this code from Kaggle and have not put in the effort
	# to learn how it works.
    dots = np.where(x.T.flatten() == 1)[0]
    run_lengths = []
    prev = -2
    for b in dots:
        if (b>prev+1): run_lengths.extend((b + 1, 0))
        run_lengths[-1] += 1
        prev = b
    return run_lengths

"""
Perform RLE encoding on an image
:param x: the image to encode
"""
def rle_encoding(x):
	return [rle_encoding_for_comp(x)]

odim = 101 # the original dimension of the images

rle_ids = []
rles = []

def encode_batch(pred, ids):
	global rle_ids, rles, odim
	for i, p in enumerate(pred):
		p = resize(p, (odim, odim), mode='constant', preserve_range=True)
		#b = (128-101)//2
		#x = x[b:-b, b:-b]

		mask = (p > args.tval).astype(np.uint8)
		mask = u.postprocessing(mask)
		mask_rle = rle_encoding(mask)

		rles.extend(mask_rle)
		rle_ids.extend([ids[i]] * len(mask_rle))

		if len(mask_rle) == 0:
			rles.extend([[1, 1]])
			rle_ids.extend([ids[i]])

test_ids = u.test_ids()
batch_size = 64
i = 0

id_batch = test_ids[i*batch_size : (i+1)*batch_size]

while i*batch_size < len(test_ids)-1:
	batch = u.test_imgs(for_ids=id_batch)
	ids = [i[:i.index('.')] for i in id_batch]

	print(i, batch.shape)

	# propagate the test images forward through the U-Net
	pred = model.predict(batch, batch_size=batch_size)[:,:,:,0]
	encode_batch(pred, ids)

	i += 1
	id_batch = test_ids[i*batch_size : (i+1)*batch_size]

df = pd.DataFrame()
df['id'] = rle_ids
df['rle_mask'] = pd.Series(rles).apply(lambda x: ' '.join(str(y) for y in x))
df.to_csv(join('models', name, args.sub_name+'.csv'), index=False)


import torch
import numpy as np
from ..molecule_models import vae_network, action_representation as ar, _train_utils
from .. import corruption_dataset, molecule_representation as mr

def embed_dataset(loader, model: vae_network.JointVaeNetwork, progress='tqdm'):
    means = []
    log_variances = []

    if progress == 'tqdm':
        import tqdm
        loader = tqdm.tqdm(loader)

    for batch in loader:
        batch = _train_utils.load_cuda_async(batch)

        with torch.autograd.no_grad():
            mean, log_variance = model.recognition(batch['graph'])

        means.append(mean.cpu().numpy())
        log_variances.append(log_variance.cpu().numpy())

    means = np.concatenate(means, axis=0)
    log_variances = np.concatenate(log_variances, axis=0)
    return means, log_variances

def make_model(action_encoder=None):
    if action_encoder is None:
        action_encoder = ar.VocabInsertEncoder(canonical=True)

    config_recog = vae_network.MoleculeRecognitionNetworkConfig(
        hidden_size=384,
        embedding_size=384,
        depth=5)

    config = vae_network.JointClassificationNetworkConfiguration(
        action_encoder.get_num_atom_insert_locations(),
        action_encoder.num_insert_bond_locations,
        hidden_size=384,
        depth=5)

    model = vae_network.JointVaeNetwork(config_recog, config)
    return model

def _dataset_transform(mol, _):
    return {
        'graph': mr.mol2graph_single(mol, include_leaves=True, include_rings=True, normalization='sqrt')
    }

def embed_dataset_files(model_path, data_path, output_path):
    model = make_model()
    model.load_state_dict(torch.load(model_path, map_location='cpu'))
    model = model.cuda()
    model.eval()

    dataset = corruption_dataset.BaseDataset(data_path, transform=_dataset_transform)
    data_loader = torch.utils.data.DataLoader(
        dataset, batch_size=512, collate_fn=_train_utils.collate, num_workers=4,
        pin_memory=True)

    means, log_variances = embed_dataset(data_loader, model)

    np.savez(output_path, means=means, log_variances=log_variances)

def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('--model-path')
    parser.add_argument('--data-path')
    parser.add_argument('--output-path')

    args = parser.parse_args()

    embed_dataset_files(args.model_path, args.data_path, args.output_path)

if __name__ == '__main__':
    main()


from asyncio import shield

import socketio

from pycrunch.watcher.fs_watcher import FSWatcher

file_watcher = FSWatcher()

# async_mode='threading'
# async_mode='tornado'
# async_mode='eventlet'
async_mode='aiohttp'

# log_ws_internals = True
log_ws_internals = False
sio_instance = None

def sio():
    global sio_instance
    if sio_instance is None:
        sio_instance = socketio.AsyncServer(async_mode=async_mode, cors_allowed_origins='*', logger=log_ws_internals, engineio_logger=log_ws_internals)
    return sio_instance

class ExternalPipe:
    async def push(self, event_type, **kwargs):
        # print(f'ws event: {event_type}')
        # pprint(kwargs)

        await shield(sio().emit('event',
                       dict(
                           event_type=event_type,
                           **kwargs
                       ),
                       namespace='/'))

pipe = ExternalPipe()


import youtube_dl
from bs4 import BeautifulSoup
try:
    from scripts.actions import notify
except:
    pass
import os
from urllib.request import urlopen

def execute(link):
    text=link.replace(" ","+")
    print(text)
    url = 'https://www.youtube.com/results?search_query='+text
    fhand=urlopen(url).read()
    soup = BeautifulSoup(fhand, "html.parser")
    songs = soup.findAll('div', {'class': 'yt-lockup-video'})
    hit = songs[0].find('a')['href']
    notify("Downloading "+link)
    ydl_opts = {
                    'format': 'bestaudio/best',
                    'postprocessors': [{
                                        'key': 'FFmpegExtractAudio',
                                        'preferredcodec': 'mp3',
                                        'preferredquality': '192',
                                        }],
                                        'quiet': True,
                                        'restrictfilenames': True,
                                        'outtmpl': os.environ['HOME']+'/Music/new/%(title)s.%(ext)s'
                                        }

    ydl = youtube_dl.YoutubeDL(ydl_opts)
    ydl.download(['https://www.youtube.com'+hit])
    notify("Song Download Complete")
    print("Song download complete")


import typing

import httpcore

if typing.TYPE_CHECKING:
    from ._models import Request, Response  # pragma: nocover

class HTTPError(Exception):
    """
    Base class for all HTTPX exceptions.
    """

    def __init__(
        self, *args: typing.Any, request: "Request" = None, response: "Response" = None
    ) -> None:
        super().__init__(*args)
        self._request = request or (response.request if response is not None else None)
        self.response = response

    @property
    def request(self) -> "Request":
        # NOTE: this property exists so that a `Request` is exposed to type
        # checkers, instead of `Optional[Request]`.
        assert self._request is not None  # Populated by the client.
        return self._request

# Timeout exceptions...

ConnectTimeout = httpcore.ConnectTimeout
ReadTimeout = httpcore.ReadTimeout
WriteTimeout = httpcore.WriteTimeout
PoolTimeout = httpcore.PoolTimeout

# Core networking exceptions...

NetworkError = httpcore.NetworkError
ReadError = httpcore.ReadError
WriteError = httpcore.WriteError
ConnectError = httpcore.ConnectError
CloseError = httpcore.CloseError

# Other transport exceptions...

ProxyError = httpcore.ProxyError
ProtocolError = httpcore.ProtocolError

# HTTP exceptions...

class DecodingError(HTTPError):
    """
    Decoding of the response failed.
    """

# Redirect exceptions...

class RedirectError(HTTPError):
    """
    Base class for HTTP redirect errors.
    """

class TooManyRedirects(RedirectError):
    """
    Too many redirects.
    """

class NotRedirectResponse(RedirectError):
    """
    Response was not a redirect response.
    """

# Stream exceptions...

class StreamError(HTTPError):
    """
    The base class for stream exceptions.

    The developer made an error in accessing the request stream in
    an invalid way.
    """

class RequestBodyUnavailable(StreamError):
    """
    Had to send the request again, but the request body was streaming, and is
    no longer available.
    """

class StreamConsumed(StreamError):
    """
    Attempted to read or stream response content, but the content has already
    been streamed.
    """

class ResponseNotRead(StreamError):
    """
    Attempted to access response content, without having called `read()`
    after a streaming response.
    """

class RequestNotRead(StreamError):
    """
    Attempted to access request content, without having called `read()`.
    """

class ResponseClosed(StreamError):
    """
    Attempted to read or stream response content, but the request has been
    closed.
    """

# Other cases...

class InvalidURL(HTTPError):
    """
    URL was missing a hostname, or was not one of HTTP/HTTPS.
    """

class CookieConflict(HTTPError):
    """
    Attempted to lookup a cookie by name, but multiple cookies existed.
    """


'''
    UNIT TESTING

    Devoloped By: Mariana Montoya Naranjo
    Written in Python 3.7 using unittest unit testing framework
'''

import unittest
from pyunitreport import HTMLTestRunner
from dollar_today import dollar_today_scrap
from price_ticket import calculate_price
from package import Package
from flight import Flight

class Testing(unittest.TestCase):

    '''
    ------ VALIDATION FUNCTION DOLLAR_TODAY ------
    Test the update of the dollar price
    '''

    def test_validations_inputs(self):

        result_dollar_today  = dollar_today_scrap()

        self.assertFalse(result_dollar_today == 0)

    '''
    ------ VALIDATION FUNCTION DOLLAR_TODAY ------
    Test the calculation of the price of an air ticket depending on the distance traveled and the days of stay
    '''

    def test_price_ticket(self):

        result_price_ticket, result_discount = calculate_price(8, 150)
        result_expected_price_ticket = 5250
        result_expected_discount = False

        self.assertEqual(result_price_ticket, result_expected_price_ticket)
        self.assertEqual(result_discount, result_expected_discount)

    def test_price_ticket_with_discount(self):

        result_price_ticket, result_discount = calculate_price(10, 1200)
        result_expected_price_ticket = 29400
        result_expected_discount = True

        self.assertEqual(result_price_ticket, result_expected_price_ticket)
        self.assertEqual(result_discount, result_expected_discount)

    '''
    ------ VALIDATION CLASS PACKAGE ------
    Test the calculation of the baggage price in pesos and dollars
    '''

    def test_calculate_price_pesos(self):

        package1 = Package(22, 3500)

        result1 = package1.calculate_price_pesos()
        result_expected1 = 0

        self.assertEqual(result1, result_expected1)

        package2 = Package(128, 3500)

        result2 = package2.calculate_price_pesos()
        result_expected2 = 192000

        self.assertEqual(result2, result_expected2)

        package3 = Package(400, 3500)

        result3 = package3.calculate_price_pesos()
        result_expected3 = 1000000

        self.assertEqual(result3, result_expected3)

    def test_calculate_price_pesos(self):

        package1 = Package(22, 3500)

        result1 = package1.calculate_price_dollar()
        result_expected1= 0

        self.assertEqual(result1, result_expected1)

        package2 = Package(128, 3500)

        result2 = package2.calculate_price_dollar()
        result_expected2 = 54.86

        self.assertEqual(result2, result_expected2)

        package3 = Package(400, 3500)

        result3 = package3.calculate_price_dollar()
        result_expected3 = 285.71

        self.assertEqual(result3, result_expected3)

if __name__ == "__main__":

    unittest.main(verbosity=2, testRunner=HTMLTestRunner(output='reportes', report_name= 'unittests-report'))


import sys
from collections import deque

input = sys.stdin.readline

def bfs(box_list):
    dir = [(0,1,0), (0,-1,0), (0,0,1), (0,0,-1), (1,0,0), (-1,0,0)]
    #visited = []
    queue = deque()
    today = deque()
    tomorrow = deque()
    day = 0

    if day == 0:
        for b in range(len(box_list)):
            for r in range(len(box_list[0])):
                for c in range(len(box_list[0][0])):
                    if box_list[b][r][c] == 1:
                        #visited.append((r,c))
                        queue.append((b,r,c))
                        today.append((b,r,c))

    while queue:
        while today:
            queue.popleft()
            cur_b, cur_x, cur_y = today.popleft()
            for direction in dir:
                b = cur_b + direction[0]
                x = cur_x + direction[1]
                y = cur_y + direction[2]
                if (b >= 0 and b < len(box_list)) and (x >= 0 and x < len(box_list[0])) and (y >= 0 and y < len(box_list[0][0])):
                    if box_list[b][x][y] == 0:
                        box_list[b][x][y] = 1
                        #visited.append((x,y))
                        queue.append((b,x,y))
                        tomorrow.append((b,x,y))

        while tomorrow:
            today.append(tomorrow.popleft())

        day += 1

    #print(tomatoBox)

    # 여기까지 왔으면 방문할 수 있는 노드는 다 방문 했다는 것. 이때 아직도 0이 남아있으면 토마토가 모두 익지 못한 상황
    for tomato_box in box_list:
        for tomato_row in tomato_box:
            if 0 not in tomato_row:
                continue
            print(-1) # continue에 안 걸렸으므로 0이 있다는 뜻이니까
            return

    # 여기까지 왔으면 0은 없다는 것. 따라서 day를 출력한다.
    print(day-2)

def main():
    box_list = []
    tomatoBox = []
    m, n, h = map(int, input().split())

    for _ in range(h):
        for i in range(n):
            _list = list(map(int, input().split()))
            tomatoBox.append(_list)
        box_list.append(tomatoBox)

    # for tomato_box in box_list:
    #     for tomato_row in tomato_box:
    #         if 0 not in tomato_row:
    #             continue
    #         print(0) # continue에 안 걸렸으므로 0이 있다는 뜻이니까
    #         return
    for tomato_box in range(len(box_list)):
        for tomato_row in range(n):
            if 0 in box_list[tomato_box][tomato_row]:
                break
            if tomato_row == n-1:
                print(0)
                return

    bfs(box_list)

main()


import csv
import os
from pydub import AudioSegment, silence
from pydub.playback import play
from matplotlib.pyplot import plot, show

path_to_repository = "/Users/rcorps/Documents/IMPRS Python/session_2 /session2b-sound"

# This piece of code is here to help you.
# It reads a text file with information about the stimuli you are going to split (names & condition),
# and returns a dictionary named 'stimuli' with condition as key, and the word itself as value.
# Use this dictionary to name the files you have to save.
stimuli_info = open(os.path.join(path_to_repository, "lexdec_stimuli.txt"))
stimuli_reader = csv.reader(stimuli_info, delimiter=',')
headers = next(stimuli_reader, None)

# Create the dictionary
stimuli = {}
for stimulus in stimuli_reader:
    if stimulus[2] not in stimuli.keys():
        stimuli[stimulus[2]] = list()
    stimuli[stimulus[2]].append(stimulus[3])

# Put them in alphabetical order
for condition, words in stimuli.items():
    sort = sorted(words)
    stimuli[condition] = sort

# change the non-word condition name
stimuli["NW"] = stimuli.pop("none")

# where are the sound files?
sound_folder = "/Users/rcorps/Documents/IMPRS Python/session_2 /session2b-sound/raw"

# make new folders
new_folder_HF = "/Users/rcorps/Documents/IMPRS Python/session_2 /session2b-sound/HF"
if not os.path.isdir(new_folder_HF):
    os.mkdir(new_folder_HF)
new_folder_LF = "/Users/rcorps/Documents/IMPRS Python/session_2 /session2b-sound/LF"
if not os.path.isdir(new_folder_LF):
    os.mkdir(new_folder_LF)
new_folder_NW = "/Users/rcorps/Documents/IMPRS Python/session_2 /session2b-sound/NW"
if not os.path.isdir(new_folder_NW):
    os.mkdir(new_folder_NW)

# where are the sound files?
sound_folder = "/Users/rcorps/Documents/IMPRS Python/session_2 /session2b-sound/raw"

# Open the high frequency audio
High_path = os.path.join(sound_folder, "HF_recording.wav")
High_sound = AudioSegment.from_wav(High_path)
Low_path = os.path.join(sound_folder, "LF_recording.wav")
Low_sound = AudioSegment.from_wav(Low_path)
None_path = os.path.join(sound_folder, "NW_recording.wav")
None_sound = AudioSegment.from_wav(None_path)

# split the words
High_words = silence.split_on_silence(High_sound, min_silence_len=200, silence_thresh=-50)
Low_words = silence.split_on_silence(Low_sound, min_silence_len=200, silence_thresh=-50)
None_words = silence.split_on_silence(None_sound, min_silence_len=200, silence_thresh=-50)

norm_HF = []
norm_LF = []
norm_NW = []

# normalise the volume
for word in High_words:
    target_volume = -10
    current_volume = word.dBFS
    change = target_volume - current_volume
    normalized_HF = word.apply_gain(change)
    norm_HF.append(normalized_HF)

for word in Low_words:
    target_volume = -10
    current_volume = word.dBFS
    change = target_volume - current_volume
    normalized_LF = word.apply_gain(change)
    norm_LF.append(normalized_LF)

for word in None_words:
    target_volume = -10
    current_volume = word.dBFS
    change = target_volume - current_volume
    normalized_NW = word.apply_gain(change)
    norm_NW.append(normalized_NW)

# export to the folders
for i in range(len(norm_HF)):
    sound = norm_HF[i]
    filename = stimuli['HF'][i] + ".wav"
    sound.export(os.path.join(new_folder_HF, filename))

for i in range(len(norm_LF)):
    sound = norm_LF[i]
    filename = stimuli['LF'][i] + ".wav"
    sound.export(os.path.join(new_folder_LF, filename))

for i in range(len(norm_NW)):
    sound = norm_NW[i]
    filename = stimuli['NW'][i] + ".wav"
    sound.export(os.path.join(new_folder_NW, filename))


# Transform the Expression

t = int(input())

def parse(s):
    if len(s) == 1:
        return s
    if len(s) == 3:
        return s[0] + s[2] + s[1]

    s = s[1:-1]

    layer = 0
    i = 0
    while True:
        if s[i] == "(":
            layer += 1
        elif s[i] == ")":
            layer -= 1
        elif s[i] in "+-*/^" and not layer:
            a = s[:i]
            o = s[i]
            b = s[i+1:]
            return parse(a) + parse(b) + o
        i += 1

for _ in range(t):
    expression = input()
    print(parse(expression))


# coding:utf-8
# Created by Equator at 2021/4/29
import hashlib
import sys
import os

def get_file_md5(file_name):
    """
    计算文件的md5（处理较大文件）
    :param file_name:
    :return:
    """
    m = hashlib.md5()
    with open(file_name, 'rb') as file_obj:
        while True:
            data = file_obj.read(4096)
            if not data:
                break
            m.update(data)
    return m.hexdigest()

def get_file_meta_recursion(file_path):
    """
    递归获取文件名，返回文件MD5值与文件名集合
    :param file_path:
    :return:
    """
    file_name_dict = {}
    paths = os.listdir(file_path)
    for path in paths:
        full_path = os.path.join(file_path, path)
        if not os.path.exists(full_path):
            continue
        if os.path.isfile(full_path):
            file_md5 = get_file_md5(full_path)
            file_name_dict[file_md5] = full_path
            print(f"读取文件：{full_path}")
        else:
            children_file_name_set = get_file_meta_recursion(full_path)
            if children_file_name_set is not None:
                file_name_dict.update(children_file_name_set)
    return file_name_dict

def delete_existed_file_by_md5(existed_path, new_path):
    """
    通过文件名删除已经存在的文件：判断new_path下每一个文件是否存在existed_path目录下，是的话则删除
    :param existed_path: 已经存在的文件的目录，下面可以有很多子目录
    :param new_path: 一个新的文件集合的目录
    :return:
    """
    existed_file_meta_dict = get_file_meta_recursion(existed_path)
    new_file_meta_dict = get_file_meta_recursion(new_path)
    existed_file_md5_set = existed_file_meta_dict.keys()
    deleted_file_num = 0
    for new_file_md5, new_file_path in new_file_meta_dict.items():
        if new_file_md5 in existed_file_md5_set:
            print(f"删除重复文件：{new_file_path}")
            os.remove(new_file_path)
            deleted_file_num += 1
    print(f"总共删除文件数量：{deleted_file_num}")

def normalize_path(path):
    return path.replace('\\', os.sep)

if __name__ == '__main__':
    if len(sys.argv) == 1:
        raise Exception('请输入文件路径参数，分别为existed_path new_path')
    existed_path = normalize_path(sys.argv[1])
    new_path = normalize_path(sys.argv[2])
    print(f"existed_path：{existed_path}，new_path：{new_path}")
    delete_existed_file_by_md5(existed_path, new_path)


import time

inicio  = time.time()

while True:
    print("Estamos jugando....")

    final = time.time()
    transcurrido = final -inicio
    if((transcurrido) >= 5 ):
        break
print(f"Fin del juego, tiempo total del juego {transcurrido}")


class Solution(object):
    def __init__(self):
        self.critical_threshold_factor = 90
    @staticmethod
    def matcher(needle, n_start, n_end, haystack, h_start, h_end):
        found = True
        while h_start < h_end and n_start < n_end:
            if needle[n_start] != haystack[h_start]:
                found = False
                break
            h_start += 1
            n_start += 1
        return found, h_start

    def naive(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if needle is None or len(needle) == 0:
            return 0
        if len(needle) > len(haystack):
            return -1
        i = 0
        while i < len(haystack) - len(needle) + 1:
            found, _ = Solution.matcher(needle, 0, len(needle), haystack, i, len(haystack))
            if found:
                return i
            i += 1
        return -1

    def strStr(self, haystack, needle):
        if haystack is None or needle is None:
            return 0
        len_needle = len(needle)
        if len_needle == 0:
            return 0
        len_haystack = len(haystack)
        if len_needle > len_haystack:
            return -1
        if len_needle == 1:
            return -1 if needle[0] != haystack[0] else 0

        if int(len_needle*100 / len_haystack) > self.critical_threshold_factor:
            return self.naive(haystack, needle)

        # Pi table: Preprocess the needle
        pi_table = [0]*len_needle

        '''
        ababcab => [0, 0, 1, 2, 0, 1, 2]
        '''
        i = 1
        previous_len = 0
        while i < len_needle:
            if needle[i] == needle[previous_len]:
                previous_len += 1
                pi_table[i] = previous_len
                i += 1
            else:
                if previous_len != 0:
                    previous_len = pi_table[previous_len - 1]
                else:
                    pi_table[i] = 0
                    i += 1

        '''
        Do the KMP search now
        '''
        i = 0
        j = 0
        while i < len_haystack:
            if haystack[i] == needle[j]:
                i += 1
                j += 1
                if j == len_needle:
                    return i - j
            else:
                if j != 0:
                    j = pi_table[j-1]
                else:
                    i += 1
        return -1


from myimports import *

def create_whatsapp_data(chat_file, name_person_1, name_person_2):
    person1_datastore = list(dict())
    person2_datastore = list(dict())

    pattern = re.compile("[^\w']")

    def strip_line(line):
        stripped_line = pattern.sub(' ', line).strip()
        datetime_str = stripped_line[0:17]
        datetime_obj = datetime.strptime(datetime_str, '%d %m %y %H %M %S')
        return datetime_obj, stripped_line

    with open(chat_file, "rb") as input_file:
        for line in input_file.readlines():
            if name_person_1 in line:
                datetime_obj, stripped_line = strip_line(line)
                message = stripped_line[34:]
                person1_datastore.append(
                    {'Datetime': str(datetime_obj), 'Message': message})
            if name_person_2 in line:
                datetime_obj, stripped_line = strip_line(line)
                message = stripped_line[35:]
                person2_datastore.append(
                    {'Datetime': str(datetime_obj), 'Message': message})

    input_file.close()

    with open(name_person_1+'_datastore.json', 'w') as outfile:
        json.dump(person1_datastore, outfile)

    with open(name_person_2+'_datastore.json', 'w') as outfile:
        json.dump(person2_datastore, outfile)


import pandas as pd

def extract(source_csv, data_series, index_series, name_series):
    csv = pd.read_csv(source_csv)
    Serie = pd.Series(data=csv[data_series].values, index=csv[index_series].values, name=name_series)
    return Serie

csv[1].sum()
series = extract("Historico de Contagio de COVID-19 - Estado de Guanajuato_Página 1_Serie temporal.csv", 'Por dia',
                 'Fecha', 'Serie de prueba')

print('Serie: ', series)

mediana = series.median()
media = series.mean()
print('Desviación estandar: \n', series.std())
print('Mediana: \n', series.median())
print('Media: \n', series.mean())

# El dia que hubó mas casos

print('Dia con mas casos', series.idxmax(), 'Casos', series.max())

# Los días (fechas) donde hubo más casos con respecto a la mediana (mayores que la mediana).

casos_mayores_mediana = series[series > series.median()]
print('Mayor a mediana = \n', casos_mayores_mediana)

# La desviación estándar.

desviacion_estandar = series.std()
print('Desviacion estandar = \n', desviacion_estandar)

# Los días (fechas) y la cantidad de casos entre la media y la mediana.
casos_entre_media_mediana = series[series.between(left=series.median(), right=series.mean())]
print('Casos entre media y mediana = \n', casos_entre_media_mediana)

# def transform(series):


from flask import request
from flask.json import jsonify
from flask_restful import Resource
from flask_login import current_user, login_required

from elearning import db
from elearning.models.databasemodels import Class, User

class ParticipantsResource(Resource):
    @login_required
    def get(self, class_id):
        """ Get all participant from a particular class """
        s_class = Class.query.join(User.classes).filter(User.email==current_user.email).filter_by(class_id=class_id).first()
        participants = []
        for user in s_class.users:
            us = {}
            us['User_id'] = user.id
            us['Name'] = user.firstname + ' ' + user.lastname
            us['User_level'] = user.user_level
            participants.append(us)
        return jsonify({
            'Participants': participants,
            'Status': 200
        })

    @login_required
    def post(self, class_id):
        """ Lecturer has ability to add new participant to a class by input student email """
        s_class = Class.query.join(User.classes).filter(User.email==current_user.email).filter_by(class_id=class_id).first()

        if request.method == 'POST':
            if 'user_email' not in request.form:
                return jsonify({
                    'Message': 'User email required!',
                    'Status': 400
                })

            user_email = request.form['user_email']
            check_user = User.query.filter_by(email=user_email).first()
            if not check_user:
                message = 'User whit {} not found'.format(user_email)
            elif check_user in s_class.users:
                message = 'User with that email already in this Class'

            else:
                s_class.users.append(check_user)
                db.session.commit()
                return jsonify({
                    'Message': 'Student with {} email added to this class'.format(check_user),
                    'Status': 200
                })

            return jsonify({
                'Message': message,
                'Status': 400
            })

class ParticipantResource(Resource):
    @login_required
    def get(self, class_id, index):
        """ Get a particular Student profile """
        s_class = Class.query.join(User.classes).filter(User.email==current_user.email).filter_by(class_id=class_id).first()

        if index > len(s_class.users):
            return jsonify({
                'Message': f'You only have {len(s_class.users)} participants in this class',
                'Status': 400
            })

        participant = s_class.users[index-1]
        return jsonify({
            'Name': str(participant),
            'User_id': participant.id,
            'Status': 200
        })
    @login_required
    def delete(self, class_id, index):
        pass