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

# # PA. Poker Hands in OOP
#
# A deck of cards is 52 cards, divided into four suits, each containing 13 ranks. Each card is uniquely idedifieable by auit and rank.
# - Suits: spades, clubs, hearts, and diamonds
# - Ranks: Ace, 2, ..., 10, Jack, Queen, King

# Shuffle the deck. Pick a card from the top of the deck and print the name of card. Repeat 5 times.

# ## Abstract `Card` class
# Q. Write a `Card` class. Class instances are created by passing `rank + suit` string, for instance:
# ```Python
# >>> card = Card('TD')
# >>> print(card)
# TD
# >>> card
# TD
# ```
# 한 장의 카드가 갖는 값(integer)은 카드 게임 종류에 따라 다르다. 보통 rank 종류에 따라 값이 결정된다. 예를 들어 King은 poker game에서는 13이지만, blackjack game에서는 10 또는 0으로 사용될 수 있다.
# value method를 implement하기 전에는 두 장의 card를 비교할 수 없다. 그러나, subclass에서 이 method만 implement한다면 비교가 가능하게 된다. 상속받을 class를 위해 정의하는 class를 'abstract class'라 한다.
#

# In[1]:

# Constants
suits = 'CDHS'
ranks = '23456789TJQKA'

from abc import ABCMeta, abstractmethod

class Card(metaclass=ABCMeta):
    """Abstact class for playing cards
    """
    def __init__(self, rank_suit):
        if rank_suit[0] not in ranks or rank_suit[1] not in suits:
            raise ValueError(f'{rank_suit}: illegal card')
        self.card = rank_suit

    def __repr__(self):
        return self.card

    @abstractmethod
    def value(self):
        """Subclasses should implement this method
        """
        raise NotImplementedError("value method not implemented")

    # card comparison operators
    def __gt__(self, other): return self.value() > other.value()
    def __ge__(self, other): return self.value() >= other.value()
    def __lt__(self, other): return self.value() < other.value()
    def __le__(self, other): return self.value() <= other.value()
    def __eq__(self, other): return self.value() == other.value()
    def __ne__(self, other): return self.value() != other.value()

# ## Poker Card class
# 단, Poker game에서 두 카드를 비교할 때 suit과 무관하게 rank로만 결정한다. 오름차 순서로 나열하면 다음과 같다.
#
#     '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'
#
# Q. `Card` class를 상속받아 Poker game용 `PKCard` class를 정의하라.
# >Hint: 위 순서대로 정수를 return하는 value() method를 implementation해야 한다.

# In[2]:

class PKCard(Card):
    """Card for Poker game
    """
    def value(self):
        #for 문
        if(self.card[0] == '2'):
            return 1
        elif(self.card[0] == '3'):
            return 2
        elif(self.card[0] == '4'):
            return 3
        elif(self.card[0] == '5'):
            return 4
        elif(self.card[0] == '6'):
            return 5
        elif(self.card[0] == '7'):
            return 6
        elif(self.card[0] == '8'):
            return 7
        elif(self.card[0] == '9'):
            return 8
        elif(self.card[0] == 'T'):
            return 9
        elif(self.card[0] == 'J'):
            return 10
        elif(self.card[0] == 'Q'):
            return 11
        elif(self.card[0] == 'K'):
            return 12
        elif(self.card[0] == 'A'):
            return 13

    #def key(self):

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

if __name__ == '__main__':
    c1 = PKCard('QC')
    c2 = PKCard('9D')
    c3 = PKCard('9C')
    print(f'{c1} {c2} {c3}')

    # comparison
    print(c1 > c2 == c3)

    # sorting
    cards = [c1, c2, c3, PKCard('AS'), PKCard('2D')]
    sorted_cards = sorted(cards)
    print(sorted_cards)
    cards.sort()
    print(cards)

# ## Deck class
# Q. 다음 methods를 갖는 `Deck` class를 작성하라.
#
# Methods:
# - `__init__(self, cls)`: `cls`는 card class name
# - shuffle
# - pop
# - `__str__`
# - `__len__(self)` to enable `len` builtin function
# - `__getitem__(self, index)` to enable indexing and slicing as well as iteration

# In[3]:

import random
class Deck:
    def __init__(self, cls):
        """Create a deck of 'cls' card class
        """
        self.deck = []
        for suit in suits:
            for rank in ranks:
                self.deck.append(cls(rank + suit))

    def shuffle(self):
        random.shuffle(self.deck)

    def pop(self):
        return self.deck.pop()

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

    def __str__(self):
        return str(self.deck[:])

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

if __name__ == '__main__':
    deck = Deck(PKCard)  # deck of poker cards
    deck.shuffle()
    c = deck[0]
    print('A deck of', c.__class__.__name__)
    print(deck)

    # testing __getitem__ method
    print(deck[-5:])

    while len(deck) >= 10:
        my_hand = []
        your_hand = []
        for i in range(5):
            for hand in (my_hand, your_hand):
                card = deck.pop()
                hand.append(card)
        my_hand.sort(reverse=True)
        your_hand.sort(reverse=True)
        print(my_hand, '>', your_hand, '?', my_hand > your_hand)

# 위의 예에서 my_hand와 your_hand는 단순히 rank value가 가장 큰 것이 이긴다는 'high card' 족보만으로 따졌을 때이다. Poker의 패는 [List of poker hands](https://en.wikipedia.org/wiki/List_of_poker_hands)에서 보듯이 다양한 족보가 있다.
#
# ## Poker Hands
# 지난 Programming Assignement를 object-oriented로 설계 구현해 보자.
#
# [List of poker hands](https://en.wikipedia.org/wiki/List_of_poker_hands)의 Hand rank category 표에 열거된 패의 rank 0..9 을 역순으로 9..0의 integer로 나열하면 hand ranking의 높고 낮음을 알수 있다. 이 수를 혼동하지 않도록 이라 하자.
#
# Straight, flush, straight flush와 같이 rank가 다른 5장으로 패가 이뤄지는 경우,
# hand ranking이 같으면
# 1. 5장끼리 rank value를 비교해서 판단해야 한다. 즉, reverse(decreading) order로 sorting하여 rank value를 비교하면 된다.
#
# Hand ranking이 같다면, 예를 들어 둘 다 two pair로 동률 이루고 있다면
# 1. 높은 수 one pair의 rank value를 비교하고
# 2. 같으면, 낮은 one pair의 rank value를 비교하고
# 3. 같으면, 나머지 1장 끼리 value를 비교해서 승부를 가른다.
#
# 따라서, 패가 이뤄지는지 찾는 method들은 (hand_ranking, five_cards) tuple로 return한다면
# tuple 비교하는 Python rule에 따라 행하면 충분하게 된다.
# 이때, 이어지는 five_cards는 rank가 높은 순서로 sorting하거나, rank가 같은 것이 있다면(find_a_kind의 경우)
# tie-breaking이 먼저 일어날 카드들을 앞으로 배치해야 list간 비교로 간편히 비교 가능히다. (four cards, tripple cards, high pair)
#
# Q. *PA. Find poker hands* 문제에서 function으로 구현한 것들을 OOP로 rewriting하라.
#
# 중요: hand ranking 찾기, hand ranking이 같을 때 tie-break이 제대로 적용되는지를 검증하기 위한
# 가능한 모든 test case를 20개 이상을 작성함으로써, unit test가 *거의* 모든 경우를 포함하고 있음을
# 보여야 한다.

# In[4]:

class Hands:
    def __init__(self, cards):
        if len(cards) != 5:
            raise ValueError('not 5 cards')
        self.cards = sorted(cards)

    def is_flush(self):#flush조건에 맞으면 ?flush 리턴 아니면 false
        count = 0
        kind_of_suit = self.cards[0][1]
        list_num=[]
        for i in range(5):
            list_num.append(self.cards[i][0])
            list_num.sort(reverse = True)

        for card in self.cards:
            if kind_of_suit == card[1]:
                count += 1

        if count == 5:
            return list_num[0]+' flush'
        else:
            return False

    def is_straight(self):#straight면 ?straight 리턴 아니면 false

        cur_list = []
        for i in range(5):
            cur_list.append(self.cards[i][0])
        for i in range(5):
            if cur_list[i]=='A':
                cur_list[i] = '14'
            elif cur_list[i]=='K':
                cur_list[i] = '13'
            elif cur_list[i]=='Q':
                cur_list[i] = '12'
            elif cur_list[i]=='J':
                cur_list[i] = '11'
            elif cur_list[i]=='T':
                cur_list[i] = '10'
        cur_list = [int (i) for i in cur_list]
        if (cur_list[0]+1==cur_list[1] and
            cur_list[1]+1==cur_list[2] and
            cur_list[2]+1==cur_list[3] and
            cur_list[3]+1==cur_list[4]):
            return str(cur_list[4])+' straight'
        else:
            return False

    def straightflush(self): #straightflush면 ?straightflush 리턴
        cur_list = []        #아니면 false
        for i in range(5):
            cur_list.append(self.cards[i][0])
        for i in range(5):
            if cur_list[i]=='A':
                cur_list[i] = '14'
            elif cur_list[i]=='K':
                cur_list[i] = '13'
            elif cur_list[i]=='Q':
                cur_list[i] = '12'
            elif cur_list[i]=='J':
                cur_list[i] = '11'
            elif cur_list[i]=='T':
                cur_list[i] = '10'
        cur_list = [int (i) for i in cur_list]
        if Hands.is_flush(self) and Hands.is_straight(self):
            return str(cur_list[4])+' straightflush'
        else:
            return False

    def find_a_kind(self): #스트레이트 플러쉬를 제외한 족보
        sslist=[]          #찾는 함수 ex) 4 four of kinds
        valList=[]
        num = []
        for card in range(5):
            valList.append(self.cards[card][0])
        for i in range(0, 5):
            if valList[i] == 'A':
                valList[i] = 14
            elif valList[i] == 'K':
                valList[i] = 13
            elif valList[i] == 'Q':
                valList[i] = 12
            elif valList[i] == 'J':
                valList[i] = 11
            elif valList[i] == 'T':
                valList[i] = 10
        valList = [int (i) for i in valList]

        for i in range(1, 15):
            a = valList.count(i)
            sslist.append(a)
        sslist.reverse()
        #[0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 2, 1, 0, 0]
    #14 high card
        #return sslist
        for i in range(len(sslist)):
            if sslist[i] == 1:
                del sslist[i]
                for j in range(len(sslist)):
                    if sslist[j] == 1:
                        del sslist[j]
                        for x in range(len(sslist)):
                            if sslist[x] == 1:
                                del sslist[x]
                                for z in range(len(sslist)):
                                    if sslist[z] == 1:
                                        num.append(14-i)
                                        return str(num[0])+' High card'
                                    #11111
                                    elif sslist[z] == 2:
                                        num.append(11-z)
                                        return str(num[0])+' One pair'
                                    #11112
                            elif sslist[x] == 2:
                                num.append(12-x)
                                return str(num[0])+' One pair'
                            #1121
                            elif sslist[x] == 3:
                                num.append(12-x)
                                return str(num[0])+' Three of a kind'

                            #113
                    elif sslist[j] == 2:
                        del sslist[j]
                        for x in range(len(sslist)):
                            if sslist[x] == 1:
                                num.append(14-j)
                                return str(num[0])+' One pair'
                            #1211
                            elif sslist[x] == 2:
                                num.append(14-j)
                                return str(num[0])+' Two pair'
                            #122
                    elif sslist[j] == 3:
                        num.append(13-j)
                        return str(num[0])+' Three of a kind'
                    #131
                    elif sslist[j] == 4:
                        num.append(14-j)
                        return str(num[0])+' Four of a kind'
                    #14

            elif sslist[i] == 4:
                num.append(14-i)
                return str(num[0])+' Four of a kinds'
            #41
            #[0, 0, 2, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0]
            elif sslist[i] == 2:
                del sslist[i]
                for j in range(len(sslist)):
                    if sslist[j] == 1:
                        del sslist[j]
                        for x in range(len(sslist)):
                            if sslist[x] == 1:
                                num.append(14-i)
                                return str(num[0])+' One pair'
                            #2111
                            elif sslist[x] == 2:
                                num.append(14-i)
                                return str(num[0])+' Two pair'
                            #212
                    elif sslist[j] == 2:
                        num.append(14-i)
                        return str(num[0])+' Two pair'
                    #221
                    elif sslist[j] == 3:
                        num.append(14-j)
                        return str(num[0])+' Full house'
                    #23

            elif sslist[i] == 3:
                del sslist[i]
                for j in range(len(sslist)):
                    if sslist[j] == 1:
                        num.append(14-i)
                        return str(num[0])+' Three of a kind'
                    #311
                    elif sslist[j] == 2:
                        num.append(14-i)
                        return str(num[0])+' Full house'
                    #32
    def tell_hand_ranking(self): #족보를 취합해 알려주는 함수
        rank_a = Hands.straightflush(self)
        rank_b = Hands.is_flush(self)
        rank_c = Hands.is_straight(self)
        rank_d = Hands.find_a_kind(self)
        if rank_a != False:
            return rank_a
        elif rank_b != False:
            return rank_b
        elif rank_c != False:
            return rank_c
        else:
            return rank_d

    def compare_user(self, other):#두 유저의 족보를보여주고
        a = Hands.numd(self)      #승자를 가리는 코드
        b = Hands.numd(other)     #tie-break 추가
        c = Hands.tell_hand_ranking(self)
        d = Hands.tell_hand_ranking(other)
        e = Hands.tie_break_compare(self, other)
        print(c, d)
        if a>b:
            return 'player1 win'
        elif a<b:
            return 'player2 win'
        elif a==b:
            return e

    def numd(self):#족보의 랭크를 숫자로 매김

        rank_a = Hands.straightflush(self)
        rank_b = Hands.is_flush(self)
        rank_c = Hands.is_straight(self)
        rank_d = Hands.find_a_kind(self)
        for i in range(2,15):
            if rank_a == str(i)+' straightflush':
                return int(i+160)
            elif rank_b == str(i)+' flush':
                return int(i+100)
            elif rank_c == str(i)+' straight':
                return int(i+80)
            elif rank_d == str(i)+' Four of a kind':
                return int(i+140)
            elif rank_d == str(i)+' Full house':
                return int(i+120)
            elif rank_d == str(i)+' Three of a kind':
                return int(i+60)
            elif rank_d == str(i)+' Two pair':
                return int(i+40)
            elif rank_d == str(i)+' One pair':
                return int(i+20)
            elif rank_d == str(i)+' High card':
                return int(i)

    def tie_break(self):#리스트를 만들어 만약 2D 2H 3S 4S 5H면
        sslist=[]       #one pair인패를 제외하고 리스트에
        valList=[]      #[3,4,5]를 추가하여 리턴
        num = []
        for card in range(5):
            valList.append(self.cards[card][0])
        for i in range(0, 5):
            if valList[i] == 'A':
                valList[i] = 14
            elif valList[i] == 'K':
                valList[i] = 13
            elif valList[i] == 'Q':
                valList[i] = 12
            elif valList[i] == 'J':
                valList[i] = 11
            elif valList[i] == 'T':
                valList[i] = 10
        valList = [int (i) for i in valList]

        for i in range(1, 15):
            a = valList.count(i)
            sslist.append(a)

        list_a = []

        for i in range(len(sslist)):
            if sslist[i]==1:
                sslist[i]=0
                list_a.append(i)
                for j in range(len(sslist)):
                    if sslist[j]==1:
                        sslist[j]=0
                        list_a.append(j)
                        for x in range(len(sslist)):
                            if sslist[x]==1:
                                sslist[x]=0
                                list_a.append(x)
                                for y in range(len(sslist)):
                                    if sslist[y]==2:
                                        return list_a
                            elif sslist[x]==2:
                                sslist[x]=0
                                for y in range(len(sslist)):
                                    if sslist[y]==1:
                                        list_a.append(y)
                                        return list_a
                            elif sslist[x]==3:
                                return list_a
                    elif sslist[j]==2:
                        sslist[j] = 0
                        for x in range(len(sslist)):
                            if sslist[x]==1:
                                sslist[x] = 0
                                list_a.append(x)
                                for y in range(len(sslist)):
                                    if sslist[y]==1:
                                        list_a.append(y)
                                        return list_a
                            elif sslist[x]==2:
                                return list_a
                    elif sslist[j]==3:
                        sslist[j] = 0
                        for x in range(len(sslist)):
                            if sslist[x]==1:
                                list_a.append(x)
                                return list_a
                    elif sslist[j]==4:
                        return list_a
            elif sslist[i]==2:
                sslist[i] = 0
                for j in range(len(sslist)):
                    if sslist[j]==1:
                        sslist[j] = 0
                        list_a.append(j)
                        for x in range(len(sslist)):
                            if sslist[x]==1:
                                sslist[x] = 0
                                list_a.append(x)
                                for y in range(len(sslist)):
                                    if sslist[y]==1:
                                        list_a.append(y)
                                        return list_a
                            elif sslist[x]==2:
                                return list_a
                    elif sslist[j]==2:
                        sslist[j] = 0
                        for x in range(len(sslist)):
                            if sslist[x]==1:
                                list_a.append(x)
                                return list_a
                    elif sslist[j]==3:
                        list_a.append(i)
                        return list_a
            elif sslist[i]==3:
                sslist[i] = 0
                for j in range(len(sslist)):
                    if sslist[j]==1:
                        sslist[j] = 0
                        list_a.append(j)
                        for x in range(len(sslist)):
                            if sslist[x]==1:
                                list_a.append(x)
                                return list_a
                    elif sslist[j]==2:
                        list_a.append(j)
                        return list_a
            elif sslist[i]==4:
                sslist[i] = 0
                for j in range(len(sslist)):
                    if sslist[j]==1:
                        list_a.append(j)
                        return list_a
    def tie_break_compare(self, other):#tie-break를 받아서
        a = Hands.tie_break(self)      #앞서받은 리스트를 역순으로
        b = Hands.tie_break(other)     #하여 비교하여 승자 결정
        if a == None:
            return 'No tie-break'
        if b == None:
            return 'No tie-break'
        if a != None:
            a.sort(reverse = True)
        if b != None:
            b.sort(reverse = True)

        if a[0]>b[0]:
            return 'tie-break 1player win'
        elif a[0]<b[0]:
            return 'tie-break 2player win'
        elif a[0]==b[0]:
            if a[1]>b[1]:
                return 'tie-break 1player win'
            elif a[1]<b[1]:
                return 'tie-break 2player win'
            elif a[1]==b[1]:
                if a[2]>b[2]:
                    return 'tie-break 1player win'
                elif a[2]<b[2]:
                    return 'tie-break 2player win'

if __name__ == '__main__':
    import sys
    def test(did_pass):
        """  Print the result of a test.  """
        linenum = sys._getframe(1).f_lineno   # Get the caller's line number.
        if did_pass:
            msg = "Test at line {0} ok.".format(linenum)
        else:
            msg = ("Test at line {0} FAILED.".format(linenum))
        print(msg)

    # your test cases here

deck = Deck(PKCard)
deck.shuffle()
my_hand = [PKCard('2D'),PKCard('2D'),PKCard('4D'),PKCard('6H'),PKCard('7D')]
your_hand = [PKCard('2S'),PKCard('2H'),PKCard('8C'),PKCard('7S'),PKCard('6S')]
#a = Hands(deck[:5])  <ㅡㅡㅡㅡㅡ 이용하면 랜덤출력 가능합니다
#b = Hands(deck[-5:]) <ㅡㅡㅡㅡㅡ 이용하면 랜덤출력 가능합니다
c = Hands(my_hand)
d = Hands(your_hand)
print(c.tell_hand_ranking())
print(d.tell_hand_ranking())
print(c.numd())
print(d.numd())
print(c.tie_break())
print(d.tie_break())
print(c.tie_break_compare(d))
print(c.compare_user(d))

a1=[PKCard('3S'),PKCard('4S'),PKCard('5S'),PKCard('6S'),PKCard('7S')]
b1=[PKCard('3D'),PKCard('4H'),PKCard('KD'),PKCard('6C'),PKCard('7D')]
a1 = Hands(a1)
b1 = Hands(b1)
a2=[PKCard('3S'),PKCard('3H'),PKCard('3C'),PKCard('3D'),PKCard('7S')]
b2=[PKCard('7H'),PKCard('7D'),PKCard('3D'),PKCard('TS'),PKCard('KS')]
a2 = Hands(a2)
b2= Hands(b2)
a3=[PKCard('3S'),PKCard('5S'),PKCard('8S'),PKCard('KS'),PKCard('6S')]
b3=[PKCard('QS'),PKCard('7C'),PKCard('KS'),PKCard('5H'),PKCard('8H')]
a3 = Hands(a3)
b3 = Hands(b3)
a4=[PKCard('3S'),PKCard('2H'),PKCard('4C'),PKCard('6D'),PKCard('5S')]
b4=[PKCard('3H'),PKCard('QH'),PKCard('6S'),PKCard('7D'),PKCard('2S')]
a4 = Hands(a4)
b4 = Hands(b4)
a5=[PKCard('3S'),PKCard('3H'),PKCard('3C'),PKCard('2D'),PKCard('2S')]
b5=[PKCard('4S'),PKCard('6H'),PKCard('QC'),PKCard('2D'),PKCard('JS')]
a5 = Hands(a5)
b5 = Hands(b5)
a6=[PKCard('2S'),PKCard('2H'),PKCard('3C'),PKCard('3D'),PKCard('7S')]
b6=[PKCard('4H'),PKCard('7H'),PKCard('2C'),PKCard('3H'),PKCard('KC')]
a6 = Hands(a6)
b6 = Hands(b6)
a7=[PKCard('3S'),PKCard('3H'),PKCard('6C'),PKCard('8C'),PKCard('TC')]
b7=[PKCard('4S'),PKCard('4H'),PKCard('3C'),PKCard('2D'),PKCard('7S')]
a7 = Hands(a7)
b7 = Hands(b7)
a8=[PKCard('3S'),PKCard('5H'),PKCard('2C'),PKCard('KD'),PKCard('AS')]
b8=[PKCard('4S'),PKCard('2H'),PKCard('5C'),PKCard('QD'),PKCard('TS')]
a8 = Hands(a8)
b8 = Hands(b8)
a9=[PKCard('3S'),PKCard('3H'),PKCard('7C'),PKCard('6D'),PKCard('KS')]
b9=[PKCard('3D'),PKCard('3C'),PKCard('6C'),PKCard('2D'),PKCard('7S')]
a9 = Hands(a9)
b9 = Hands(b9)
a10=[PKCard('2D'),PKCard('2D'),PKCard('4D'),PKCard('6H'),PKCard('7D')]
b10=[PKCard('2S'),PKCard('2H'),PKCard('8C'),PKCard('7S'),PKCard('6S')]
a10 = Hands(a10)
b10 = Hands(b10)
a11=[PKCard('JC'),PKCard('JS'),PKCard('3S'),PKCard('3D'),PKCard('JH')]
b11=[PKCard('JD'),PKCard('2C'),PKCard('JH'),PKCard('7C'),PKCard('7S')]
a11 = Hands(a11)
b11 = Hands(b11)
a12=[PKCard('JC'),PKCard('6S'),PKCard('KS'),PKCard('3S'),PKCard('JH')]
b12=[PKCard('2D'),PKCard('6D'),PKCard('3D'),PKCard('2S'),PKCard('7S')]
a12 = Hands(a12)
b12 = Hands(b12)
a13=[PKCard('JC'),PKCard('6S'),PKCard('6H'),PKCard('5S'),PKCard('JH')]
b13=[PKCard('4D'),PKCard('JS'),PKCard('JD'),PKCard('6C'),PKCard('6S')]
a13 = Hands(a13)
b13 = Hands(b13)
a14=[PKCard('8C'),PKCard('9S'),PKCard('TS'),PKCard('JS'),PKCard('QS')]
b14=[PKCard('AD'),PKCard('7S'),PKCard('JH'),PKCard('JC'),PKCard('7S')]
a14 = Hands(a14)
b14 = Hands(b14)
a15=[PKCard('AD'),PKCard('KD'),PKCard('JD'),PKCard('3D'),PKCard('7D')]
b15=[PKCard('5C'),PKCard('TS'),PKCard('QS'),PKCard('KS'),PKCard('JH')]
a15 = Hands(a15)
b15 = Hands(b15)
a16=[PKCard('4D'),PKCard('6D'),PKCard('5D'),PKCard('8D'),PKCard('7D')]
b16=[PKCard('9D'),PKCard('9H'),PKCard('8S'),PKCard('5D'),PKCard('9C')]
a16 = Hands(a16)
b16 = Hands(b16)
a17=[PKCard('4D'),PKCard('6D'),PKCard('5D'),PKCard('9D'),PKCard('8D')]
b17=[PKCard('2S'),PKCard('3S'),PKCard('4S'),PKCard('6S'),PKCard('7S')]
a17 = Hands(a17)
b17 = Hands(b17)
a18=[PKCard('JD'),PKCard('AD'),PKCard('KD'),PKCard('QD'),PKCard('TD')]
b18=[PKCard('6D'),PKCard('2S'),PKCard('4H'),PKCard('5C'),PKCard('3S')]
a18 = Hands(a18)
b18 = Hands(b18)
a19=[PKCard('JC'),PKCard('6S'),PKCard('KS'),PKCard('3S'),PKCard('JH')]
b19=[PKCard('AD'),PKCard('KH'),PKCard('JD'),PKCard('JS'),PKCard('7S')]
a19 = Hands(a19)
b19 = Hands(b19)
a20=[PKCard('JC'),PKCard('6S'),PKCard('KC'),PKCard('3S'),PKCard('JH')]
b20=[PKCard('KD'),PKCard('KS'),PKCard('JS'),PKCard('JD'),PKCard('7S')]
a20 = Hands(a20)
b20 = Hands(b20)
print(a1.compare_user(b1))
print()
print(a2.compare_user(b2))
print()
print(a3.compare_user(b3))
print()
print(a4.compare_user(b4))
print()
print(a5.compare_user(b5))
print()
print(a6.compare_user(b6))
print()
print(a7.compare_user(b7))
print()
print(a8.compare_user(b8))
print()
print(a9.compare_user(b9))
print()
print(a10.compare_user(b10))
print()
print(a11.compare_user(b11))
print()
print(a12.compare_user(b12))
print()
print(a13.compare_user(b13))
print()
print(a14.compare_user(b14))
print()
print(a15.compare_user(b15))
print()
print(a16.compare_user(b16))
print()
print(a17.compare_user(b17))
print()
print(a18.compare_user(b18))
print()
print(a19.compare_user(b19))
print()
print(a20.compare_user(b20))


#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse

def arguments():
    # Handle command line arguments
    parser = argparse.ArgumentParser(description='Adventofcode.')
    parser.add_argument('-f', '--file', required=True)

    args = parser.parse_args()

    return args

class CorruptionChecksum: # pylint: disable=too-few-public-methods, too-many-instance-attributes

    def __init__(self):
        self.checksum = 0
        self.checksum_part2 = 0

    def calculate_checksum_part1(self, numbers):
        for row in numbers:
            self.checksum = self.checksum + (max(row) - min(row))

    def calculate_checksum_part2(self, numbers):
        for row in numbers:
            for index, number in enumerate(row):
                for idx, num in enumerate(row):
                    if idx == index:
                        continue
                    else:
                        if number % num == 0:
                            self.checksum_part2 = self.checksum_part2 + int((number / num))

def main():
    args = arguments()
    work_list = []

    with open(args.file) as file:
        input_file = file.read().strip("\t").split("\n")

    for row in input_file:
        row = row.replace(" ", ",")
        row = row.replace("\t", ",")
        row = row.split(",")
        row = [int(x) for x in row]
        work_list.append(row)

    corruption_checksum = CorruptionChecksum()
    corruption_checksum.calculate_checksum_part1(work_list)
    corruption_checksum.calculate_checksum_part2(work_list)
    print("part1:", corruption_checksum.checksum)
    print("part2:", corruption_checksum.checksum_part2)

if __name__ == '__main__':
    main()


from .. import db
import csv

class Movie(db.Model):
    __tablename__ = 'movies'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=False)
    url = db.Column(db.String(100), nullable=False)
    rank = db.Column(db.Integer, nullable=False, index=True)
    category = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(100))
    cast = db.Column(db.String(100))
    score = db.Column(db.Float, nullable=False)
    picture = db.Column(db.String(100), nullable=False)

    def __init__(self, name, category, cast, score, rank, description, picture, url):
        self.name = name
        self.category = category
        self.cast = cast
        self.score = score
        self.rank = rank
        self.description = description
        self.picture = picture
        self.url = url

def read_movie(filename):
    """read csv file from out side"""
    with open(filename, 'r', encoding="utf-8") as f:
        reader = csv.reader(f)
        result = []
        for item in reader:
            if reader.line_num == 1:
                continue
            result.append(item)

    for i in result:
        try:
            movie = Movie(*i)
        except TypeError as e:
            print(e)
        else:
            db.session.add(movie)
        finally:
            db.session.commit()


from flask import Flask, jsonify, request, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Resource, Api
from flask_migrate import Migrate
from datetime import datetime
from models import db, Teacher, Student, Class  # Import your models here

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///chatwave.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.json.compact = False

migrate = Migrate(app,db)

db.init_app(app)
api = Api(app)

class TeacherResource(Resource):
    def get(self):
        teachers = [teacher.to_dict() for teacher in Teacher.query.all()]
        return make_response(jsonify(teachers), 200)

    def post(self):
        data = request.json
        new_teacher = Teacher(
            first_name=data['first_name'],
            last_name=data['last_name'],
            salary=data['salary']
        )
        db.session.add(new_teacher)
        db.session.commit()
        teacher_dict = new_teacher.to_dict()
        return make_response(jsonify(teacher_dict), 201)

class StudentResource(Resource):
    def get(self):
        students = [student.to_dict() for student in Student.query.all()]
        return make_response(jsonify(students), 200)

    def post(self):
        data = request.json
        new_student = Student(
            first_name=data['first_name'],
            last_name=data['last_name'],
            gender=data['gender'],
            age=data['age'],
            grade=data['grade']
        )
        db.session.add(new_student)
        db.session.commit()
        student_dict = new_student.to_dict()
        return make_response(jsonify(student_dict), 201)

class ClassResource(Resource):
    def get(self):
        classes = [class_obj.to_dict() for class_obj in Class.query.all()]
        return make_response(jsonify(classes), 200)

    def post(self):
        data = request.json
        new_class = Class(
            title=data['title'],
            teacher_id=data['teacher_id'],
            student_id=data['student_id'],
            start_time=datetime.now(),
            end_time=datetime.now()
        )
        db.session.add(new_class)
        db.session.commit()
        class_dict = new_class.to_dict()
        return make_response(jsonify(class_dict), 201)

class TeacherByIdResource(Resource):
    def get(self, id):
        teacher = Teacher.query.filter_by(id=id).first()
        if teacher:
            teacher_dict = teacher.to_dict()
            return make_response(jsonify(teacher_dict), 200)
        else:
            return make_response(jsonify({'message': 'Teacher not found'}), 404)

    def put(self, id):
        teacher = Teacher.query.filter_by(id=id).first()
        if teacher:
            data = request.json
            teacher.first_name = data.get('first_name', teacher.first_name)
            teacher.last_name = data.get('last_name', teacher.last_name)
            teacher.salary = data.get('salary', teacher.salary)
            db.session.commit()
            teacher_dict = teacher.to_dict()
            return make_response(jsonify(teacher_dict), 200)
        else:
            return make_response(jsonify({'message': 'Teacher not found'}), 404)

    def delete(self, id):
        teacher = Teacher.query.filter_by(id=id).first()
        if teacher:
            db.session.delete(teacher)
            db.session.commit()
            return make_response(jsonify({'message': 'Teacher deleted'}), 200)
        else:
            return make_response(jsonify({'message': 'Teacher not found'}), 404)

class StudentByIdResource(Resource):
    def get(self, id):
        student = Student.query.filter_by(id=id).first()
        if student:
            student_dict = student.to_dict()
            return make_response(jsonify(student_dict), 200)
        else:
            return make_response(jsonify({'message': 'Student not found'}), 404)

    def put(self, id):
        student = Student.query.filter_by(id=id).first()
        if student:
            data = request.json
            student.first_name = data.get('first_name', student.first_name)
            student.last_name = data.get('last_name', student.last_name)
            student.gender = data.get('gender', student.gender)
            student.age = data.get('age', student.age)
            student.grade = data.get('grade', student.grade)
            db.session.commit()
            student_dict = student.to_dict()
            return make_response(jsonify(student_dict), 200)
        else:
            return make_response(jsonify({'message': 'Student not found'}), 404)

    def delete(self, id):
        student = Student.query.filter_by(id=id).first()
        if student:
            db.session.delete(student)
            db.session.commit()
            return make_response(jsonify({'message': 'Student deleted'}), 200)
        else:
            return make_response(jsonify({'message': 'Student not found'}), 404)

class ClassByIdResource(Resource):
    def get(self, id):
        class_obj = Class.query.filter_by(id=id).first()
        if class_obj:
            class_dict = class_obj.to_dict()
            return make_response(jsonify(class_dict), 200)
        else:
            return make_response(jsonify({'message': 'Class not found'}), 404)

    def put(self, id):
        class_obj = Class.query.filter_by(id=id).first()
        if class_obj:
            data = request.json
            class_obj.title = data.get('title', class_obj.title)
            class_obj.teacher_id = data.get('teacher_id', class_obj.teacher_id)
            class_obj.student_id = data.get('student_id', class_obj.student_id)
            db.session.commit()
            class_dict = class_obj.to_dict()
            return make_response(jsonify(class_dict), 200)
        else:
            return make_response(jsonify({'message': 'Class not found'}), 404)

    def delete(self, id):
        class_obj = Class.query.filter_by(id=id).first()
        if class_obj:
            db.session.delete(class_obj)
            db.session.commit()
            return make_response(jsonify({'message': 'Class deleted'}), 200)
        else:
            return make_response(jsonify({'message': 'Class not found'}), 404)

api.add_resource(TeacherResource, '/teachers')
api.add_resource(StudentResource, '/students')
api.add_resource(ClassResource, '/classes')
api.add_resource(TeacherByIdResource, '/teachers/<int:id>')
api.add_resource(StudentByIdResource, '/students/<int:id>')
api.add_resource(ClassByIdResource, '/classes/<int:id>')

if __name__ == '__main__':
    app.run()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

""" This package read binary file to get all strings or read it with hexareader. """

###################
#    This package read binary file to get all strings or read it with hexareader.
#    Copyright (C) 2021  Maurice Lambert

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.
###################

print(
"""
BinaryFileReader  Copyright (C) 2021  Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.
"""
)

try:
    from .Strings import Strings, main as get_strings
    from .HexaReader import HexaReader, main as hexaread
except ImportError:
    from Strings import Strings, main as get_strings
    from HexaReader import HexaReader, main as hexaread

from sys import argv

help_message = """USAGE: python3 -m BinaryFileReader module filename
    [module] must be "strings" or "hexareader"
    [filename] must be an existing binary file
"""

if len(argv) > 1:
    module = argv.pop(1).lower()

    if module == "strings":
        get_strings()
        exit(0)
    elif module == "hexareader":
        hexaread()
        exit(0)
    else:
        print(help_message)
        exit(1)
else:
    print(help_message)
    exit(1)


import os
from subprocess import Popen, PIPE
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from .settings import *

@csrf_exempt
def index(request) :
    params = {
        'title' : 'Japanese Stable Diffusion Test',
        'reload' : False,
    }
    s = readTest()
    if s == "" :
        if request.POST :
            writeSentence(request.POST['sentence'])
            Popen(TEST_COM, shell=True, stdout=PIPE, stderr=PIPE, text=True)
            params['prompt'] = '画像生成実行中...'
            params['sentence'] = request.POST['sentence']
            params['reload'] = True
    else :
        params['sentence'] = readSentence()
        if s == TEST_PROCESS :
            params['prompt'] = '画像生成実行中...'
            params['reload'] = True
            params['imglist'] = []
            for imgfile in IMGLIST :
                if os.path.exists(os.path.join(IMGDIR, imgfile)) :
                    params['imglist'].append(imgfile)
            if len(params['imglist']) <= 0 :
                del params['imglist']
        elif s == TEST_FINISH :
            writeTest("")
            params['prompt'] = '画像生成完了'
            params['img'] = IMGFILE
            params['imglist'] = IMGLIST
    return render(request, 'JapaneseStableDiffusion/index.html', params)

def readTest() :
    s = ""
    if os.path.exists(TEST_TXT) :
        with open(TEST_TXT) as f :
            s = f.read()
    return s

def writeTest(s) :
    with open(TEST_TXT, mode="w") as f :
        f.write(s)
    return

def readSentence() :
    s = ""
    if os.path.exists(SENTENCE_FILE) :
        with open(SENTENCE_FILE) as f :
            s = f.read()
    return s

def writeSentence(s) :
    with open(SENTENCE_FILE, mode="w") as f :
        f.write(s)
    return


import os
import numpy as np
from matplotlib import pyplot as plt
from scipy import stats, signal
from keras.models import Model, Sequential
from keras.layers import Conv2D,Conv1D, Dropout, MaxPooling2D, Flatten, Dense, Input , concatenate, MaxPooling1D, BatchNormalization, AveragePooling2D,AveragePooling1D
from keras.losses import categorical_crossentropy
from keras.utils import plot_model
from keras.optimizers import Adam, schedules
from keras import metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Normalizer , StandardScaler
from sklearn.metrics import roc_curve, roc_auc_score,auc , precision_recall_curve,  confusion_matrix, multilabel_confusion_matrix
from sklearn.utils import shuffle

def get_names():

    #feats = ['mfcc', 'del-mfcc','del-del-mfcc', 'Spect', 'rms', 'dSdT', 'dS2dT2','zero_crossing_rate', 'spectral_centroid', 'spectral_bandwidth']
    feats = ['mfcc' ,'mel_spec_dev_2']
    dims = {
            'STFT':'image',
            'Spect':'image',
            'dSdT':'image',
            'mel_spec_dev_2':'image',
            'mfcc':'coeffs',
            'del-mfcc':'coeffs',
            'del-del-mfcc':'coeffs',
            'rms':'stats',
            'zero_crossing_rate':'stats',
            'spectral_centroid':'stats',
            'spectral_bandwidth':'stats'
            }
    return feats , dims

def sort_data(feat_space,best_features = None):

    X = {}
    Y = {}

    class_no = 0
    stat_names =[
            'spectral_centroid',
            'spectral_bandwidth',
            'rms',
            'zero_crossing_rate']

    for spect_path in os.listdir(feat_space):
        data = {}
        if '.npy' in spect_path and 'Copy' not in spect_path:
            label, ind = spect_path.split('_')

        obj = np.load(feat_space+spect_path, allow_pickle=True)

        if best_features == None:
            stats = obj[0,0]
            data['STFT'] = obj[0,1]
            data['mfcc'] = obj[0,2]
            data['del-mfcc'] = obj[0,3]
            data['del-del-mfcc'] = obj[0,4]
            data['Spect'] = obj[0,5]
            data['dSdT'] = obj[0,6]
            data['dS2dT2'] = obj[0,7]

            for i in range(len(stat_names)):
                data[stat_names[i]] = stats[i,:]

        else:
            for feature in range(len(best_features) ):
                data[best_features[feature] ] = obj[0,feature ]

        if label not in Y.keys():
          Y[label] = class_no
          X[class_no] = []
          class_no += 1

        this_class = Y[label]
        X[this_class].append(data)

    return X , class_no

def split_test_train_custom(X_, class_no, ratio=0.6):

  X_train = []
  Y_train = []
  X_test = []
  Y_test = []

  for i in range(class_no):

      X_i = X_[i]

      available_samples = len(X_i)
      no_train_samples = int(available_samples*ratio)

      train_samples = np.random.choice(range(available_samples), no_train_samples, replace=False)

      X_train.extend([X_i[k] for k in train_samples])
      Y_train.extend([i for k in range(no_train_samples)])

      X_test.extend([X_i[k] for k in range(available_samples) if k not in train_samples])
      Y_test.extend([i for k in range(available_samples-no_train_samples)])

  return np.array(X_train), np.array(X_test), np.array(Y_train), np.array(Y_test)

def one_hot_encoder(_Y_train):

    classes = _Y_train.max()+1
    class_labels = np.zeros((classes))
    _Y_train2 = []

    for y in _Y_train:
        t = np.copy(class_labels)
        t[y] = 1
        _Y_train2.append(t)

    _Y_train2 = np.array(_Y_train2)

    return _Y_train2

def normalize_reshape(x_train, x_test, feats):
    Xtrain = {}
    Xtest = {}

    for f in feats:
        train_len = len(x_train)
        test_len = len(x_test)
        orig_shape = x_train[0][f].shape
        dims = len(orig_shape)
        norm = Normalizer()

        if dims > 1:
            h,w = orig_shape
            X0 = np.array([x[f].flatten() for x in x_train])
            Xf = np.array([x[f].flatten() for x in x_test])

            X0 = norm.fit_transform(X0).reshape(train_len, h, w)
            Xf = norm.transform(Xf).reshape(test_len, h, w)

        else:
            l = orig_shape[0]
            X0 = np.array([x[f] for x in x_train])
            Xf = np.array([x[f] for x in x_test])

            X0 = norm.fit_transform(X0).reshape(train_len, l, 1)
            Xf = norm.transform(Xf).reshape(test_len, l, 1)

        Xtrain[f] = X0
        Xtest[f] = Xf

    return Xtrain, Xtest

def get_model_block(inp_shape, dims, p=0.5):

    if dims=='image':

      inp = Input(shape= (inp_shape[0], inp_shape[1], 1))
      x = Conv2D(256, kernel_size=(3,3), activation='relu', input_shape=inp_shape)(inp)
      x = MaxPooling2D(pool_size=(2,2))(x)
      x = Dropout(1*p)(x)
      x = Conv2D(128, kernel_size=(3,3), activation='relu')(x)
      x = MaxPooling2D(pool_size=(2,2))(x)
      x = Dropout(1*p)(x)
      x = Conv2D(64, kernel_size=(3,3), activation='relu')(x)
      x = MaxPooling2D(pool_size=(2,2))(x)
      x = Dropout(1*p)(x)
      x = Conv2D(32, kernel_size=(3,3), activation='relu')(x)
      x = MaxPooling2D(pool_size=(2,2))(x)
      x = Dropout(2*p)(x)
      x = Conv2D(16, kernel_size=(3,3), activation='relu')(x)
      x = MaxPooling2D(pool_size=(2,2))(x)
      x = Dropout(3*p)(x)

      connection_layer = Flatten()(x)

    if dims=='coeffs':

      inp = Input(shape= (inp_shape[0], inp_shape[1], 1))
      x = Conv2D(128, kernel_size=(3,3), activation='relu', input_shape=inp_shape)(inp)
      x = MaxPooling2D(pool_size=(2,2))(x)
      x = Dropout(1*p)(x)
      x = Conv2D(64, kernel_size=(3,3), activation='relu')(x)
      x = MaxPooling2D(pool_size=(2,2))(x)
      x = Dropout(1*p)(x)
      x = Conv2D(32, kernel_size=(3,3), activation='relu')(x)
      x = MaxPooling2D(pool_size=(2,2))(x)
      x = Dropout(2*p)(x)
      x = Conv2D(16, kernel_size=(3,3), activation='relu')(x)
      x = Dropout(3*p)(x)

      connection_layer = Flatten()(x)

    if dims=='stats':
      inp = Input(shape = (inp_shape[0],1) )
      x = Conv1D(128, kernel_size=3, activation='relu', input_shape=inp_shape)(inp)
      x = MaxPooling1D(pool_size=2)(x)
      x = Dropout(p)(x)
      x = Conv1D(64, kernel_size=3, activation='relu')(x)
      x = MaxPooling1D(pool_size=2)(x)
      x = Dropout(2*p)(x)
      x = Conv1D(32, kernel_size=3, activation='relu')(x)
      x = MaxPooling1D(pool_size=2)(x)
      x = Dropout(3*p)(x)

      connection_layer = Flatten()(x)

    m = Model(inputs = inp,outputs = connection_layer)

    return m

def model_output(models,num_class,lr=1e-3, p=0.5):

    if len(models) > 1 :
      outputs = concatenate([ m.output for m in models ])
      inputs = [ m.input for m in models ]

    else:
      outputs = concatenate([models[0].output,models[0].output])
      inputs = [models[0].input]

    output_layer = Dense(num_class, activation='softmax')(outputs)

    lr_schedule = schedules.ExponentialDecay(
    initial_learning_rate=lr,
    decay_steps= 35,
    decay_rate=0.97)

    opt = Adam(lr_schedule)
    m = Model(inputs = inputs ,outputs = output_layer)
    m.compile(loss=categorical_crossentropy, optimizer=opt, metrics=['accuracy'])
    return m

def training_model(X_,dims,feats,class_no):

  best_feats = ['mfcc', 'mel_spec_dev_2']
  lr=1e-3
  batch_size = class_no
  dropout_block= 0.1
  dropout_out= 0.1
  epochs=50
  split = 0.7
  v = 1

  x_train_best = []
  x_test_best = []
  m_list = []
  x_train_i = []
  x_test_i = []

  x_train_round,x_test_round, y_train,y_test = split_test_train_custom(X_,class_no, ratio=split)

  y_train = one_hot_encoder(y_train)
  y_test = one_hot_encoder(y_test)
  x_train_round, x_test_round = normalize_reshape(x_train_round, x_test_round, feats)

  for f in best_feats:

    x_train_best.append(x_train_round[f])
    x_test_best.append(x_test_round[f])

    m_list.append(get_model_block(x_test_round[f][0].shape, dims[f], p=dropout_block))

  m = model_output(m_list, num_class=y_train.shape[-1],lr=lr, p=dropout_out)

  x_train_i.extend([block for block in x_train_best])
  x_test_i.extend([block for block in x_test_best])

  h = m.fit(x_train_i, y_train, epochs=epochs, batch_size=batch_size,verbose=v,shuffle=True)
  loss, acc = m.evaluate(x_test_i, y_test)
  y_hat = m.predict(x_test_i)

  print('train acc:' + str(max(h.history['accuracy'])))
  print('test loss:' + str(loss) )
  print('test acc:' + str(acc) )

  #m.save_weights(filepath+'trained_model', overwrite=True, save_format=None, options=None)

  return m, y_test, y_hat


class Create_Partitions(object):
	def __init__(self,number=1):
		self.number = number
		n = self.number
		partition_list= []
		partition_list.append([[]])
		partition_list.append([[1,]])
		for k in range(2, n+1):
			partitions = []
			for i in range(k):
				for partition in partition_list[i]:
					tmp_list = list(sorted([k-i] + partition))
					if tmp_list not in partitions:
						partitions.append(tmp_list)
			partition_list.append(partitions)
		self.partitions = partition_list[n]

	def possible_partitions(self):
		return self.partitions

	def get_number(self):
		return self.number


import os
import pandas as pd
import numpy as np
from dotenv import load_dotenv
load_dotenv()

# Purpose is to create a clean csv with Names (id), Gender, avg Number of messages sent, number of likes per user's average message
# To see if the average number of messages sent by a user can be predicted from the number of likes they receive and their
# Gender

messagedata = os.environ.get('MESSAGEDATA')
df = pd.read_csv(messagedata)

# Create a dictionary that matches a persons name to their user_id
users = df.set_index('user_id')['name'].to_dict()

# Creates a new dataframe with only names and sender_id
df_groupme = pd.DataFrame.from_dict(users, orient = 'index')

# Add total number of messages to clean data
df_groupme['Total Messages'] = df['user_id'].value_counts()
df_groupme = df_groupme.reset_index() # reseting index to not include 'user_id'
df_groupme = df_groupme.rename(columns = {'index': 'user_id'}) # correcting column label

# Create dataframe with only the like columns & user_id
df_likes = df.loc[:,'fav0':'user_id']
df_likes = df_likes.replace(np.nan, 0, regex=True) # Replacing NaNs with 0

# Iteratesthrough columns and replace User_id that liked the message with int 1
for label, content in df_likes.loc[:,'fav0':'fav19'].items(): # iterates through the columns as a series
	for like in content:
		value = 1
		if like != 0:
			df_likes.replace(to_replace = like, value = value, inplace = True)

df_likes['total_likes'] = df_likes.loc[:,'fav0':'fav19'].sum(axis = 1) # summation of likes for a given msg

# Creates dataframe with total sum of likes on messages and user_id
df_likes_sums = df_likes.loc[:, 'user_id':'total_likes'].groupby('user_id')['total_likes'].sum()
df_groupme_merged =  pd.merge(df_likes_sums, df_groupme, on='user_id', how='inner') # inner join of dataframes on 'user_id'

# Export df as csv
df_groupme_merged.to_csv('clean_msg_data.csv')


import torch
from typing import List, Tuple
import math

SORTING_NETWORK_TYPE = List[torch.tensor]

def s_best(x):
    return torch.clamp(x, -0.25, 0.25) + .5 + \
        ((x > 0.25).float() - (x < -0.25).float()) * (0.25 - 1/16/(x.abs()+1e-10))

class NormalCDF(torch.autograd.Function):
    def forward(ctx, x, sigma):
        ctx.save_for_backward(x, torch.tensor(sigma))
        return 0.5 + 0.5 * torch.erf(x / sigma / math.sqrt(2))

    def backward(ctx, grad_y):
        x, sigma = ctx.saved_tensors
        return grad_y * 1 / sigma / math.sqrt(math.pi * 2) * torch.exp(-0.5 * (x/sigma).pow(2)), None

def execute_sort(
        sorting_network,
        vectors,
        steepness=10.,
        art_lambda=0.25,
        distribution='cauchy'
):
    x = vectors
    X = torch.eye(vectors.shape[1], dtype=x.dtype, device=x.device).repeat(x.shape[0], 1, 1)

    for split_a, split_b, combine_min, combine_max in sorting_network:
        split_a = split_a.type(x.dtype)
        split_b = split_b.type(x.dtype)
        combine_min = combine_min.type(x.dtype)
        combine_max = combine_max.type(x.dtype)

        a, b = x @ split_a.T, x @ split_b.T

        # float conversion necessary as PyTorch doesn't support Half for sigmoid as of 25. August 2021
        new_type = torch.float32 if x.dtype == torch.float16 else x.dtype

        if distribution == 'logistic':
            alpha = torch.sigmoid((b-a).type(new_type) * steepness).type(x.dtype)

        elif distribution == 'logistic_phi':
            alpha = torch.sigmoid((b-a).type(new_type) * steepness / ((a-b).type(new_type).abs() + 1.e-10).pow(art_lambda)).type(x.dtype)

        elif distribution == 'gaussian':
            v = (b - a).type(new_type)
            alpha = NormalCDF.apply(v, 1 / steepness)
            alpha = alpha.type(x.dtype)

        elif distribution == 'reciprocal':
            v = steepness * (b - a).type(new_type)
            alpha = 0.5 * (v / (2 + v.abs()) + 1)
            alpha = alpha.type(x.dtype)

        elif distribution == 'cauchy':
            v = steepness * (b - a).type(new_type)
            alpha = 1 / math.pi * torch.atan(v) + .5
            alpha = alpha.type(x.dtype)

        elif distribution == 'optimal':
            v = steepness * (b - a).type(new_type)
            alpha = s_best(v)
            alpha = alpha.type(x.dtype)

        else:
            raise NotImplementedError('softmax method `{}` unknown'.format(distribution))

        aX = X @ split_a.T
        bX = X @ split_b.T
        w_min = alpha.unsqueeze(-2) * aX + (1-alpha).unsqueeze(-2) * bX
        w_max = (1-alpha).unsqueeze(-2) * aX + alpha.unsqueeze(-2) * bX
        X = (w_max @ combine_max.T.unsqueeze(-3)) + (w_min @ combine_min.T.unsqueeze(-3))
        x = (alpha * a + (1-alpha) * b) @ combine_min.T + ((1-alpha) * a + alpha * b) @ combine_max.T
    return x, X

def sort(
        sorting_network: SORTING_NETWORK_TYPE,
        vectors: torch.Tensor,
        steepness: float = 10.0,
        art_lambda: float = 0.25,
        distribution: str = 'cauchy'
) -> Tuple[torch.Tensor, torch.Tensor]:
    """Sort a matrix along axis 1 using differentiable sorting networks. Return the permutation matrix.

    Positional arguments:
    sorting_network
    vectors -- the matrix to sort along axis 1; sorted in-place

    Keyword arguments:
    steepness -- relevant for sigmoid and sigmoid_phi interpolation (default 10.0)
    art_lambda -- relevant for logistic_phi interpolation (default 0.25)
    distribution -- how to interpolate when swapping two numbers; (default 'cauchy')
    """
    assert sorting_network[0][0].device == vectors.device, (
        f"The sorting network is on device {sorting_network[0][0].device} while the vectors are on device"
        f" {vectors.device}, but they both need to be on the same device."
    )
    return execute_sort(
        sorting_network=sorting_network,
        vectors=vectors,
        steepness=steepness,
        art_lambda=art_lambda,
        distribution=distribution
    )


import math
import sys
sys.stdout = open('./output.txt', 'w')
sys.stdin = open('./input.txt', 'r')

def answer_finder():
    x,y = [int(x) for x in input().split()]
    if x == y:
        print(0)
        return
    if y < x:
        val1 = x - y
        val = math.ceil(val1/2) if not val1%2 else math.ceil(val1/2) + 1

        print(val)
    else:
        print(y-x)

test_cases = int(input())
while test_cases:
    test_cases -= 1
    answer_finder()


from typing import TYPE_CHECKING, Union

from loguru import logger
from starknet_py.net.account.account import Account
from starknet_py.net.client_errors import ClientError
from starknet_py.net.models.transaction import DeployAccount

from src import enums
from modules.base import ModuleBase
from modules.deploy.custom_curve_signer import BraavosCurveSigner
from src.schemas.action_models import ModuleExecutionResult
from utils.key_manager.key_manager import get_key_pair_from_pk, get_key_data

if TYPE_CHECKING:
    from src.schemas.tasks.deploy import DeployTask

class Deploy(ModuleBase):
    task: 'DeployTask'
    account: Account

    def __init__(
            self,
            private_key: str,
            key_type: enums.PrivateKeyType,
            account,
            task: 'DeployTask',
    ):
        super().__init__(
            account=account,
            task=task
        )

        self.task = task
        self.account = account
        self.pk = private_key

        self.key_type = key_type
        self.key_pair = get_key_pair_from_pk(self.pk)
        self.key_data = get_key_data(key_pair=self.key_pair, key_type=self.key_type)

        if self.key_type == enums.PrivateKeyType.braavos:
            self.account.signer = BraavosCurveSigner(
                account_address=self.account.address,
                key_pair=self.key_pair,
                chain_id=self.chain_id
            )

    async def build_deploy_txn(self) -> Union[DeployAccount, None]:
        """
        Build signed deploy account transaction
        :return:
        """
        nonce = await self.get_nonce(account=self.account)

        max_fee = None
        estimated_fee = True

        if self.task.forced_gas_limit:
            max_fee = int(self.task.max_fee * 10 ** 9)
            estimated_fee = None

        try:
            deploy_account_tx = await self.account.sign_deploy_account_transaction(
                class_hash=self.key_data.class_hash,
                contract_address_salt=self.key_pair.public_key,
                constructor_calldata=self.key_data.call_data,
                nonce=nonce,
                max_fee=max_fee,
                auto_estimate=estimated_fee
            )

            return deploy_account_tx

        except ClientError as e:
            if "unavailable for deployment" in str(e):
                err_msg = f"Account unavailable for deployment or already deployed."
                logger.error(err_msg)
                return None

            else:
                err_msg = f"Error while estimating transaction fee"
                logger.error(err_msg)
                return None

    async def send_txn(self) -> ModuleExecutionResult:
        """
        Send deploy transaction
        :return:
        """
        account_deployed = await self.account_deployed(account=self.account)
        if account_deployed is True:
            err_msg = f"Account already deployed."
            logger.warning(err_msg)
            self.module_execution_result.execution_info = err_msg
            self.module_execution_result.retry_needed = False
            return self.module_execution_result

        logger.warning(f"Action: Deploy {self.key_type.title()} account")

        signed_deploy_txn = await self.build_deploy_txn()
        if signed_deploy_txn is None:
            err_msg = f"Error while estimating transaction fee"
            logger.error(err_msg)
            self.module_execution_result.execution_info = err_msg

        wallet_eth_balance_wei = await self.get_eth_balance(account=self.account)
        wallet_eth_balance_decimals = wallet_eth_balance_wei / 10 ** 18

        try:
            estimated_fee = await self.account.client.estimate_fee(tx=signed_deploy_txn)
            overall_fee = estimated_fee.overall_fee

        except ClientError:
            err_msg = f"Error while estimating transaction fee"
            logger.error(err_msg)

            self.module_execution_result.execution_info = err_msg
            return self.module_execution_result

        overall_fee = int(overall_fee * 2)
        if overall_fee is None:
            err_msg = f"Error while estimating transaction fee."
            logger.error(err_msg)

            self.module_execution_result.execution_info = err_msg
            return self.module_execution_result

        if overall_fee > wallet_eth_balance_wei:
            err_msg = (f"Not enough native for fee, wallet ETH balance = {wallet_eth_balance_decimals} "
                       f"(need {overall_fee / 10 ** 18}) ")
            logger.error(err_msg)

            self.module_execution_result.execution_info = err_msg
            return self.module_execution_result

        logger.success(f"Transaction estimation success, overall fee: "
                       f"{overall_fee / 10 ** 18} ETH.")

        if self.task.test_mode is True:
            err_msg = f"Test mode enabled. Skipping transaction"

            self.module_execution_result.execution_info = err_msg
            return self.module_execution_result

        try:
            deploy_result = await self.account.client.deploy_account(signed_deploy_txn)
            txn_hash = deploy_result.transaction_hash

            if self.task.wait_for_receipt is True:
                logger.info(f"Txn sent. Waiting for receipt (Timeout in {self.task.txn_wait_timeout_sec}s)."
                            f" Txn Hash: {hex(txn_hash)}")

                txn_receipt = await self.wait_for_tx_receipt(tx_hash=txn_hash,
                                                             time_out_sec=int(self.task.txn_wait_timeout_sec))
                if txn_receipt is None:
                    err_msg = f"Txn timeout ({self.task.txn_wait_timeout_sec}s)."
                    logger.error(err_msg)

                    self.module_execution_result.execution_info = err_msg
                    return self.module_execution_result

                txn_status = txn_receipt.execution_status.value if txn_receipt.execution_status is not None else None
                logger.success(f"Txn success, status: {txn_status} "
                               f"(Actual fee: {txn_receipt.actual_fee / 10 ** 18}). "
                               f"Txn Hash: {hex(txn_hash)})")

                self.module_execution_result.execution_status = True
                self.module_execution_result.execution_info = f"Txn success, status: {txn_status}"
                self.module_execution_result.hash = hex(txn_hash)

                return self.module_execution_result

            else:
                logger.success(f"Txn sent. Txn Hash: {hex(txn_hash)}")

                self.module_execution_result.execution_status = True
                self.module_execution_result.execution_info = f"Txn sent"
                self.module_execution_result.hash = hex(txn_hash)
                return self.module_execution_result

        except Exception as e:
            err_msg = f"Error while sending deploy txn: {e}"
            logger.error(err_msg)

            self.module_execution_result.execution_info = err_msg
            return self.module_execution_result


from operator import truediv
import random
numero_aleatorio= random.randrange(100)
gane= False
print("tenes 5 oportunidades para adivinar el numero")
intento= 1
while( intento <6) and (not gane):
     numero_ingresado=int(input('ingresa tu numero'))
     if( numero_ingresado==numero_aleatorio):
         print('ganaste y necesitas {} intentos!!!'.format(intento))
         gane:True
     else:
         print('ese numero no es segui intentado')
         intento+=1
if(not gane):
    print('\n perdiste:(\ el numero era: {}' .format(numero_aleatorio) )


"""Application : Dashboard de Crédit Score

"""

# ====================================================================
# Chargement des librairies
# ====================================================================
import streamlit as st
import numpy as np
import pandas as pd
from PIL import Image
import pickle
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import seaborn as sns
import shap
from st_aggrid import AgGrid

# Répertoire du dashboard
# Test set brut original
FILE_APPLICATION_TEST = 'data/application_test.pickle'
# Test set pré-procédé
FILE_TEST_SET = 'data/test_set.pickle'
# Dashboard
FILE_DASHBOARD = 'data/df_dashboard.pickle'
# Client
FILE_CLIENT_INFO = 'data/df_info_client.pickle'
FILE_CLIENT_PRET = 'data/df_pret_client.pickle'

# Shap values
FILE_SHAP_VALUES = 'data/shap_values.pickle'

# Description
FILE_DESCRIPTION_VALUES = 'data/feature_description.pickle'

# ====================================================================
# IMAGES
# ====================================================================
# Logo de l'entreprise
logo =  Image.open("images/logo.png")

# ====================================================================
# HEADER - TITRE
# ====================================================================
html_header="""

        <title>Application Dashboard Credit Score</title>

 Prêt à dépenser

 DASHBOARD

"""
st.set_page_config(page_title="Prêt à dépenser ", page_icon="", layout="wide")
st.markdown('',unsafe_allow_html=True)
st.markdown(html_header, unsafe_allow_html=True)

# ====================================================================
# CHARGEMENT DES DONNEES
# ====================================================================

def load():
    with st.spinner('Uploading data'):

        # Import du dataframe des informations des traits stricts du client
        with open(FILE_CLIENT_INFO, 'rb') as df_info_client:
            df_info_client = pickle.load(df_info_client)

        # Import du dataframe des informations sur le prêt du client
        with open(FILE_CLIENT_PRET, 'rb') as df_pret_client:
            df_pret_client = pickle.load(df_pret_client)

        # Import du dataframe des informations sur le dashboard
        with open(FILE_DASHBOARD, 'rb') as df_dashboard:
            df_dashboard = pickle.load(df_dashboard)

        # Import du dataframe du test set nettoyé et pré-procédé
        with open(FILE_TEST_SET, 'rb') as df_test_set:
            test_set = pickle.load(df_test_set)

        # Import du dataframe du test set brut original
        with open(FILE_APPLICATION_TEST, 'rb') as df_application_test:
            application_test = pickle.load(df_application_test)

        # Import du dataframe du test set brut original
        with open(FILE_SHAP_VALUES, 'rb') as shap_values:
            shap_values = pickle.load(shap_values)

        # Import du dataframe du test set brut original
        with open(FILE_DESCRIPTION_VALUES, 'rb') as desc_values:
            desc_values = pickle.load(desc_values)

    return df_info_client, df_pret_client, df_dashboard,  test_set, \
            application_test, shap_values, desc_values

# Chargement des dataframes et du modèle
df_info_client, df_pret_client, df_dashboard,  test_set, \
            application_test, shap_values, desc_values = load()

# ====================================================================
# CHARGEMENT DE MODELE
# ====================================================================
best_model = pickle.load(open('model.pickle', 'rb'))

# ====================================================================
# CHOIX DU CLIENT
# ====================================================================

html_select_client="""

          Client information

    """

st.markdown(html_select_client, unsafe_allow_html=True)

with st.container():

    col1, col2 = st.columns([1,4])
    with col1:
        st.write("")
        col1.header("**Client ID**")
        client_id = col1.selectbox('Insert client ID :',
                                   test_set['SK_ID_CURR'].unique())
    with col2:
        # Infos principales client
        # st.write("*Traits stricts*")
        client_info = df_info_client[df_info_client['SK_ID_CURR'] == client_id].iloc[: , :]
        client_info.set_index('SK_ID_CURR', inplace=True)
        st.table(client_info)
        # Infos principales sur la demande de prêt
        # st.write("*Demande de prêt*")
        client_pret = df_pret_client[df_pret_client['SK_ID_CURR'] == client_id].iloc[:, :]
        client_pret.set_index('SK_ID_CURR', inplace=True)
        st.table(client_pret)

# ============== Score du client en pourcentage ==> en utilisant le modèle ======================
# Sélection des variables du clients
X_test = test_set[test_set['SK_ID_CURR'] == client_id]
# Score des prédictions de probabiltés
y_proba = best_model.predict_proba(X_test.drop('SK_ID_CURR', axis=1))[:, 1]
# Score du client en pourcentage arrondi et nombre entier
score_client = int(np.rint(y_proba * 100))

# Graphique de jauge du cédit score ==========================================
fig_jauge = go.Figure(go.Indicator(
    mode = 'gauge+number',
    # Score du client en % df_dashboard['SCORE_CLIENT_%']
    value = score_client,
    domain = {'x': [0, 1], 'y': [0, 1]},
    title = {'text': 'Client\'s Credit Score', 'font': {'size': 24}},
    # Score des 10 voisins test set
    # df_dashboard['SCORE_10_VOISINS_MEAN_TEST']
    delta = {
             'increasing': {'color': 'Crimson'},
             'decreasing': {'color': 'Green'}},
    gauge = {'axis': {'range': [None, 100],
                      'tickwidth': 3,
                      'tickcolor': 'darkblue'},
             'bar': {'color': 'white', 'thickness' : 0.25},
             'bgcolor': 'white',
             'borderwidth': 2,
             'bordercolor': 'gray',
             'steps': [{'range': [0, 25], 'color': 'Green'},
                       {'range': [25, 49.49], 'color': 'LimeGreen'},
                       {'range': [49.5, 50.5], 'color': 'red'},
                       {'range': [50.51, 75], 'color': 'Orange'},
                       {'range': [75, 100], 'color': 'Crimson'}],
             'threshold': {'line': {'color': 'white', 'width': 10},
                           'thickness': 0.8,
                           # Score du client en %
                           # df_dashboard['SCORE_CLIENT_%']
                           'value': score_client}}))

fig_jauge.update_layout(paper_bgcolor='white',
                        height=400, width=500,
                        font={'color': 'darkblue', 'family': 'Arial'},
                        margin=dict(l=0, r=0, b=0, t=0, pad=0))

with st.container():
    # JAUGE + récapitulatif du score moyen des voisins
    col1, col2 = st.columns([1.5, 1])
    with col1:
        st.plotly_chart(fig_jauge)
    with col2:
        st.write("")
        st.write("")
        st.write("")
        st.write("")
        st.write("")
        # Texte d'accompagnement de la jauge
        if 0 <= score_client < 25:
            score_text = 'Credit score : EXCELLENT'
            st.success(score_text)
        elif 25 <= score_client < 50:
            score_text = 'Credit score : BON'
            st.success(score_text)
        elif 50 <= score_client < 75:
            score_text = 'Credit score : MOYEN'
            st.warning(score_text)
        else :
            score_text = 'Credit score : BAS'
            st.error(score_text)
        st.write("")
        #st.markdown(f'Crédit score moyen des 10 clients similaires : **{score_moy_voisins_test}**')
        #st.markdown(f'**{pourc_def_voisins_train}**% de clients voisins réellement défaillants dans l\'historique')
        #st.markdown(f'**{pourc_def_voisins_test}**% de clients voisins défaillants prédits pour les nouveaux clients')

# LOGO
# --------------------------------------------------------------------
# Chargement du logo de l'entreprise
st.sidebar.image(logo, width=240,  use_column_width='always')

# ====================================================================
# SIDEBAR
# ====================================================================
# Toutes Les informations non modifiées du client courant
df_client_origin = application_test[application_test['SK_ID_CURR'] == client_id]

# Toutes Les informations non modifiées du client courant
df_client_test = test_set[test_set['SK_ID_CURR'] == client_id]

# Les informations pré-procédées du client courant
df_client_courant = df_dashboard[df_dashboard['SK_ID_CURR'] == client_id]

# --------------------------------------------------------------------
# MORE INFORMATIONS
# --------------------------------------------------------------------
def all_infos_clients():
    ''' Affiche toutes les informations sur le client courant
    '''
    html_all_infos_clients="""

                      All client's Information

        """

    # ====================== GRAPHIQUES COMPARANT CLIENT COURANT / CLIENTS SIMILAIRES ===========================
    if st.sidebar.checkbox("Client"):

        st.markdown(html_all_infos_clients, unsafe_allow_html=True)

        with st.spinner('**Waitting...**'):
            with st.expander('All informations of the client', expanded=True):
                AgGrid(df_client_test, height=100, fit_columns_on_grid_load=False)
                #st.table( df_client_test)
                #st.dataframe( df_client_origin)
                AgGrid(df_client_origin, height=100, fit_columns_on_grid_load=False)

            with st.expander('Description of all information',expanded=True):
                st.dataframe(desc_values)

st.sidebar.subheader('More information :')
all_infos_clients()

# ====================================================================
# HTML MARKDOWN
# ====================================================================
html_YEAR_BIRTH = "
Age (year)

"
html_AMT_ANNUITY = "
AMT of ANNUITY

"
html_YEAR_EMPLOYED = "
Experience (yrear)

"
html_OWN_CAR_AGE = "
Age of own car

"
html_AMT_CREDIT = "
AMT of CREDIT

"
html_OWN_CAR_AGE = "
Car'/s age of client

"
html_EXT_SOURCE_Mean = "
Mean of 3 Externel sources

"

html_EXT_SOURCE_1 = "
EXT_SOURCE_3

Source externe normalisée (valeur * 100)

"

# --------------------------------------------------------------------
# SATATISTICS
# --------------------------------------------------------------------
def stat_graph():
    ''' Affiche les les graphiques du client courant
    '''
    html_stat_graph="""

                      Distribution

        """
    titre = True

    # ====================== GRAPHIQUES DE SITUATION CLIENT COURANT  ===========================
    if st.sidebar.checkbox("statistics"):

        st.markdown(html_stat_graph, unsafe_allow_html=True)

        with st.spinner('**Waitting...**'):

            with st.expander('Age of clients',expanded=False):

                with st.container():

                    df_dashboard['YEAR_BIRTH'] = \
                        np.trunc(np.abs(df_dashboard['DAYS_BIRTH'] / 365)).astype('int8')
                    age_client = int(df_dashboard[df_dashboard['SK_ID_CURR'] == client_id]['YEAR_BIRTH'].values)
                    st.markdown(html_YEAR_BIRTH, unsafe_allow_html=True)

                    # ==================== ViolinPlot ========================================================
                    st.set_option('deprecation.showPyplotGlobalUse', False)
                    sns.violinplot(x='PRED_CLASSE_CLIENT', y='YEAR_BIRTH',
                                   data=df_dashboard,palette=['LimeGreen', 'Crimson'])

                    plt.plot(df_client_courant['PRED_CLASSE_CLIENT'],age_client,
                             color="orange", marker="$\\bigotimes$", markersize=18)

                    plt.xlabel('TARGET', fontsize=10)
                    client = mlines.Line2D([], [], color='orange', marker='$\\bigotimes$',linestyle='None',
                                               markersize=10, label='Clent\'s position')

                    plt.legend(handles=[client], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
                    st.pyplot(showPyplotGlobalUse = False)
                    st.set_option('deprecation.showPyplotGlobalUse', False)

                    # ==================== DistPlot ==========================================================
                    # No_Defaulter
                    sns.distplot(df_dashboard['YEAR_BIRTH'][df_dashboard['PRED_CLASSE_CLIENT'] == 0],
                                 label='No-Defaulter', hist=False, color='Green')
                    # Défaillants
                    sns.distplot(df_dashboard['YEAR_BIRTH'][df_dashboard['PRED_CLASSE_CLIENT'] == 1],
                                 label='Defaulter', hist=False, color='Crimson')
                    plt.xlabel('YEAR_BIRTH', fontsize=16)
                    plt.ylabel('Probability Density', fontsize=16)
                    plt.xticks(fontsize=16, rotation=90)
                    plt.yticks(fontsize=16)
                    # Position du client
                    plt.axvline(x=age_client, color='orange', label='Clent\'s position')
                    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=18)
                    st.pyplot()

                # ==============================================================
                # Variable Annuity ($)
                # ==============================================================
            with st.expander('Annuity ($)', expanded=False):

                with st.spinner('**Waitting**'):

                    ann_client = int(df_dashboard[df_dashboard['SK_ID_CURR'] == client_id]['AMT_ANNUITY'].values)
                    st.markdown(html_AMT_ANNUITY, unsafe_allow_html=True)

                    # ==================== ViolinPlot ========================================================
                    st.set_option('deprecation.showPyplotGlobalUse', False)
                    sns.violinplot(x='PRED_CLASSE_CLIENT', y='AMT_ANNUITY',
                                   data=df_dashboard,palette=['LimeGreen', 'Crimson'])

                    plt.plot(df_client_courant['PRED_CLASSE_CLIENT'],ann_client,
                             color="orange", marker="$\\bigotimes$", markersize=18)

                    plt.xlabel('TARGET', fontsize=10)
                    client = mlines.Line2D([], [], color='orange', marker='$\\bigotimes$',linestyle='None',
                                               markersize=10, label='Clent\'s position')

                    plt.legend(handles=[client], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
                    st.pyplot(showPyplotGlobalUse = False)
                    st.set_option('deprecation.showPyplotGlobalUse', False)

                    # ==================== DistPlot ==========================================================
                    # No-Defaulter
                    sns.distplot(df_dashboard['AMT_ANNUITY'][df_dashboard['PRED_CLASSE_CLIENT'] == 0],
                                 label='No-Defaulter', hist=False, color='Green')
                    # Défaillants
                    sns.distplot(df_dashboard['AMT_ANNUITY'][df_dashboard['PRED_CLASSE_CLIENT'] == 1],
                                 label='Defaulter', hist=False, color='Crimson')
                    plt.xlabel('AMT_ANNUITY', fontsize=16)
                    plt.ylabel('Probability Density', fontsize=16)
                    plt.xticks(fontsize=16, rotation=90)
                    plt.yticks(fontsize=16)
                    # Position du client
                    plt.axvline(x=ann_client, color='orange', label='Clent\'s position')
                    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=18)
                    st.pyplot()

                # ==============================================================
                # Variable YEAR_EMPLOYED
                # ==============================================================
            with st.expander('Experience ', expanded=False):

                with st.spinner('**Waitting**'):

                    ann_client = int(df_dashboard[df_dashboard['SK_ID_CURR'] == client_id]['YEAR_EMPLOYED'].values)
                    st.markdown(html_YEAR_EMPLOYED, unsafe_allow_html=True)

                    # ==================== ViolinPlot ========================================================
                    st.set_option('deprecation.showPyplotGlobalUse', False)
                    sns.violinplot(x='PRED_CLASSE_CLIENT', y='YEAR_EMPLOYED',
                                   data=df_dashboard,palette=['LimeGreen', 'Crimson'])

                    plt.plot(df_client_courant['PRED_CLASSE_CLIENT'],ann_client,
                             color="orange", marker="$\\bigotimes$", markersize=18)

                    plt.xlabel('TARGET', fontsize=10)
                    client = mlines.Line2D([], [], color='orange', marker='$\\bigotimes$',linestyle='None',
                                               markersize=10, label='Clent\'s position')

                    plt.legend(handles=[client], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
                    st.pyplot(showPyplotGlobalUse = False)
                    st.set_option('deprecation.showPyplotGlobalUse', False)

                    # ==================== DistPlot ==========================================================
                    # No-Defaulter
                    sns.distplot(df_dashboard['YEAR_EMPLOYED'][df_dashboard['PRED_CLASSE_CLIENT'] == 0],
                                 label='No-Defaulter', hist=False, color='Green')
                    # Défaillants
                    sns.distplot(df_dashboard['YEAR_EMPLOYED'][df_dashboard['PRED_CLASSE_CLIENT'] == 1],
                                 label='Defaulter', hist=False, color='Crimson')
                    plt.xlabel('YEAR_EMPLOYED', fontsize=16)
                    plt.ylabel('Probability Density', fontsize=16)
                    plt.xticks(fontsize=16, rotation=90)
                    plt.yticks(fontsize=16)
                    # Position du client
                    plt.axvline(x=ann_client, color='orange', label='Clent\'s position')
                    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=18)
                    st.pyplot()

                    # ==============================================================
                # Variable AMT_CREDIT
                # ==============================================================
            with st.expander('Amounth of credit', expanded=False):

                with st.spinner('**Waitting**'):

                    crd_client = int(df_dashboard[df_dashboard['SK_ID_CURR'] == client_id]['AMT_CREDIT'].values)
                    st.markdown(html_AMT_CREDIT, unsafe_allow_html=True)

                    # ==================== ViolinPlot ========================================================
                    st.set_option('deprecation.showPyplotGlobalUse', False)
                    sns.violinplot(x='PRED_CLASSE_CLIENT', y='AMT_CREDIT',
                                   data=df_dashboard,palette=['LimeGreen', 'Crimson'])

                    plt.plot(df_client_courant['PRED_CLASSE_CLIENT'],crd_client,
                             color="orange", marker="$\\bigotimes$", markersize=18)

                    plt.xlabel('TARGET', fontsize=10)
                    client = mlines.Line2D([], [], color='orange', marker='$\\bigotimes$',linestyle='None',
                                               markersize=10, label='Clent\'s position')

                    plt.legend(handles=[client], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
                    st.pyplot(showPyplotGlobalUse = False)
                    st.set_option('deprecation.showPyplotGlobalUse', False)

                    # ==================== DistPlot ==========================================================
                    # No-Defaulter
                    sns.distplot(df_dashboard['AMT_CREDIT'][df_dashboard['PRED_CLASSE_CLIENT'] == 0],
                                 label='No-Defaulter', hist=False, color='Green')
                    # Défaillants
                    sns.distplot(df_dashboard['AMT_CREDIT'][df_dashboard['PRED_CLASSE_CLIENT'] == 1],
                                 label='Defaulter', hist=False, color='Crimson')
                    plt.xlabel('AMT_CREDIT', fontsize=16)
                    plt.ylabel('Probability Density', fontsize=16)
                    plt.xticks(fontsize=16, rotation=90)
                    plt.yticks(fontsize=16)
                    # Position du client
                    plt.axvline(x=crd_client, color='orange', label='Clent\'s position')
                    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=18)
                    st.pyplot()

                # ==============================================================
                # Variable EXT_SOURCE_3
                # ==============================================================
            with st.expander('OWN_CAR_AGE', expanded=False):

                with st.spinner('**Waitting**'):

                    car_age = float(df_dashboard[df_dashboard['SK_ID_CURR'] == client_id]['OWN_CAR_AGE'].values)
                    st.markdown(html_OWN_CAR_AGE, unsafe_allow_html=True)

                    # ==================== ViolinPlot ========================================================
                    st.set_option('deprecation.showPyplotGlobalUse', False)
                    sns.violinplot(x='PRED_CLASSE_CLIENT', y='OWN_CAR_AGE',
                                   data=df_dashboard,palette=['LimeGreen', 'Crimson'])

                    plt.plot(df_client_courant['PRED_CLASSE_CLIENT'],car_age,
                             color="orange", marker="$\\bigotimes$", markersize=18)

                    plt.xlabel('TARGET', fontsize=10)
                    client = mlines.Line2D([], [], color='orange', marker='$\\bigotimes$',linestyle='None',
                                               markersize=10, label='Clent\'s position')

                    plt.legend(handles=[client], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
                    st.pyplot(showPyplotGlobalUse = False)
                    st.set_option('deprecation.showPyplotGlobalUse', False)

                    # ==================== DistPlot ==========================================================
                    # No-Defaulter
                    sns.distplot(df_dashboard['OWN_CAR_AGE'][df_dashboard['PRED_CLASSE_CLIENT'] == 0],
                                 label='No-Defaulter', hist=False, color='Green')
                    # Défaillants
                    sns.distplot(df_dashboard['OWN_CAR_AGE'][df_dashboard['PRED_CLASSE_CLIENT'] == 1],
                                 label='Defaulter', hist=False, color='Crimson')
                    plt.xlabel('OWN_CAR_AGE', fontsize=16)
                    plt.ylabel('Probability Density', fontsize=16)
                    plt.xticks(fontsize=16, rotation=90)
                    plt.yticks(fontsize=16)
                    # Position du client
                    plt.axvline(x=car_age, color='orange', label='Clent\'s position')
                    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=18)
                    st.pyplot()

                # ==============================================================
                # Variable EXT_SOURCE_mean
                # ==============================================================
            with st.expander('EXT_sources_MEAN', expanded=False):

                with st.spinner('**Waitting**'):

                    ext_m = float(df_dashboard[df_dashboard['SK_ID_CURR'] == client_id]['NEW_EXT_MEAN'].values)
                    st.markdown(html_EXT_SOURCE_Mean, unsafe_allow_html=True)

                    # ==================== ViolinPlot ========================================================
                    st.set_option('deprecation.showPyplotGlobalUse', False)
                    sns.violinplot(x='PRED_CLASSE_CLIENT', y='NEW_EXT_MEAN',
                                   data=df_dashboard,palette=['LimeGreen', 'Crimson'])

                    plt.plot(df_client_courant['PRED_CLASSE_CLIENT'],ext_m,
                             color="orange", marker="$\\bigotimes$", markersize=18)

                    plt.xlabel('TARGET', fontsize=10)
                    client = mlines.Line2D([], [], color='orange', marker='$\\bigotimes$',linestyle='None',
                                               markersize=10, label='Clent\'s position')

                    plt.legend(handles=[client], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
                    st.pyplot(showPyplotGlobalUse = False)
                    st.set_option('deprecation.showPyplotGlobalUse', False)

                    # ==================== DistPlot ==========================================================
                    # No-Defaulter
                    sns.distplot(df_dashboard['NEW_EXT_MEAN'][df_dashboard['PRED_CLASSE_CLIENT'] == 0],
                                 label='No-Defaulter', hist=False, color='Green')
                    # Défaillants
                    sns.distplot(df_dashboard['NEW_EXT_MEAN'][df_dashboard['PRED_CLASSE_CLIENT'] == 1],
                                 label='Defaulter', hist=False, color='Crimson')
                    plt.xlabel('NEW_EXT_MEAN', fontsize=16)
                    plt.ylabel('Probability Density', fontsize=16)
                    plt.xticks(fontsize=16, rotation=90)
                    plt.yticks(fontsize=16)
                    # Position du client
                    plt.axvline(x=ext_m, color='orange', label='Clent\'s position')
                    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=18)
                    st.pyplot()

stat_graph()

# --------------------------------------------------------------------
# FACTEURS D'INFLUENCE : SHAP VALUE
# --------------------------------------------------------------------

def affiche_facteurs_influence():
    ''' Affiche les facteurs d'influence du client courant
    '''
    html_facteurs_influence="""

                      Importante variables

        """

    # ====================== GRAPHIQUES Influential factors========================================
    if st.sidebar.checkbox("Influential factors"):

        st.markdown(html_facteurs_influence, unsafe_allow_html=True)

        with st.spinner('**Waitting...**'):

                explainer = shap.TreeExplainer(best_model)

                client_index = test_set[test_set['SK_ID_CURR'] == client_id].index.item()
                X_shap = test_set.set_index('SK_ID_CURR')
                X_test_courant = X_shap.iloc[client_index]
                X_test_courant_array = X_test_courant.values.reshape(1, -1)

                shap_values_courant = explainer.shap_values(X_test_courant_array)

                col1, col2 = st.columns([1, 1])
                # BarPlot du client courant
                with col1:

                    plt.clf()

                    # BarPlot du client courant
                    shap.plots.bar( shap_values[client_index], max_display=40)

                    fig = plt.gcf()
                    fig.set_size_inches((10, 20))
                    # Plot the graph on the dashboard
                    st.pyplot(fig)

                # Decision plot du client courant
                with col2:
                    plt.clf()

                    # Decision Plot
                    shap.decision_plot(explainer.expected_value[1], shap_values_courant[1],
                                    X_test_courant)

                    fig2 = plt.gcf()
                    fig2.set_size_inches((10, 15))
                    # Plot the graph on the dashboard
                    st.pyplot(fig2)

affiche_facteurs_influence()


"""allow comment field in hello world table

Revision ID: 48c98f1996d6
Revises: 938dda2c917f
Create Date: 2021-05-12 04:11:54.738919

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '48c98f1996d6'
down_revision = '938dda2c917f'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('hello_world_post', schema=None) as batch_op:
        batch_op.add_column(sa.Column('allowed_comment', sa.Boolean(), nullable=True))

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('hello_world_post', schema=None) as batch_op:
        batch_op.drop_column('allowed_comment')

    # ### end Alembic commands ###


import os
import subprocess
import re
import json
import time

def run_sim(iterations, bodies, cores, strategy='default', chunk_size = None):

	extra_args = ""
	if strategy == "pm" or strategy == "pb":
		extra_args = strategy

	if strategy == "plc":
		extra_args = "plc {}".format(chunk_size)

	if strategy == "pbc":

		extra_args = "pbc {}".format(chunk_size)

	command = "(time -p barnes-hut -i {} -n {} {} +RTS -N{}) > times.txt 2>&1".format(iterations, bodies, extra_args, cores)
	print(command)
	result = subprocess.run(command, shell=True)
	# result = subprocess.Popen(['bash', '-p', command])
    # os.system("bash")

	with open("times.txt") as f:
		lines = f.readlines()
		real = lines[-3].split(" ")[1]#re.search('real ([^]*)', lines[0])
		user = lines[-2].split(" ")[1]#re.search('user ([^]*)', lines[1])
		sys = lines[-1].split(" ")[1]#re.search('sys ([^]*)', lines[2])
		return (float(real), float(user) + float(sys))

def parse_time(time_string):

	split = time_string.split('m')
	mins = split[0]
	secs = split[1]

	return float(mins) * 60 + float(secs)

def main():

	iterations = 500
	bodies = 1000
	print("Starting tests.")

	os.chdir('../')
	subprocess.run('stack install', shell=True)
	os.chdir('test/')
	cores = [2, 4, 6, 8]
	chunks = [25 * i for i in range(1,21)]
	results = {}
	strategies = ["default", 'pm', 'pb', 'plc', 'pbc']

	for strategy in strategies:

		strategyResults = {}

		if strategy == 'default':
			run_time = run_sim(iterations, bodies, 1) # no parallel
			clock_time = run_time[0]
			strategyResults[strategy] = clock_time
			continue

		for core in cores:

			coreResults = {}
			if strategy == 'pbc' or strategy == 'plc':

				for chunk in chunks:

					run_time = run_sim(iterations, bodies, core, strategy=strategy, chunk_size=chunk)
					clock_time = run_time[0]

					coreResults[chunk] = clock_time
			else:

				run_time = run_sim(iterations, bodies, core, strategy=strategy)
				clock_time = run_time[0]
				coreResults[1] = clock_time

			strategyResults[core] = coreResults

		results[strategy] = strategyResults

	timestr = time.strftime("%Y%m%d-%H-%M-%S")
	with open('test_results_' + timestr + '.json', 'w') as f:

		f.write(json.dumps(results))

def other_test():

	iterations = 500
	body_count = [240, 480, 720, 960]
	results = {}
	strategies = ["default", 'plc', 'pbc']
	cores = [2, 4, 6, 8]
	for strategy in strategies:

		strategyResults = {}

		if strategy == 'default':

			for bodies in body_count:
				run_time = run_sim(iterations, bodies, 1) # no parallel
				clock_time = run_time[0]
				strategyResults[bodies] = clock_time

			results[strategy] = strategyResults
			continue

		for core in cores:

			coreResults = {}

			for bodies in body_count:

				chunk_size = int(bodies / core)
				run_time = run_sim(iterations, bodies, core, strategy=strategy, chunk_size=chunk_size)
				clock_time = run_time[0]

				coreResults[bodies] = clock_time

			strategyResults[core] = coreResults

		results[strategy] = strategyResults

	timestr = time.strftime("%Y%m%d-%H-%M-%S")
	with open('test_results_' + timestr + '.json', 'w') as f:

		f.write(json.dumps(results))

if __name__ == '__main__':
    other_test()


from argparse import ArgumentParser
import pandas as pd
import torch
from sklearn.metrics import precision_recall_curve, roc_curve
from sklearn.model_selection import train_test_split
from data_loader import SMILESDataset
from train import train_dense, train_ff
import matplotlib.pyplot as plt
def get_args():
    device_choices = ['cpu']
    if not torch.backends.mps.is_available():
        if not torch.backends.mps.is_built():
            print("MPS not available because the current PyTorch install was not "
                  "built with MPS enabled.")
        else:
            print("MPS not available because the current MacOS version is not 12.3+ "
                  "and/or you do not have an MPS-enabled device on this machine.")
    else:
        device_choices.append("mps")

    if torch.cuda.is_available():
        device_choices.append('cuda')

    parser = ArgumentParser()
    parser.add_argument('--data', type=str, default='/Users/austin/Downloads/AmpC_screen_table.csv')
    parser.add_argument('--device', type=str, default='cpu', choices=device_choices)
    return parser.parse_args()

def main():
    args = get_args()
    df = pd.read_csv(args.data, low_memory=False, engine='c', nrows=1000000)
    print(f"Read in data with {len(df)} rows and headers {df.columns}")

    df_train, df_test = train_test_split(df, test_size=0.3)
    train_data = SMILESDataset(df=df_train, cutoff=10, pre_compute=True, smiles_key='smiles', score_key='dockscore')
    test_data = SMILESDataset(df=df_test, cutoff=10, test=True, pre_compute=True, smiles_key='smiles', score_key='dockscore')

    dense_model, dense_rocs,  dense_pred, dense_test = train_dense(train_data, test_data, device_str=args.device,
                input_dim=2048,
                num_iters=20,
                batch_size=32,
                lr=0.00025,
                dropout=0.05)

    ff_model, ff_rocs, ff_pred, ff_test = train_ff(train_data, test_data, device_str=args.device,
             input_dim=2048,
             num_iters=20,
             batch_size=32,
             lr=0.00025,
             dropout=0.05)

    dense_fpr, dense_tpr, dense_thresholds = roc_curve(dense_test, dense_pred)
    ff_fpr, ff_tpr, ff_thresholds = roc_curve(ff_test, ff_pred)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8))

    ax1.plot(dense_rocs, lw=3, label='SimpleNet')
    ax1.plot(ff_rocs, lw=3, label='Forward-Forward')
    ax1.set_xlabel('Iteration', fontsize=20)
    ax2.set_ylabel('ROC-AUC', fontsize=20)

    ax2.plot(dense_fpr, dense_tpr, lw=3, label='SimpleNet')
    ax2.plot(ff_fpr, ff_tpr, lw=3, label="Forward-Forward")
    ax2.set_xlabel('false positive rate', fontsize=20)
    ax2.set_ylabel('true positive rate', fontsize=20)
    ax1.legend(fontsize=20)

    plt.show()

if __name__ == '__main__':
    main()