import numpy as np
import pandas as pd
import csv
from tqdm import tqdm
import math
import seaborn as sns
import matplotlib.pyplot as plt

# useful global variables
wines_header, tumors_header, wines_global,tumors_global = [],[],[],[]

# def normalize(x):
#     if max(x) == min(x):
#         return x
#     return x / (max(x) - min(x))

def norm(x):
    x_normed = (x - x.min(0)) / x.ptp(0)
    return x_normed

def process_wines():
    with open("winequality-red.csv", 'r') as f:
        wines = list(csv.reader(f, delimiter=";"))
    global wines_header
    wines_header = np.array(wines[0])  # with label header
    wines = np.array(wines[1:], dtype=np.float)  # with label

    # clean malinformed values by deleting the rows they inhabit
    invalid_index = []
    for i in range(len(wines)):
        for number in wines[i]:
            if math.isnan(number):
                np.delete(wines, i, 0)

    # differentiate labels
    for i in tqdm(range(len(wines[:, -1]))):
        if wines[:, -1][i] > 5:
            wines[:, -1][i] = 1
        else:
            wines[:, -1][i] = 0

    global wines_global
    wines_global = wines
    wines_x = wines[:, :-1]
    # for i in range(len(wines_x)):
    #     for j in range(len(wines_x[0])):
    #         wines_x[i][j] -= 5

    # # wines_x = np.delete(wines_x,10,axis=1)
    # # wines_x = np.delete(wines_x,9,axis=1)
    # wines_x = np.delete(wines_x,8,axis=1)
    # wines_x = np.delete(wines_x,7,axis=1)
    # wines_x = np.delete(wines_x,6,axis=1)
    # wines_x = np.delete(wines_x,5,axis=1)
    # wines_x = np.delete(wines_x,4,axis=1)
    # wines_x = np.delete(wines_x,3,axis=1)
    # # wines_x = np.delete(wines_x,2,axis=1)
    # # wines_x = np.delete(wines_x,1,axis=1)
    # wines_x = np.delete(wines_x, 0, axis=1)
    wines_y = wines[:, -1]
    #
    # for i in range(len(wines_x)):
    #     wines_x[i] = normalize(wines_x[i])
    # wines_x = norm(wines_x)

    return wines_x, wines_y

def process_tumors():
    with open("breast-cancer-wisconsin.data", 'r') as f:
        tumors = list(csv.reader(f, delimiter=";"))

    global tumors_header
    tumors_header = ["clump thickness", "cell size", "cell shape", "marginal adhesion", \
                     "single epithelial cell size", "number of bare nuclei", "bland chromatin", \
                     "number of normal nuclei", "mitosis", "label"]  # with label header but no IDs

    # highlight malinformed values
    invalid_index = []
    for i in tqdm(range(len(tumors))):
        tumors[i] = tumors[i][0].split(",")
        for j in range(len(tumors[i])):
            if tumors[i][j].isnumeric() == False:
                invalid_index.append(i)  # the whole row
        # differentiate labels
        if int(tumors[i][-1]) <= 2:
            tumors[i][-1] = '0'
        else:
            tumors[i][-1] = '1'

    # clean malinformed values by deleting the rows they inhabit
    invalid_index.sort(reverse=True)
    for i in invalid_index:
        tumors.remove(tumors[i])

    tumors = np.array(tumors[0:], dtype=np.float)
    tumors = tumors[:, 1:]

    global tumors_global
    tumors_global = tumors
    tumors_x = tumors[:,:-1]
    # tumors_x = norm(tumors_x) normalization
    #tumors_x = np.delete(tumors_x,3,axis=1) #
    tumors_y = tumors[:,-1]

    # for i in range(len(tumors_x)):
    #     tumors_x[i] = normalize(tumors_x[i])

    return tumors_x, tumors_y

def stats_wines():
    global wines_global
    wines = wines_global
    pos_index = []
    neg_index = []
    # separate two classes
    for index in range(len(wines)):
        if wines[index][-1] == 1:
            pos_index.append(index)
        else:
            neg_index.append(index)
    pos_wines = wines[pos_index]
    neg_wines = wines[neg_index]
    # sns.boxplot(data=pos_wines)
    # sns.boxplot(data=neg_wines)
    df = pd.DataFrame(wines, columns=wines_header)
    df.describe()
    # sns.pairplot(df) # density looks very suspicious
    # sns_plot = sns.pairplot(df)
    # sns_plot.savefig("wines_pairplot.png")
    df_pos = pd.DataFrame(pos_wines, columns=wines_header)
    df_pos.describe()
    df_neg = pd.DataFrame(neg_wines, columns=wines_header)
    df_neg.describe()

def stats_tumors():
    global tumors_global
    tumors = tumors_global
    pos_index = []
    neg_index = []
    # separate two classes
    for index in range(len(tumors)):
        if tumors[index][-1] == 1:
            pos_index.append(index)
        else:
            neg_index.append(index)
    pos_tumors = tumors[pos_index]
    neg_tumors = tumors[neg_index]

    df = pd.DataFrame(tumors, columns=tumors_header)
    df.describe()
    # sns.pairplot(df) # density looks very suspicious
    df_pos = pd.DataFrame(pos_tumors, columns=tumors_header)
    df_pos.describe()
    df_neg = pd.DataFrame(neg_tumors, columns=tumors_header)
    df_neg.describe()

# x,y = process_tumors()
# print(wines_global)
# print(x)
# print(y)
# for i in range(len(x)):
#     for j in range(len(x[0])):
#         if math.isnan(x[i][j]):
#             print(i,j)


# Definition for singly-linked list.
from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/2493388/Python-or-O(1)-or-Easily-Explained-or-Recursively
class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        # even if n (number of nodes) == 1 than k will be also 1
        if k == 1:
            return head

        # two pointers to get head and tails
        last: Optional[ListNode] = head
        first: Optional[ListNode] = head

        # steps to get the `k` pair we want
        steps = 1
        while steps < k:
            if last == None:
                return head
            last = last.next
            steps += 1

        # returning None shows our pair is incomplete, and we don't have to reverse the pairs
        if last == None:
            return head

        # 'cause our last node will be head when reversed
        head = last

        # reverse returns the first node (which will be the last node of the pair)
        # and that last node of the pair is connected to next pair which will be sent by `reverseKGroup`
        self.reverse(first, last).next = self.reverseKGroup(last.next, k)

        return head

    def reverse(self, first: Optional[ListNode], last: Optional[ListNode]):

        # to reverse
        prev: Optional[ListNode] = None
        current: Optional[ListNode] = first
        last: Optional[ListNode] = last.next
        temp: Optional[ListNode]

        while (current != last):
            temp = current.next
            current.next = prev
            prev = current
            current = temp

        return first


"""
Текстовый файл содержит только заглавные буквы латинского алфавита (ABC...Z).
Определите символ, который чаще всего встречается в файле между двумя одинаковыми символами.
Например, в тексте CBCABABACCC есть комбинации CBC, ABA (два раза), BAB и CCC.
Чаще всего – 3 раза – между двумя одинаковыми символами стоит B,
в ответе для этого случая надо написать B.
"""

document = open('Faily_IN11_02022021/24/24_2010301_statgrad.txt')
a = document.read()
alphabet = []
max_k = 0
max_k_index = 0

for i in range(26):
    alphabet.append(0)

for i in range(1, len(a) - 1):
    if a[i-1] == a[i + 1]:
        index = ord(a[i]) - 65
        alphabet[index] += 1

for i in range(len(alphabet)):
    if alphabet[i] > max_k:
        max_k = alphabet[i]
        max_k_index = i

print(chr(max_k_index + 65))


"""Render a Conway's Game of Life."""
import random
import time
from typing import Any, NamedTuple, Set

from ledmatrix import matrix
from ledmatrix.utilities import colors
from ledmatrix.utilities.colors import BLACK

INITIAL_POPULATION_DENSITY = 0.7  # type: float

CellCoords = NamedTuple('CellCoords', [('row_index', int), ('col_index', int)])

class GameOfLife(matrix.LedMatrix):
    """Matrix for playing Conway's Game of Life.

    See: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life.
    """
    def __init__(
        self,
        *args,  # type: Any
        **kwargs  # type: Any
    ):  # type: (...) -> None
        super().__init__(*args, **kwargs)
        self._living_cell_coordinates = set()  # type: Set[CellCoords]

        # initialize to random state
        for row_index in range(self.height):
            for col_index in range(self.width):
                if random.random() > INITIAL_POPULATION_DENSITY:  # noqa: S311
                    cell = CellCoords(row_index, col_index)
                    self._living_cell_coordinates.add(cell)
                    self[row_index][col_index] = self.default_color  # type: ignore

    def next_state(self):  # type: () -> None
        """Determine which cells live and die and apply to matrix."""
        next_living_cell_coordinates = set()  # type: Set[CellCoords]

        # get batch of cells that will survive / regenerate in the next round
        for cell in self._living_cell_coordinates:
            if self._will_live(cell):
                next_living_cell_coordinates.add(cell)
            for neighbor_cell in self._get_neighbor_coordinates(cell):
                if self._will_live(neighbor_cell):
                    next_living_cell_coordinates.add(neighbor_cell)

        # update living cell coordinates on class
        self._living_cell_coordinates = next_living_cell_coordinates

        # apply changes to the matrix
        for row_index in range(self.height):
            for col_index in range(self.width):
                cell = CellCoords(row_index, col_index)
                if self._is_alive(cell):
                    self[row_index][col_index] = self.default_color    # type: ignore
                else:
                    self[row_index][col_index] = BLACK    # type: ignore

    def _is_alive(self, cell):  # type: (CellCoords) -> bool
        """Return True if the given cell is alive in the current round."""
        return cell in self._living_cell_coordinates

    def _will_live(self, cell):  # type: (CellCoords) -> bool
        """Return True if the given cell will survive to the next round."""
        neighbors = self._get_neighbor_coordinates(cell)
        num_living_neighbors = sum(self._is_alive(neighbor) for neighbor in neighbors)

        # any cell with three live neighbors will live or revive by "reproduction"
        if num_living_neighbors == 3:
            return True
        # any dead cell not revived by the step above will remain dead
        if not self._is_alive(cell):
            return False
        # any live cell with more than three live neighbors dies by "overpopulation"
        if num_living_neighbors > 3:
            return False
        # any live cell with fewer than two live neighbors dies by "underpopulation"
        if num_living_neighbors < 2:
            return False
        # any remaining cells are alive and will survive to the next round
        return True

    def _get_neighbor_coordinates(self, cell):  # type: (CellCoords) -> Set[CellCoords]
        """Return the coordinates of all 8 neighboring cells for the given cell.

        The board "wraps" so that cells along opposite boundaries are considered neighbors.
        """
        neighbors = set()  # type: Set[CellCoords]

        for row_offset in (-1, 0, 1):
            for col_offset in (-1, 0, 1):
                # skip the origin cell
                if not row_offset and not col_offset:
                    continue

                row_index = cell.row_index + row_offset
                col_index = cell.col_index + col_offset

                # wrap neighbors around board
                if row_index < 0:
                    row_index = row_index + self.height
                if row_index >= self.height:
                    row_index >= row_index - self.height
                if col_index < 0:
                    col_index = col_index + self.width
                if col_index >= self.width:
                    col_index = col_index - self.width

                # add the neighbor cell to the set of neighbors
                neighbor = CellCoords(row_index, col_index)
                neighbors.add(neighbor)

        return neighbors

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--rows', '-r', type=int, default=4)
    parser.add_argument('--cols', '-c', type=int, default=4)
    parser.add_argument('--brightness', '-b', type=float, default=1)
    parser.add_argument('--turns', '-t', type=int, default=20)
    parser.add_argument('--delay', '-d', type=float, default=0.2)
    parser.add_argument('--orient', '-o', default='ALTERNATING_COLUMN')
    parser.add_argument('--start', '-s', default='NORTHEAST')
    parser.add_argument('--color', '-co', type=str, default='RED')
    args = parser.parse_args()

    game = GameOfLife(
        auto_write=False,
        num_rows=args.rows,
        num_cols=args.cols,
        origin=getattr(matrix.MATRIX_ORIGIN, args.start),
        orientation=getattr(matrix.MATRIX_ORIENTATION, args.orient),
        default_color=getattr(colors, args.color),
    )
    try:
        for _ in range(args.turns):
            time.sleep(args.delay)
            game.render()
            game.next_state()
    finally:
        game.deinit()


discount = [10, 20, 30, 40]

def solution(users, emoticons):
    # answer = [(이모티콘 가입자수, 이모티콘 매출액)]
    # users = [(할인율,  이모티콘 가입한도)]
    # emoticons = [(각 이모티콘 가격)]
    answer = [0,0]
    dis_list = []
    def backtrack(v):
        nonlocal answer
        if v == len(emoticons): # 이모티콘의 개수만큼 다 탐색하면
            cnt = total = 0
            for i in range(len(users)):
                temp = 0
                for j in range(len(emoticons)):
                    if users[i][0] <=dis_list[j]: # 유저가 원하는 할인율보다 각각의 이모티콘 할인율이 더 크면
                        temp += emoticons[j]*(100-dis_list[j])//100  # temp에 j번째 이모티콘의 가격*할인적용
                if temp>=users[i][1]: # 만약 temp비용이 유저의 이코티콘 플러스 서비스보다 크면
                    cnt+=1 # 이모티콘 서비스 가입
                else:
                    total += temp # 아니라면 이모티콘 구입
            if cnt > answer[0] or (cnt==answer[0] and total>answer[1]):
                # 만약 현재의 cnt가 answer의 cnt보다 크거나 만약 answer의 cnt와 현재 cnt가 같을때
                # total이 answer의 total보다 값이 크면 갱신해준다.!
                answer = [cnt, total]
            return

        for i in range(4): # discount는 4개밖에 없으므로 4개의 할인율만 돈다.
            dis_list.append(discount[i]) # 각각 이모티콘 할인율에 이모티콘 할인율을 넣고
            backtrack(v+1) # 개수를 증가시키고 또 반복
            dis_list.pop() # 빼고 또 반복
    backtrack(0)
    return answer

개인 알고리즘 공부/programmers/20230410/이모티콘 할인행사.py

이모티콘 할인행사.py


from TP8 import *

def ouverture(ims):
    ims= erosion(ims)
    ims=dilatation(ims)
    return ims

def fermeture(ims):
    ims=dilatation(ims)
    ims= erosion(ims)
    return ims

def test2nbgris():
    listeimg=  ["img.bmp", "cyto1.bmp"]
    for k in listeimg:
        img=ouvrir(k)
        #affiche(img)
        mon_ouverture_k=ouverture(img)
        affiche(mon_ouverture_k)
        #sauvegarde(mon_ouverture_k,k+"_gris'_ouverture.bmp")
        ma_fermeture_k=fermeture(img)
        affiche(ma_fermeture_k)
        #sauvegarde(ma_fermeture_k,k+"_gris_fermeture.bmp")

def test2nbcouleur():
    listeimg=  ["img.bmp", "cellule.jpg"]
    for k in listeimg:
        img=ouvrir(k)
        mon_ouverture_k=ouverture(img)
        affiche(mon_ouverture_k)
        ma_fermeture_k=fermeture(img)
        affiche(ma_fermeture_k)

def test2bin():
    listeimg=  ["lenabin.bmp", "tanbin.bmp"]
    for k in listeimg:
        img=ouvrir(k)
        mon_ouverture_k=ouverture(img)
        affiche(mon_ouverture_k)
        ma_fermeture_k=fermeture(img)
        affiche(ma_fermeture_k)

#######EXERCICE 2 ###########

def morphocyto1():
    l=[2,5,10]
    img=ouvrir("cyto1.bmp")
    #img=imc2img(img,1)
    for n in l:
        ims=Iterexponentielle(img,0.5,n)
        affiche(ims)

#test2nbgris()
#test2nbcouleur()
##test2bin()
##morphocyto1()


from multiprocessing import Event, Lock
from multiprocessing.managers import BaseManager
import os
import random
import signal
import sys
import sysv_ipc

T = ["airplane", "car", "train", "bike", "shoes"]
Transports = range(len(T))

class Shm():
    hands_start: list[list[int]] = []
    offers: list[int] = []
    playersPID: list[int] = []
    lock = Lock()
    start_game = Event()
    stop_game = Event()
    winner: int = None

    def __init__(self) -> None:
        pass

    def win(self, i: int):
        with self.lock:
            self.winner = i
            self.stop_game.set()

    def wait_for_start(self):
        self.start_game.wait()

    def wait_for_stop(self):
        self.stop_game.wait()

    def get_hand(self, pid) -> tuple[list[int], int]:
        with self.lock:
            if len(self.hands_start) == 0:
                return (None, None)

            self.offers.append(0)
            self.playersPID.append(pid)
            i = len(self.offers) - 1
            hand = self.hands_start.pop()
            hand.sort()

            # launch game if all players are ready
            if len(self.hands_start) == 0:
                self.start_game.set()

            return (hand, i)

    def get_nb_players(self) -> int:
        with self.lock:
            return len(self.playersPID)

    def get_winner(self) -> int:
        with self.lock:
            return self.winner

    def get_offers(self) -> list[int]:
        with self.lock:
            return self.offers

    def get_playersPID(self) -> list[int]:
        with self.lock:
            return self.playersPID

    def offer(self, i: int, nb_cards: int):
        with self.lock:
            self.offers[i] = nb_cards

class Game():
    manager: BaseManager
    ishm: Shm = Shm()
    shm: Shm
    exchanges: sysv_ipc.MessageQueue
    nb_players: int

    def __init__(self, nb_players: int):
        self.nb_players = nb_players

        # clean old IPC mq
        try:
            mq = sysv_ipc.MessageQueue(666)
            mq.remove()
            print("old messagequeue removed")
        except:
            pass

        self.exchanges = sysv_ipc.MessageQueue(666, sysv_ipc.IPC_CREX)

        BaseManager.register("shm", lambda: self.ishm)

        self.manager = BaseManager(address=("127.0.0.1", 6666), authkey=b"cambiecolo")

        # Hands generation
        possible_transports = list(Transports)[-nb_players:]
        print("Possible transports:", possible_transports)
        cards = possible_transports * 5
        print("Cards pool         :", cards)
        random.shuffle(cards)
        print("Cards pool shuffled:", cards)
        self.ishm.hands_start = [cards[i:i + 5] for i in range(0, len(cards), 5)]
        print("Cards:", self.ishm.hands_start)

    def stop(self):
        print("Stopping game")
        self.manager.shutdown()
        self.exchanges.remove()

    def start(self):
        # Start game
        self.manager.start()
        self.manager.connect()
        self.shm = self.manager.shm()

        print("Waiting for all {} players to get ready...".format(self.nb_players))

        self.shm.wait_for_start()

        print("Game started")
        print("PIDs:", self.shm.get_playersPID())

        self.shm.wait_for_stop()

        print("Game finished")
        print("\n!!! Player {} (pid {}) won !!!\n".format(self.shm.get_winner(), self.shm.get_playersPID()[self.shm.get_winner()]))
        print("PIDs:", self.shm.get_playersPID())

        for pid in self.shm.get_playersPID():
            try:
                print("Killed pid {}".format(pid))
                os.kill(pid, signal.SIGINT)
            except:
                print("Can't kill pid {}".format(pid))

if __name__ == "__main__":
    try:
        n = int(sys.argv[1])
        if not 2 <= n <= 5:
            raise ValueError
    except:
        print("Usage: {} <nb_players [2;5]>".format(sys.argv[0]))
        exit()

    g = Game(n)
    g.start()
    g.stop()


# import library
import pandas as pd
import matplotlib.pyplot as plot

# read data
data_public = pd.read_csv("survey_results_public.csv",
                        usecols=["Respondent", "Age", "WorkWeekHrs", "YearsCodePro", "Age1stCode", "CompTotal"],
                        index_col="Respondent")

# drop null
data_public.dropna(inplace=True)
# Converting text to numeric data
data_public = data_public.replace(to_replace={"Younger than 5 years":"0"})
data_public = data_public.replace(to_replace={"Older than 85":"90"})
data_public = data_public.replace(to_replace={"Less than 1 year":"0"})
data_public = data_public.replace(to_replace={"More than 50 years":"55"})
# Converting work week hrs
data_public["WorkWeekHrs"] = data_public["WorkWeekHrs"] / 40

# change data type to float
data_public["Age1stCode"] = data_public["Age1stCode"].astype("float64")
data_public["YearsCodePro"] = data_public["YearsCodePro"].astype("float64")
# print data type
print(data_public.dtypes)
# show correlation between data
print(data_public.corr(method='pearson'))

# Creating a plots

plot.scatter(data_public["Age"], data_public["YearsCodePro"])
plot.title("Age depending on Years code pro")
plot.xlabel("Age")
plot.ylabel("Years Code Pro")
plot.show()

plot.scatter(data_public["YearsCodePro"], data_public["CompTotal"])
plot.title("Years code pro depending on CompTotal")
plot.xlabel("Years Code Pro")
plot.ylabel("CompTotal")
plot.show()

plot.scatter(data_public["Age"], data_public["CompTotal"])
plot.title("Age depending on CompTotal")
plot.xlabel("Age")
plot.ylabel("CompTotal")
plot.show()

plot.scatter(data_public["Age1stCode"], data_public["Age"])
plot.title("Age 1st code depending on Age")
plot.xlabel("Age 1st Code")
plot.ylabel("Age")
plot.show()

plot.scatter(data_public["Age"], data_public["WorkWeekHrs"])
plot.title("Work Week Hrs depending on Age")
plot.xlabel("Age")
plot.ylabel("WorkWeekHrs")
plot.show()
# dependent variable: "YearsCodePro"
# independent variables: "Age" & "Age1stCode"


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
  @Date    : 2019-04-03
  @Author  : Kaka
  @File    : groupAnagrams.py
  @Software: PyCharm
  @Contact : https://leetcode-cn.com/problems/group-anagrams/
  @Desc    : 字母异位词分组
  给定一个字符串数组，将字母异位词组合在一起。字母异位词指字母相同，但排列不同的字符串。

    示例:

    输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
    输出:
    [
      ["ate","eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]
    说明：

    所有输入均为小写字母。
    不考虑答案输出的顺序。
"""

class Solution(object):
    def groupAnagrams(self, strs):
        """O(n),O(n)
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        dic = {}
        for i,str in enumerate(strs):
            sstr = ''.join(sorted(str))
            if dic.get(sstr)==None:
                dic[sstr] =[i]
            else:
                dic[sstr].append(i)
        rs = []
        for k in dic:
            rs.append([ strs[i] for i in dic[k]])

        print(dic.values())

if __name__ == '__main__':
    strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
    solu = Solution()
    solu.groupAnagrams(strs)


# -*- coding: utf-8 -*-
"""
Created on Tue Dec 19 16:06:50 2017

@author: Adwait
"""

def isPalindrome(aString):
    s=aString
    s=s.lower()
    s1=''
    for l in s:
        if l in 'abcdefghijklmnopqrstuvwxyz1234567890':
            s1+=l
    ans=True
    for n in range(len(s1)):
        if s1[n]==s1[len(s1)-1-n]:
            ans=ans and True
        else:
            ans=ans and False
    return ans


import pickle

with open("database/doctors.pkl", "wb") as file :
    doctors = [["Dr. Major RS Rengan", "Surgeon"], ["Dr. AP Prem", "Physician"], ["Dr. Rajan Santosham", "Ortho"], ["Dr. Barani R", "Physician"], ["Dr. Yamini", "Ortho"], ["Dr. Indira G", "Surgeon"]]
    pickle.dump(doctors, file)

with open("database/nurses.pkl", "wb") as file :
    nurses = [["Anjali Kumari", "None"], ["Kajal Kumari", "None"], ["Shilpa", "Ortho"]]
    pickle.dump(nurses, file)

with open("database/pharmacists.pkl", "wb") as file :
    pharmacists = [["Apollo Pharmacy", "None"], ["MedPlus Pharmacy", "None"], ["Velu Pharmacy", "None"]]
    pickle.dump(pharmacists, file)

with open("database/doctors.pkl", "rb") as file :
    print(pickle.load(file))

with open("database/patients.pkl", "wb") as file :
    patients = [["Richa Singh", 21, "female"], ["Rohit Kumar", 19, "male"]]
    pickle.dump(patients, file)

with open("database/patients.pkl", "rb") as file :
    print(pickle.load(file))

with open("database/appointments.pkl", "wb") as file :
    appointments = [["Dr. Major RS Rengan", "Richa Singh",(16,11,2021)], ["Dr. Rajan Santosham", "Rohit Kumar", (16,11,2021)]]
    pickle.dump(appointments, file)


# PYTHON configuration file.
# Description:  Example of dijet mass plot
#               with corrected and uncorrected jets
#               for various jet algorithms
# Author: Kalanand Mishra
# Date:  22 - November - 2009

import FWCore.ParameterSet.Config as cms

process = cms.Process("Ana")
process.load("FWCore.MessageService.MessageLogger_cfi")
#############   Set the number of events #############
process.maxEvents = cms.untracked.PSet(
    input = cms.untracked.int32(1000)
)
#############   Define the source file ###############
process.source = cms.Source("PoolSource",
		fileNames = cms.untracked.vstring(
			#'file:Filt_RSGllsuon.root'
			'file:Filt_QCD.root'
    #'/store/mc/Summer09/QCDFlat_Pt15to3000/GEN-SIM-RECO/MC_31X_V9_7TeV-v1/0000/FABD2A94-C0D3-DE11-B6FD-00237DA13C2E.root'
    )
)
#process.source.inputCommands = cms.untracked.vstring("keep *","drop *_MEtoEDMConverter_*_*")

process.TFileService=cms.Service("TFileService",
		fileName=cms.string('TriggerPlotter.root'))

#############   User analyzer (PF jets) ##
process.TriggerPlots = cms.EDAnalyzer("hltTriggerPlots",
    # Uncorrected PFJets
    hltFilter           = cms.string('hltCambridgeAachen8PFJetsTrim'),
    # Name of the output ROOT file containing the histograms
    #HistoFileName = cms.untracked.string('TriggerPlots.root')
)

#############   Path       ###########################
process.p = cms.Path(process.TriggerPlots)

#############   Format MessageLogger #################
process.MessageLogger.cerr.FwkReport.reportEvery = 100


def element_content_as_string(element):
    """Serialize etree.Element.

    Note: element may contain more than one child or only text (i.e. no child
          at all). Therefore the resulting string may raise an exception, when
          passed back to etree.XML().
    """
    if len(element) == 0:
        return element.text or ""  # Make sure, None is returned as ''
    stream = compat.StringIO()
    for childnode in element:
        stream.write(xml_to_bytes(childnode, pretty_print=False) + "\n")
        # print(xml_to_bytes(childnode, pretty_print=False), file=stream)
    s = stream.getvalue()
    stream.close()
    return s


import argparse
import os
import torch.optim as optim
import torch.utils.data as util_data
import itertools

import network
import pre_process as prep
import lr_schedule
from util import *
from data_list import ImageList_au, ImageList_land_au

optim_dict = {'SGD': optim.SGD, 'Adam': optim.Adam}

def main(config):
    ## set loss criterion
    use_gpu = torch.cuda.is_available()

    ## prepare data
    dsets = {}
    dset_loaders = {}
    dsets['source'] = {}
    dset_loaders['source'] = {}

    dsets['source']['test'] = ImageList_au(config.src_test_path_prefix,
                                          transform=prep.image_test(crop_size=config.crop_size))

    dset_loaders['source']['test'] = util_data.DataLoader(dsets['source']['test'], batch_size=config.eval_batch_size,
                                                         shuffle=False, num_workers=config.num_workers)

    dsets['target'] = {}
    dset_loaders['target'] = {}

    dsets['target']['test'] = ImageList_au(config.tgt_test_path_prefix,
                                          transform=prep.image_test(crop_size=config.crop_size))

    dset_loaders['target']['test'] = util_data.DataLoader(dsets['target']['test'], batch_size=config.eval_batch_size,
                                                         shuffle=False, num_workers=config.num_workers)

    ## set network modules
    base_net = network.network_dict[config.base_net]()
    land_enc = network.network_dict[config.land_enc](land_num=config.land_num)
    au_enc = network.network_dict[config.au_enc](au_num=config.au_num)
    invar_shape_enc = network.network_dict[config.invar_shape_enc]()
    feat_gen = network.network_dict[config.feat_gen]()

    if use_gpu:
        base_net = base_net.cuda()
        land_enc = land_enc.cuda()
        au_enc = au_enc.cuda()
        invar_shape_enc = invar_shape_enc.cuda()
        feat_gen = feat_gen.cuda()

    base_net.train(False)
    land_enc.train(False)
    au_enc.train(False)
    invar_shape_enc.train(False)
    feat_gen.train(False)

    print(base_net, land_enc, au_enc, invar_shape_enc, feat_gen)

    if not os.path.exists(config.write_path_prefix + config.mode):
        os.makedirs(config.write_path_prefix + config.mode)
    if not os.path.exists(config.write_res_prefix + config.mode):
        os.makedirs(config.write_res_prefix + config.mode)

    test_type = 'target'  # 'source'

    if config.start_epoch <= 0:
        raise (RuntimeError('start_epoch should be larger than 0\n'))

    res_file = open(config.write_res_prefix + config.mode + '/' + test_type + '_test_AU_pred_' + str(config.start_epoch) + '.txt', 'w')

    for epoch in range(config.start_epoch, config.n_epochs + 1):

        base_net.load_state_dict(
            torch.load(config.write_path_prefix + config.mode + '/base_net_' + str(epoch) + '.pth'))
        land_enc.load_state_dict(
            torch.load(config.write_path_prefix + config.mode + '/land_enc_' + str(epoch) + '.pth'))
        au_enc.load_state_dict(
            torch.load(config.write_path_prefix + config.mode + '/au_enc_' + str(epoch) + '.pth'))
        invar_shape_enc.load_state_dict(
            torch.load(config.write_path_prefix + config.mode + '/invar_shape_enc_' + str(epoch) + '.pth'))
        feat_gen.load_state_dict(
            torch.load(config.write_path_prefix + config.mode + '/feat_gen_' + str(epoch) + '.pth'))

        if test_type == 'source':
            f1score_arr, acc_arr = AU_detection_eval_src(dset_loaders[test_type]['test'], base_net, au_enc, use_gpu=use_gpu)
        else:
            f1score_arr, acc_arr = AU_detection_eval_tgt(dset_loaders[test_type]['test'], base_net, land_enc, au_enc,
                                                         invar_shape_enc, feat_gen, use_gpu=use_gpu)

        print('epoch =%d, f1 score mean=%f, accuracy mean=%f' %(epoch, f1score_arr.mean(), acc_arr.mean()))
        print>> res_file, '%d\t%f\t%f' % (epoch, f1score_arr.mean(), acc_arr.mean())

    res_file.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    # Model configuration.
    parser.add_argument('--gpu_id', type=str, default='0', help='device id to run')
    parser.add_argument('--crop_size', type=int, default=176, help='crop size for images')
    parser.add_argument('--output_size', type=int, default=44, help='size for landmark response map')
    parser.add_argument('--au_num', type=int, default=6, help='number of AUs')
    parser.add_argument('--land_num', type=int, default=49, help='number of landmarks')
    parser.add_argument('--eval_batch_size', type=int, default=4, help='mini-batch size for evaluation')
    parser.add_argument('--start_epoch', type=int, default=1, help='starting epoch')
    parser.add_argument('--n_epochs', type=int, default=10, help='number of total epochs')
    parser.add_argument('--num_workers', type=int, default=4)
    parser.add_argument('--mode', type=str, default='weak', choices=['weak', 'full'])
    parser.add_argument('--base_net', type=str, default='Feat_Enc')
    parser.add_argument('--land_enc', type=str, default='Land_Detect')
    parser.add_argument('--au_enc', type=str, default='AU_Detect')
    parser.add_argument('--invar_shape_enc', type=str, default='Texture_Enc')
    parser.add_argument('--feat_gen', type=str, default='Generator')

    # Directories.
    parser.add_argument('--write_path_prefix', type=str, default='data/snapshots/')
    parser.add_argument('--write_res_prefix', type=str, default='data/res/')
    parser.add_argument('--src_test_path_prefix', type=str, default='data/list/BP4D_test')
    parser.add_argument('--tgt_test_path_prefix', type=str, default='data/list/emotioNet_test')

    config = parser.parse_args()
    os.environ['CUDA_VISIBLE_DEVICES'] = config.gpu_id

    print(config)
    main(config)


from django.urls import path, include
from .views import PostsList, PostsSearch, PostDetail, PostCreate, PostUpdate, PostDelete, PostsListInCategory, \
    SubscribeCategoryView, Testtt
from django.views.generic import RedirectView
from django.views.decorators.cache import cache_page

urlpatterns = [
    # path('', RedirectView.as_view(url='accounts/')),  # instead of error page, it will redirect to the needed page
    path('posts/', cache_page(60)(PostsList.as_view()), name='posts_list'),
    path('posts/<int:pk>', PostDetail.as_view(), name='post_detail'),
    path('posts/search/', PostsSearch.as_view(), name='posts_search_list'),

    path('article/create/', PostCreate.as_view(), name='article_create'),
    path('article/<int:pk>/update/', PostUpdate.as_view(), name='article_update'),
    path('article/<int:pk>/delete/', PostDelete.as_view(), name='article_delete'),

    path('news/create/', PostCreate.as_view(), name='news_create'),
    path('news/<int:pk>/update/', PostUpdate.as_view(), name='news_update'),
    path('news/<int:pk>/delete/', PostDelete.as_view(), name='news_delete'),

    path('category/<int:category_id>/', PostsListInCategory.as_view(), name='posts_in_category'),
    path('category/<int:category_id>/subscribe/', SubscribeCategoryView.as_view(), name='subscribe_category'),

    path('testtt/', Testtt.as_view(), name='posts_testtt_list'),
]


import asyncio
import datetime
import re
from datetime import timedelta

import asynctest
from django.utils import timezone

from feed_fetcher.tests.utils import get_cursor, get_session
from feed_fetcher.workers import fill_queue, pull_data

class FillQueueTestCase(asynctest.TestCase):
    async def setUp(self):
        self.test_feeds = [
            (1, 'https://www.dachi.me/rss/news', False, timezone.now(), 60, 1)
        ]
        self.cur = get_cursor(self.test_feeds)
        self.data = asyncio.Queue()

    async def test_tasks_are_added_to_the_queue(self):
        await fill_queue(self.data, self.cur)
        self.assertEqual(self.data.qsize(), 1)
        data = await self.data.get()
        self.cur.execute.assert_awaited()
        self.cur.fetchall.assert_awaited()
        self.assertEqual(data[1], 'https://www.dachi.me/rss/news')

    async def test_tasks_are_being_scheduled_correctly(self):
        await fill_queue(self.data, self.cur)
        self.assertEqual(self.data.qsize(), 1)
        data = await self.data.get()
        self.cur.execute.assert_awaited()
        self.cur.fetchall.assert_awaited()
        scheduled_date = data[3] + timedelta(seconds=data[4])
        scheduled_date_str = datetime.datetime.strftime(
            scheduled_date, "%Y-%m-%d %H:%M:%S.%f")
        query = (f"UPDATE feed SET scan_after = '{scheduled_date_str}' "
                 f"WHERE id = 1")
        cur_execute_args_list = self.cur.execute.await_args_list
        self.assertEqual(len(cur_execute_args_list), 2)
        executed_query = self.cur.execute.await_args_list[1][0][0]
        executed_query = re.sub(r"\+\d{2}\:\d{2}'", r"'", executed_query)
        self.assertEqual(query, executed_query)

class PullData(asynctest.TestCase):
    async def setUp(self):
        self.test_feeds = [
            (1, 'https://www.dachi.me/rss/news', False, timezone.now(), 60, 1)
        ]
        self.data = asyncio.Queue()
        await self.data.put(self.test_feeds[0])

    @asynctest.patch('feed_fetcher.workers.terminate_feed')
    @asynctest.patch('feed_fetcher.workers.push_to_db')
    @asynctest.patch('feed_fetcher.workers.get_feed_as_dict')
    @asynctest.patch('feed_fetcher.workers.aiohttp.ClientSession')
    async def test_success_request_leads_to_correct_calls(
            self, mock_client_session, mock_parser, mock_db_insert,
            mock_feed_termination
    ):
        client, response = get_session("Dummy content", 200)
        mock_client_session.return_value.__aenter__.side_effect = client
        conn = asynctest.CoroutineMock()
        await pull_data(self.data, conn)
        self.assertEqual(self.data.qsize(), 0)
        response.assert_called_once()
        mock_parser.assert_awaited()
        mock_db_insert.assert_awaited()
        mock_feed_termination.assert_not_awaited()

    @asynctest.patch('feed_fetcher.workers.terminate_feed')
    @asynctest.patch('feed_fetcher.workers.push_to_db')
    @asynctest.patch('feed_fetcher.workers.get_feed_as_dict')
    @asynctest.patch('feed_fetcher.workers.aiohttp.ClientSession')
    async def test_back_off_mechanism(
            self, mock_client_session, mock_parser, mock_db_insert,
            mock_feed_termination
    ):
        client, response = get_session("Dummy content", 400)
        mock_client_session.return_value.__aenter__.side_effect = client
        conn = asynctest.CoroutineMock()
        await pull_data(self.data, conn)
        self.assertEqual(self.data.qsize(), 0)
        response.assert_called()
        self.assertEqual(response.call_count, 5)
        mock_parser.assert_not_awaited()
        mock_db_insert.assert_not_awaited()
        mock_feed_termination.assert_awaited()


count_numbers = int(input())

left_sum = 0
right_sum = 0

for i in range(1, 2 * count_numbers + 1):
    current_number = int(input())

    if i <= count_numbers:
        left_sum = left_sum + current_number
    else:
        right_sum = right_sum + current_number

if left_sum == right_sum:
    print(f"Yes, sum = {left_sum}")
else:
    print(f"No, diff = {abs(left_sum - right_sum)}")


import openerp
from openerp.osv import fields, osv
from openerp.tools.translate import _

class product_minimum(osv.Model):
    _name = 'product.minimum'

    def _get_product(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        for rec in self.browse(cr, uid, ids, context=context):
            result[rec.id] = False
            if rec.product_tmp_id:
                product_ids = self.pool.get('product.product').search(cr, uid, [('product_tmpl_id', '=', rec.product_tmp_id.id)])
                if product_ids:
                    result[rec.id] = product_ids[0]
        return result

    _columns={
        'location_id': fields.many2one('stock.location', 'Location', required=True, domain=[('usage', '=', 'internal')]),
        'product_tmp_id': fields.many2one('product.template', 'Product'),
        'product_id': fields.function(_get_product, type='many2one', relation='product.product', string='Product'),
        'quantity': fields.float('Minimum Qty'),
    }


import numpy as np
import matplotlib.pyplot as plt
import cv2

#please make sure to keep the face images in the same folder as code
#before running this

#Task 4
#Part 1
I = cv2.imread('face 02 7043565.jpg', 1);
I = cv2.cvtColor(I, cv2.COLOR_BGR2RGB)
I = np.clip(I, 0, 255)

J = I[50:600, 200:800]
#cropped the image

J = cv2.cvtColor(J, cv2.COLOR_RGB2GRAY)
cropped_resized_gray = cv2.resize(J, (256, 256), interpolation = cv2.INTER_AREA)
cropped_resized_gray = np.clip(cropped_resized_gray, 0, 255)

fig, ax = plt.subplots(1, 2)
fig.suptitle('Display img and resized gray img')

ax[0].imshow(I)
ax[0].set(title="The original img")

ax[1].imshow(cropped_resized_gray, cmap=plt.cm.gray)
ax[1].set(title="Cropped resized gray img")
plt.show()

#Part 2
noise = 15*np.random.randn(256,256)
gray_with_noise = cropped_resized_gray + noise

plt.imshow(gray_with_noise, cmap=plt.cm.gray)

#Part 3
hist_without_noise = cv2.calcHist([cropped_resized_gray], [0], None, [256], [0,256])
hist_with_noise = cv2.calcHist([np.clip(np.uint8(gray_with_noise), 0, 255)], [0], None, [256], [0,256])

fig, ax = plt.subplots(1, 2)
fig.suptitle('Added Gaussian noise')

ax[0].plot(hist_without_noise)
ax[0].set(title="Without Noise")

ax[1].plot(hist_with_noise)
ax[1].set(title="With Noise")
plt.show()

#Part 4

#First let's create a Gaussian kernel
kernel_1 = cv2.getGaussianKernel(5, 1) #size, std is 1
kernel_5 = cv2.getGaussianKernel(5, 5) #std=5
kernel_10 = cv2.getGaussianKernel(5, 10) #std=10
kernel_15 = cv2.getGaussianKernel(5, 15) #std=15
window = np.outer(kernel_1, kernel_1.T) #the 5x5 kernel

#The convolution function
def conv(img, kernel):
    img_row, img_col = img.shape
    kernel_row, kernel_col = kernel.shape
    final_img = np.zeros(img.shape)

    pad_h = int((kernel_row-1)/2)
    pad_w = int((kernel_col-1)/2)

    padded_img = np.zeros((img_row+2*pad_h, img_col+2*pad_w))

    padded_img[pad_h:padded_img.shape[0]-pad_h,pad_w:padded_img.shape[1]-pad_w] = img

    for i in range(img_row):
        for j in range(img_col):
            final_img[i, j] = np.sum(kernel*padded_img[i:i+kernel_row, j:j+kernel_col])

    return final_img

#Part 5
output_img = conv(gray_with_noise, window)

fig, ax = plt.subplots(1, 2)
fig.suptitle('Applying custom Gaussian filter')

ax[0].imshow(gray_with_noise, cmap=plt.cm.gray)
ax[0].set(title="Gray img with noise")

ax[1].imshow(output_img, cmap=plt.cm.gray)
ax[1].set(title="Gray img after filter applied")
plt.show()

fig, ax = plt.subplots(2, 2)

ax[0,0].imshow(output_img, cmap=plt.cm.gray)
ax[0,0].set(title="Gaussian Filter with std 1")

ax[0,1].imshow(conv(gray_with_noise, np.outer(kernel_5, kernel_5.T)), cmap=plt.cm.gray)
ax[0,1].set(title="Gaussian Filter with std 1")

ax[1,0].imshow(conv(gray_with_noise, np.outer(kernel_10, kernel_10.T)), cmap=plt.cm.gray)
ax[1,0].set(title="Gaussian Filter with std 10")

ax[1,1].imshow(conv(gray_with_noise, np.outer(kernel_15, kernel_15.T)), cmap=plt.cm.gray)
ax[1,1].set(title="Gaussian Filter with std 15")

plt.tight_layout()
plt.show()

#Part 6
output_img = conv(gray_with_noise, np.outer(kernel_15, kernel_15.T))
output_with_built_in = cv2.GaussianBlur(gray_with_noise, (5,5), 15)
#https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html#void%20GaussianBlur(InputArray%20src,%20OutputArray%20dst,%20Size%20ksize,%20double%20sigmaX,%20double%20sigmaY,%20int%20borderType)

fig, ax = plt.subplots(1, 2)
fig.suptitle('Comparing custom filter with built-in filter')

ax[0].imshow(output_img, cmap=plt.cm.gray)
ax[0].set(title="Gray img after Custom filter")

ax[1].imshow(output_with_built_in, cmap=plt.cm.gray)
ax[1].set(title="Gray img after Built-in Filter")
plt.show()

hist_my_func = cv2.calcHist([np.uint8(output_img)], [0], None, [256], [0,256])
hist_built_in = cv2.calcHist([np.uint8(output_with_built_in)], [0], None, [256], [0,256])

fig, ax = plt.subplots(1, 2)
fig.suptitle('Compare histograms of filtered images')

ax[0].plot(hist_my_func)
ax[0].set(title="Hist custom function")

ax[1].plot(hist_built_in)
ax[1].set(title="Hist built-in function")
plt.show()

#Task 5

sobel_filter = np.array([[-1, 0, 1],[-2, 0, 2],[-1, 0, 1]])
output_sobel_vertical = conv(cropped_resized_gray, sobel_filter)
output_sobel_horizontal = conv(cropped_resized_gray, sobel_filter.T)#np.flip axis=0

fig, ax = plt.subplots(1, 3)
fig.suptitle('')

ax[0].imshow(cropped_resized_gray, cmap=plt.cm.gray)
ax[0].set(title="Original image")

ax[1].imshow(output_sobel_vertical, cmap=plt.cm.gray)
ax[1].set(title="After vertical sobel")

ax[2].imshow(output_sobel_horizontal, cmap=plt.cm.gray)
ax[2].set(title="After horizontal sobel")
plt.show()

#Comparison with in-built func
sobelx = cv2.Sobel(cropped_resized_gray,cv2.CV_64F,1,0,ksize=3)
sobely = cv2.Sobel(cropped_resized_gray,cv2.CV_64F,0,1,ksize=3)

fig, ax = plt.subplots(1, 3)
fig.suptitle('In-built Sobel Filter')

ax[0].imshow(cropped_resized_gray, cmap=plt.cm.gray)
ax[0].set(title="Original image")

ax[1].imshow(sobelx, cmap=plt.cm.gray)
ax[1].set(title="After vertical sobel")

ax[2].imshow(sobely, cmap=plt.cm.gray)
ax[2].set(title="After horizontal sobel")
plt.show()

#On more images
I = cv2.imread('face 03 7043565.jpg', 1);
I = cv2.cvtColor(I, cv2.COLOR_BGR2RGB)
I = np.clip(I, 0, 255)

J = I[50:600, 200:800]
#cropped the image

J = cv2.cvtColor(J, cv2.COLOR_RGB2GRAY)
cropped_resized_gray = cv2.resize(J, (256, 256), interpolation = cv2.INTER_AREA)
cropped_resized_gray = np.clip(cropped_resized_gray, 0, 255)

output_sobel_vertical = conv(cropped_resized_gray, sobel_filter)
output_sobel_horizontal = conv(cropped_resized_gray, sobel_filter.T)#np.flip axis=0

fig, ax = plt.subplots(1, 3)
fig.suptitle('')

ax[0].imshow(cropped_resized_gray, cmap=plt.cm.gray)
ax[0].set(title="Original image")

ax[1].imshow(output_sobel_vertical, cmap=plt.cm.gray)
ax[1].set(title="After vertical sobel")

ax[2].imshow(output_sobel_horizontal, cmap=plt.cm.gray)
ax[2].set(title="After horizontal sobel")
plt.show()

sobelx = cv2.Sobel(cropped_resized_gray,cv2.CV_64F,1,0,ksize=3)
sobely = cv2.Sobel(cropped_resized_gray,cv2.CV_64F,0,1,ksize=3)

fig, ax = plt.subplots(1, 3)
fig.suptitle('In-built Sobel Filter')

ax[0].imshow(cropped_resized_gray, cmap=plt.cm.gray)
ax[0].set(title="Original image")

ax[1].imshow(sobelx, cmap=plt.cm.gray)
ax[1].set(title="After vertical sobel")

ax[2].imshow(sobely, cmap=plt.cm.gray)
ax[2].set(title="After horizontal sobel")
plt.show()


def headerHTML(header,fname):
        """given the bytestring ABF header, make and launch HTML."""
        html=""
        html+="
%s
"%(fname)
        html+=pprint.pformat(header, indent=1)
        html=html.replace("\n",'
').replace(" "," ")
        html=html.replace(r"\x00","")
        html+=""
        print("saving header file:",fname)
        f=open(fname,'w')
        f.write(html)
        f.close()
        webbrowser.open(fname)


class Solution:
    def find_averages(self, k, arr):
        result = []
        window_sum = 0
        window_start = 0
        for window_end in range(len(arr)):
            window_sum += arr[window_end]
            if window_end >= k - 1:
                result.append(window_sum / k)
                window_sum -= arr[window_start]
                window_start += 1
        return result

def main():
    solution = Solution()
    print(solution.find_averages(5, [1, 3, 2, 6, -1, 4, 1, 8, 2]))

if __name__ == '__main__':
    main()


# 4948 베르트랑 공준
# https://www.acmicpc.net/problem/4948
n = 123456
temp = [1] * (2*n+1)
temp[0] = temp[1] = 0
for i in range(2, n//2+1):
    for j in range(i*2, n*2+2, i):
        if temp[j]:
            temp[j] = 0

while True:
    cnt = 0
    n = int(input())
    if n == 0:
        break

    cnt = temp[n+1:2*n+1].count(1)
    print(cnt)


import cv2
import numpy as np
from scipy.stats import linregress
import serial
import time

# 웹캠 해상도 설정
FRAME_WIDTH = 640
FRAME_HEIGHT = 480

# 파이 시리얼 포트 설정 및 연결 대기
arduino = serial.Serial('COM8', 9600)
time.sleep(2)

#파이 시리얼 통신 코드
def py_serial(line_angle_input, width_input):

    # 음수 값이면 '-'를 붙여서 전송
    if float(line_angle_input) < 0:
        line_angle_input = "-" + line_angle_input
    if float(width_input) < 0:
        width_input = "-" + width_input
    # 숫자 두개를 하나의 문자열로 변환하여 통신(오버헤드 줄이려면 한 문자열로 하는게 좋음)
    message = f"{line_angle_input},{width_input}\n"
    arduino.write(message.encode())
    time.sleep(0.05)

    # 아두이노로부터 입력 받은 응답을 버퍼를 비우기 위해 읽어옴
    while arduino.in_waiting > 0:
        response = arduino.readline().decode().strip()
        print(response)

def py_serial(line_angle_input, width_input):

    # 음수 값이면 '-'를 붙여서 전송
    if float(line_angle_input) < 0:
        line_angle_input = "-" + line_angle_input
    if float(width_input) < 0:
        width_input = "-" + width_input

    message = f"{line_angle_input},{width_input}\n"
    arduino.write(message.encode())
    time.sleep(0.05)

    # 아두이노로부터 입력 받은 응답을 버퍼를 비우기 위해 읽어옴
    while arduino.in_waiting > 0:
        response = arduino.readline().decode().strip()
        print(response)

def undistort_frame(frame):
    # 카메라 캘리브레이션 매개 변수
    camera_matrix = np.array([[1.0, 0, FRAME_WIDTH / 2],
                              [0, 1.0, FRAME_HEIGHT / 2],
                              [0, 0, 1.0]], dtype=np.float32)
    distortion_coefficients = np.zeros((4, 1), dtype=np.float32)

    # 왜곡 보정
    undistorted_frame = cv2.undistort(frame, camera_matrix, distortion_coefficients)
    return undistorted_frame

def detect_dotted_line():
    # 웹캠 열기
    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_WIDTH)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT)

    # 웹캠 영상 읽기
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        # 영상 보정
        frame = undistort_frame(frame)

        # 영상 크기
        height, width = frame.shape[:2]

        # 원의 중심 좌표와 반지름 설정
        center_x = int(width / 2)
        center_y = int(height / 2)
        radius = int(min(center_x, center_y) * 0.6)

        # ROI (원 내부 영역) 생성
        mask = np.zeros((height, width), dtype=np.uint8)
        cv2.circle(mask, (center_x, center_y), radius, (255, 255, 255), -1)
        roi = cv2.bitwise_and(frame, frame, mask=mask)

        # 이미지를 그레이스케일로 변환
        gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)

        # 이미지 이진화
        _, binary = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY)

        # 추세선을 위한 점 리스트 초기화
        dotted_points = []
        solid_points = []
        solid_rect_lines = []  # 실선의 긴 변을 저장하는 리스트

        # 점선과 실선 검출을 위한 컨투어 찾기
        contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # 점선과 실선 그리기
        for contour in contours:
            area = cv2.contourArea(contour)
            if 300 < area < 1000:  # 점선으로 인식할 면적 조건 설정
                # 직사각형의 꼭지점 좌표 구하기
                rect = cv2.minAreaRect(contour)
                box = cv2.boxPoints(rect)
                box = np.intp(box)

                # 점선 그리기
                cv2.drawContours(frame, [box], 0, (0, 0, 255), 2)

                # 중심점 좌표 수집
                cx = int(rect[0][0])
                cy = int(rect[0][1])
                dotted_points.append((cx, cy))
            elif area >= 1000:  # 실선으로 인식할 면적 조건 설정
                # 직사각형의 꼭지점 좌표 구하기
                rect = cv2.minAreaRect(contour)
                box = cv2.boxPoints(rect)
                box = np.intp(box)

                # 실선 그리기
                cv2.drawContours(frame, [box], 0, (255, 255, 0), 2)

                # 중심점 좌표 수집
                cx = int(rect[0][0])
                cy = int(rect[0][1])
                solid_points.append((cx, cy))

                # 가장 긴 변의 직선 그리기
                rect_lines = cv2.boxPoints(rect)
                rect_lines = np.intp(rect_lines)
                longest_line = np.argmax(np.linalg.norm(rect_lines[:-1] - rect_lines[1:], axis=1))

                # 가장 긴 변의 두 점
                p1 = rect_lines[longest_line]
                p2 = rect_lines[(longest_line + 1) % 4]

                # 직선의 방정식 계산
                dx = p2[0] - p1[0]
                dy = p2[1] - p1[1]
                if dx != 0:
                    slope = dy / dx
                else:
                    slope = np.inf

                # 직선을 화면 밖까지 그리기
                x1 = p1[0] - int((p1[1] - 0) / slope) if slope != 0 else p1[0]
                y1 = 0
                x2 = p2[0] + int((height - p2[1]) / slope) if slope != 0 else p2[0]
                y2 = height - 1

                cv2.line(frame, (x1, y1), (x2, y2), (255, 0, 255), 2)
                solid_rect_lines.append(rect_lines[longest_line])

        # 점선 추세선 그리기
        if len(dotted_points) > 1:
            xs, ys = zip(*dotted_points)
            unique_xs = np.unique(xs)
            if len(unique_xs) == 1:
                continue
            slope, intercept, _, _, _ = linregress(xs, ys)
            if np.isnan(slope) or np.isnan(intercept):
                continue

            # 점선 추세선 그리기
            x1 = 0
            x2 = width
            y1 = int(slope * x1 + intercept)
            y2 = int(slope * x2 + intercept)

            cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)

            # 가장 긴 변의 직선과 점선 추세선의 교점 계산
            dx = x2 - x1
            dy = y2 - y1
            if dx != 0:
                line_slope = dy / dx
                line_intercept = y1 - line_slope * x1
                if line_slope != slope:
                    intersection_x = (intercept - line_intercept) / (line_slope - slope)
                    intersection_y = slope * intersection_x + intercept

                    # 화면에 교점 표시
                    if np.isfinite(intersection_x) and np.isfinite(intersection_y) and 0 <= intersection_x < width:
                        cv2.circle(frame, (int(intersection_x), int(intersection_y)), 5, (0, 255, 255), -1)

                        # 교점의 x 좌표에 따라 동작 결정 (아예 여유를 안줬는데 straight로 갔으면 하는 정도의 여유줘야함)
                        if intersection_x > center_x:
                            cv2.putText(frame, 'Turn right', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
                        elif intersection_x < center_x:
                            cv2.putText(frame, 'Turn left', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
                        else:
                            cv2.putText(frame, 'Go straight', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
                else:
                    print("No intersection")
            else:
                print("No intersection")

        # 원의 영역 표시
        cv2.circle(frame, (center_x, center_y), radius, (255, 0, 0), 2)

        # Calculate the angle between the dotted line and the horizontal axis
        angle = None
        if len(dotted_points) > 1:
            xs, ys = zip(*dotted_points)
            unique_xs = np.unique(xs)
            if len(unique_xs) == 1:
                continue
            slope, intercept, _, _, _ = linregress(xs, ys)
            if np.isnan(slope) or np.isnan(intercept):
                continue

            x1 = 0
            x2 = width
            y1 = int(slope * x1 + intercept)
            y2 = int(slope * x2 + intercept)

            vec1 = np.array([1, 0])  # Vector along the horizontal axis
            vec2 = np.array([x2 - x1, y2 - y1])  # Vector along the dotted line
            vec2_normalized = vec2 / np.linalg.norm(vec2)  # Normalize the dotted line vector
            angle = np.degrees(np.arccos(np.dot(vec1, vec2_normalized)))

        # Calculate the midpoint of the right solid line
        midpoint_x = None
        distance_to_right_line = None
        if len(solid_points) > 0:
            p1 = rect_lines[longest_line]
            p2 = rect_lines[(longest_line + 1) % 4]
            midpoint_x = int((p1[0] + p2[0]) / 2)

            # 차의 위치 좌표 (예시로 가운데 좌표 사용)
            cx = int(width / 2)
            cy = int(height / 2)

            # 오른쪽 실선과 차의 거리 계산
            dx = p2[0] - p1[0]
            dy = p2[1] - p1[1]
            if dx != 0:
                line_slope = dy / dx
                line_intercept = p1[1] - line_slope * p1[0]
                distance_to_right_line = abs(line_slope * cx - cy + line_intercept) / np.sqrt(line_slope ** 2 + 1)

        # Display the angle, midpoint x-coordinate, and distance to the right line on the frame
        if angle is not None:
            cv2.putText(frame, f"Angle: {angle:.2f} degrees", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        if midpoint_x is not None:
            cv2.putText(frame, f"Midpoint X: {midpoint_x}", (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        if distance_to_right_line is not None:
            cv2.putText(frame, f"Distance to Right Line: {distance_to_right_line:.2f} units", (10, 120),
                        cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

        # 파이시리얼 통신 (현장에서 angle, distance_to_right_line 변수 확인 및 튜닝 필요)
        py_serial(angle, distance_to_right_line)

        # 결과 프레임 출력
        cv2.imshow('Detected Lines', frame)

        # 'q' 키를 누르면 종료
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        # 파이 시리얼 통신

    # 웹캠 종료
    cap.release()
    cv2.destroyAllWindows()

# 웹캠으로 특정 색상 점선 및 흰색 실선 검출 및 추세선, 가장 긴 변 표시 함수 호출
detect_dotted_line()


def process_message(self, stanza):
        """Process message stanza.

        Pass it to a handler of the stanza's type and payload namespace.
        If no handler for the actual stanza type succeeds then hadlers
        for type "normal" are used.

        :Parameters:
            - `stanza`: message stanza to be handled
        """

        stanza_type = stanza.stanza_type
        if stanza_type is None:
            stanza_type = "normal"

        if self.__try_handlers(self._message_handlers, stanza,
                                                stanza_type = stanza_type):
            return True

        if stanza_type not in ("error", "normal"):
            # try 'normal' handler additionaly to the regular handler
            return self.__try_handlers(self._message_handlers, stanza,
                                                    stanza_type = "normal")
        return False


from django.shortcuts import render

# Create your views here.
def stock_exchange(request):
    stock_details= { 'stock_name1': {'SBI': '400'},
                     'stock_name2': {'PNB': '45'}}

    data = {"my_stock":stock_details}

    return render(request,"stock.html",data)


import pickle
from datetime import datetime

import numpy as np
from langchain.embeddings import AzureOpenAIEmbeddings
from langchain.chat_models import AzureChatOpenAI
import models.recommend_rest_loaction.util as util
from models.common.util import get_current_kst_time, find_top_k_similarities, get_weather_db, get_current_weather_info
from models.recommend_call_location.util import get_address_by_lat_lng, parsing_address
from models.recommend_rest_loaction.recommend_rest_template import get_template_prompt

class RecommendRestGpt:
    def __init__(self, azure_deployment="gpt-4",
                 poi_db_path="./data/poi_review_with_embedding.pkl",
                 weather_db_path="./data/weather_rapid.csv"):
        self.event_type = None
        self.chat = AzureChatOpenAI(azure_deployment=azure_deployment)
        self.embedding_model = AzureOpenAIEmbeddings(azure_deployment="text-embedding-ada-002", chunk_size=1000)

        self.weather_db = get_weather_db(weather_db_path)
        with open(poi_db_path, "rb") as f:
            self.poi_db = pickle.load(f)

        self.distance_threshold_meters_dict = {
            "quick": 3000,
            "taxi": 3000,
            "wheel": 1000
        }

        self.driver_rest_poi = {
            "식사": "가격이 싸고, 웨이팅이 없으며 음식 종류가 많고 {time}시간에 혼자 가기 좋은 식당을 추천해 줘.",
            "휴식": "사람이 많지 않고, 시끄럽지 않으면서 웨이팅이 없고 휴식하기에 좋은 장소를 추천해 줘."
        }

    def get_query_embedding(self, current_time):
        current_hour = datetime.strptime(current_time, "%Y-%m-%dT%H:00").hour
        if 12 <= current_hour <= 14:
            self.event_type = "식사"
            query = self.driver_rest_poi["식사"].format(time="점심")
        elif 18 <= current_hour <= 20:
            self.event_type = "식사"
            query = self.driver_rest_poi["식사"].format(time="저녁")
        else:
            self.event_type = "휴식"
            query = self.driver_rest_poi["휴식"]

        query_embedding = self.embedding_model.embed_query(query)

        return np.array(query_embedding)

    def get_document_embedding(self, poi_candidate):
        doc_embeddings = []
        for key, value in poi_candidate.items():
            doc_embedding = np.array(value["embedding"]).reshape(1, -1)
            doc_embeddings.append(doc_embedding)

        return np.vstack(doc_embeddings)

    def get_recommend_poi(self, top_k_indices, poi_candidate):
        def _parsing_address(poi_info: dict):
            addresses = [addr for addr in
                         [poi_info.get('hname1', ''), poi_info.get('hname2', ''), poi_info.get('hname3', '')] if
                         addr != '']
            lat_lng = f"({poi_info['coord'][0]}, {poi_info['coord'][1]})"

            return " ".join(addresses) + lat_lng

        poi_candidate_list = list(poi_candidate.items())
        recommend_poi = {}
        for index in top_k_indices:
            key, value = poi_candidate_list[index]
            new_value = {"address": _parsing_address(value)}
            for k in ["poi_name", "distance", "categories", "time_list", "reviews"]:
                new_value[k] = value[k]

            recommend_poi[key] = new_value

        return list(recommend_poi.values())

    def predict(self, driver_lat, driver_lon, driver_type="quick", current_time=None):
        if current_time is None:
            current_time = get_current_kst_time()

        # 01. api 및 db 조회로 기타 정보 획득
        raw_driver_location = get_address_by_lat_lng([driver_lat, driver_lon])[0]
        driver_location = parsing_address(raw_driver_location)
        weather_info = get_current_weather_info(self.weather_db, current_time=current_time,
                                                areaname_wide=raw_driver_location['name1'],
                                                areaname_city=raw_driver_location.get('name2'))

        # 02. 현재 기사 위치를 기반으로 근처 장소 검색
        poi_candidate = util.get_poi_by_distances(
            self.poi_db, driver_lat, driver_lon,
            distance_threshold_meters=self.distance_threshold_meters_dict[driver_type])

        # 03. 검색된 장소를 기반으로 vector search 진행
        query_embedding = self.get_query_embedding(current_time)
        doc_embeddings = self.get_document_embedding(poi_candidate)
        top_k_indices, _ = find_top_k_similarities(query_embedding, doc_embeddings, k=5)
        recommend_poi = self.get_recommend_poi(top_k_indices, poi_candidate)

        # 04. 프롬프트 생성
        prompt = get_template_prompt(
            event_type=self.event_type,
            driver_location=driver_location,
            weather_info=weather_info,
            location_info=recommend_poi
        )

        # 05. 예측 수행
        chain = prompt | self.chat
        result = chain.invoke({}).content
        return [result, recommend_poi]

        # print(result)
        #
        # coordDict = dict()
        # # ++. 근처 장소 좌표 추출
        # for e in recommend_poi:
        #
        #     print(e.get('poi_name'), e.get('address').rstrip(')').split('(')[1])
        #     coordDict[e.get('poi_nane')] = e.get('address').rstrip(')').split('(')[1]
        #
        # resultList = []
        #
        # for e in result:
        #     print(e)

        # split = result.split("|")
        # for rest in split:
        #     result_poi_name, result_recommend = rest.split("-")
        #     resultList.append([result_poi_name, result_recommend, store_map[result_poi_name]])
        # return resultList

if __name__ == "__main__":
    import dotenv
    dotenv.load_dotenv()
    recommend_rest_gpt = RecommendRestGpt(
        azure_deployment="gpt-4",
        poi_db_path="../../data/poi_review_with_embedding.pkl",
        weather_db_path="../../data/weather_rapid.csv"
    )

    resp = recommend_rest_gpt.predict(
        driver_lat=37.508811,
        driver_lon=127.040978,
        current_time="2023-11-21T18:00"
    )

    print(resp)


#!/usr/bin/env python3

from serializer import Deserializer,deserializeValidator
from tx_validator import tx_validator
from transaction import Transaction
import wallet, ecdsa, binascii

def pendingtopool(serialize):

    if deserializeValidator(serialize) == False:
        print("Not appended to pending pool")
        return False

    f = open('mempool', 'a')
    f.write(serialize + '\n')
    f.close

    f = open('mempool', 'r')
    trans = f.readlines()[-3:]
    f.close()
    return trans


from typing import List

class Solution:
    def connect(self,i,j):
        while self.dsu[i] != -1:
            i = self.dsu[i]
        while self.dsu[j] != -1:
            j = self.dsu[j]
        if i==j:
            return
        self.dsu[i] = j
    def findCircleNum(self, isConnected: List[List[int]]) -> int:
        length = len(isConnected)
        self.dsu = [-1]*length
        improve = 1
        for i in range(length):
            for j in range(improve,length):
                if isConnected[i][j]==1:
                    self.connect(i,j)
                else:
                    continue
            else:
                improve+=1
        return self.dsu.count(-1)
if __name__=='__main__':
    print(Solution().findCircleNum([[1,0,0,1],[0,1,1,0],[0,1,1,1],[1,0,1,1]]))


N1,N2,count = int(input()),int(input()),0
for i in range(N1, N2+1):
  if i > 1:
    for j in range(2, i):
        if(i % j == 0):
            break
    else:
        print(i)
        count += 1
print("primos: {}".format(count))


import os
import numpy as np
from numpy import genfromtxt

topks = []
result_dir = "results"
maps = {"short": {}, "long": {}, "twostage": {}}
for filename in os.listdir(result_dir):
    if filename.endswith(".csv") and filename.startswith("aps."):
        topks += [int(filename.split(".")[1])]

topks = sorted(topks)
maps = np.zeros((len(topks), 4))
for i, topk in enumerate(topks):
    maps[i, 0] = topk
    topk = str(topk)
    filename = "aps." + topk + ".csv"
    data = genfromtxt(os.path.join(result_dir, filename), delimiter=',')
    print(topk + " & " + " & ".join(map(str, np.round(np.mean(data[:, 1:], axis=0), 4))) + " \\\\")
    maps[i, 1:] = np.round(np.mean(data[:, 1:], axis=0), 4)

maps = np.swapaxes(maps, 0, 1)
print("top $k$ & " + " & ".join(map(str, map(int, maps[0]))) + " \\\\")
print("\\hline")
print("short & " + " & ".join(map(str, maps[1])) + " \\\\")
print("twostage & " + " & ".join(map(str, maps[2])) + " \\\\")
print("long & " + " & ".join(map(str, maps[3])) + " \\\\")

# print (topk + " & " + " & ".join(map(str, np.round(np.mean(data[:,1:],axis=0), 5))) + " \\\\")


import torch

video_path = "Video/push_up/right.mp4"
img_folder = "img/test"

write_video = False
write_box = True
write_kps = True

device = "cuda:0"
print("Using {}".format(device))

confidence = 0.05
num_classes = 80
nms_thresh = 0.33
input_size = 416

# For pose estimation
input_height = 320
input_width = 256
output_height = 80
output_width = 64

fast_inference = True
pose_batch = 80

frame_size = (720,540)

pose_backbone = "seresnet101"
pose_weight = "weights/sppe/duc_se.pth"
pose_cfg = None
pose_cls = 17

DUCs = [480, 240]

yolo_cfg = "config/yolo_cfg/yolov3.cfg"
yolo_model = 'weights/yolo/yolov3.weights'

track_idx = "all"    # If all idx, track_idx = "all"
track_plot_id = ["all"]   # If all idx, track_plot_id = ["all"]
assert track_idx == "all" or isinstance(track_idx, int)

plot_bbox = True
plot_kps = True
plot_id = True


from django.test import TestCase
from model_bakery import baker

from .models import Post

class PostModelTestCase(TestCase):
    def test_list_only_published_posts(self):
        post_published = baker.make(Post, status="published")
        baker.make(Post, status="draft", _quantity=2)
        posts = Post.published.all()
        self.assertEqual(posts.count(), 1)
        self.assertIn(post_published, posts)


# 39. Combination Sum

# Given a set of candidate numbers (candidates) (without duplicates) and a target number (target),
# find all unique combinations in candidates where the candidate numbers sums to target.
# The same repeated number may be chosen from candidates unlimited number of times.

# Note:
# All numbers (including target) will be positive integers.
# The solution set must not contain duplicate combinations.

# Example 1:
# Input: candidates = [2,3,6,7], target = 7,
# A solution set is:
# [
#   [7],
#   [2,2,3]
# ]

# Example 2:
# Input: candidates = [2,3,5], target = 8,
# A solution set is:
# [
#   [2,2,2,2],
#   [2,3,3],
#   [3,5]
# ]

class Solution:
	def combinationSum(self, candidates, target):
		"""
		:type candidates: List[int]
		:type target: int
		:rtype: List[List[int]]
		"""
		# candidates = list(set(candidates))
		candidates.sort()
		self.results = []
		self.dfs(candidates, target, 0, [])
		return self.results

	def dfs(self, candidates, target, idx, valueList):
		if target == 0:
			return self.results.append(valueList)

		for i in range(idx, len(candidates)):
			if target < candidates[i]:
				return

			self.dfs(candidates, target - candidates[i], i, valueList + [candidates[i]])

Problems Notebook/39. Combination Sum.py


# coding: UTF-8
import os
import torch
import torch.nn as nn
from script.classifier.nn_classifier import Classifier
from script.classifier.nn_classifier.text_utils import TextCnnDataset
from script.classifier.setting import DataConfig
import torch.nn.functional as F
from script.pretraining import load_emb_vec
from importlib import import_module
from script.pretraining import Vocabulary

class Config(DataConfig):
    """数据配置参数"""

    def __init__(self, **kwargs):
        DataConfig.__init__(self,
                            dataset=kwargs.get('dataset'),
                            cache_dir=kwargs.get('cache_dir'),
                            model_name=kwargs.get('model_name'),
                            adversarial=kwargs.get('adversarial'),
                            )

        if self.emb_path and os.path.exists(self.emb_path):
            init_embedding, self.word2index = load_emb_vec(self.emb_path)
            self.embedding_pretrained = torch.tensor(init_embedding.astype('float32'))
            self.embed = self.embedding_pretrained.size(1)
        else:
            self.embedding_pretrained = None
            self.embed = 300
            vocabulary = Vocabulary(train_files=[self.train_path, self.test_path, self.dev_path],
                                    emb_path=self.emb_path,
                                    vocab_path=self.vocab_path,
                                    max_vocab_size=10000)
            self.word2index = vocabulary.get_vocab()
        self.dropout = 0.5  # 随机失活
        self.require_improvement = 1000  # 若超过1000batch效果还没提升，则提前结束训练
        self.n_vocab = len(self.word2index)+1  # 词表大小，在运行时赋值
        self.num_epochs = 20  # epoch数
        self.batch_size = 128  # mini-batch大小
        self.pad_size = 32  # 每句话处理成的长度(短填长切)
        self.learning_rate = 1e-3  # 学习率
        self.filter_sizes = (2, 3, 4)  # 卷积核尺寸
        self.num_filters = 256

class Model(nn.Module):
    def __init__(self, config):
        super(Model, self).__init__()
        if config.embedding_pretrained is not None:
            self.embedding = nn.Embedding.from_pretrained(config.embedding_pretrained, freeze=False)
        else:
            self.embedding = nn.Embedding(config.n_vocab, config.embed, padding_idx=config.n_vocab - 1)
        self.convs = nn.ModuleList(
            [nn.Conv2d(1, config.num_filters, (k, config.embed)) for k in config.filter_sizes])
        self.dropout = nn.Dropout(config.dropout)
        self.fc = nn.Linear(config.num_filters * len(config.filter_sizes), config.num_classes)

    def conv_and_pool(self, x, conv):
        x = F.relu(conv(x)).squeeze(3)
        x = F.max_pool1d(x, x.size(2)).squeeze(2)
        return x

    def forward(self, x, labels=None):
        out = self.embedding(x[0])
        out = out.unsqueeze(1)
        out = torch.cat([self.conv_and_pool(out, conv) for conv in self.convs], 1)
        out = self.dropout(out)
        out = self.fc(out)

        if labels is not None:
            # loss_mask = labels.gt(-1)
            loss = F.cross_entropy(out, labels)
            return out, loss

        return out

class TextCNNClassifier(Classifier, Config):
    def __init__(self, **kwargs):
        Config.__init__(self, **kwargs)
        self.model = Model(self).to(self.device)
        self.logger.info(self.model.parameters)
        adversarial = kwargs.get('adversarial', 'base')
        at_model = import_module("script.adversarial.{}_model".format(adversarial))
        self.atModel = at_model.ATModel(self.model)
        self.modelDataset = TextCnnDataset
        self._set_optimizer()
        if kwargs.get('evaluate') and os.path.exists(self.save_model_path):
            self.model.load_state_dict(torch.load(self.save_model_path))
            self.model.eval()
            self.logger.info("load {} success".format(self.model_name))

    def _set_optimizer(self, ):
        self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.learning_rate)


#!/usr/bin/python3
import os
import sys

dummy_wsgi_framework_module_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if dummy_wsgi_framework_module_path not in sys.path:
    sys.path.append(dummy_wsgi_framework_module_path)
from dummy_wsgi_framework.core.routes import (
    get_controller_by_uri_regexp,
)
from dummy_wsgi_framework.core.exceptions import (
    ControllerFileDoesNotExist,
    ControllerFileIsInvalid,
    RouteDoesNotExist,
    ViewDoesNotExist,
    BadTermUsage,
    ExistViewFileIsInvalid
)
from dummy_wsgi_framework.core.controllers import (
    error404,
    redirect
)

def resolve_name_by_python_file_name(file_name, template_of_name='%s'):
    if file_name.endswith('.py'):
        return template_of_name % os.path.basename(file_name)[:-3]
    raise BadTermUsage('Impossible detect name by file_name "%s".' % file_name)

def get_controller_response(environ, start_response, app_config):
    uri = environ.get('REQUEST_URI')
    if not uri.endswith('/'):
        return redirect.get_response(environ, start_response, app_config, uri + '/')
    try:
        controller_file, kwargs = get_controller_by_uri_regexp(uri, app_config)
        if app_config.APP_CONTROLLERS_DIR not in sys.path:
            sys.path.insert(0, app_config.APP_CONTROLLERS_DIR)
        controller_module = __import__(
            resolve_name_by_python_file_name(controller_file)
        )
        if not hasattr(controller_module, 'get_response'):
            raise ControllerFileIsInvalid(
                'Controller method "get_response" is not declared '
                'in controller-file "%s" of application "%s"' % (controller_file, app_config.APP_NAME))
        return controller_module.get_response(environ, start_response, app_config, **kwargs)
    except RouteDoesNotExist:
        return error404.get_response(
            environ, start_response, app_config,
            message='RouteDoesNotExist: %s' % sys.exc_info()[1]
        )
    except ControllerFileDoesNotExist:
        return error404.get_response(
            environ, start_response, app_config,
            message='ControllerFileDoesNotExist: %s' % sys.exc_info()[1]
        )
    except ViewDoesNotExist:
        return error404.get_response(
            environ, start_response, app_config,
            message='ViewDoesNotExist: %s' % sys.exc_info()[1]
        )
    except BadTermUsage:
        return error404.get_response(
            environ, start_response, app_config,
            message='BadTermUsage: %s' % sys.exc_info()[1]
        )
    except ControllerFileIsInvalid:
        return error404.get_response(
            environ, start_response, app_config,
            message='ControllerFileIsInvalid: %s' % sys.exc_info()[1]
        )
    except ExistViewFileIsInvalid:
        return error404.get_response(
            environ, start_response, app_config,
            message='ExistViewFileIsInvalid: %s' % sys.exc_info()[1]
        )
    except:
        raise

def get_view_response(environ, start_response, app_config, view_file_name, **kwargs):
    if environ or kwargs:
        pass  # Lets ignore PyCharm warning about not usage
    try:
        view_path = os.path.join(app_config.APP_VIEWS_DIR, view_file_name)
        with open(view_path, 'rb') as f:
            response_body = f.read()
        start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
        return [response_body]
    except FileNotFoundError:
        raise ViewDoesNotExist(
            'Declared view-file "%s" '
            'of application "%s" does not found in directory "%s".' % (
                view_file_name, app_config.APP_NAME, app_config.APP_VIEWS_DIR
            )
        )

def decorate_loaded_view_function_for_response(decorated_load_view_function):
    def load_view_response(environ, start_response, app_config, view_file_name, **kwargs):
        if environ or kwargs:
            pass  # Lets ignore PyCharm warning about not usage
        try:
            view_path = os.path.join(app_config.APP_VIEWS_DIR, view_file_name)
            response_body = decorated_load_view_function(view_path, **kwargs)
            start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
            return [response_body]
        except FileNotFoundError:
            raise ViewDoesNotExist(
                'Declared view-file "%s" '
                'of application "%s" does not found in directory "%s".' % (
                    view_file_name, app_config.APP_NAME, app_config.APP_VIEWS_DIR
                )
            )

    return load_view_response

@decorate_loaded_view_function_for_response
def load_view(view_path, **kwargs):
    if kwargs:
        pass  # Lets ignore PyCharm warning about not usage
    with open(view_path, 'rb') as f:
        return f.read()


def solution(numbers, hand):
    answer = []
    leftHand = '*'
    rightHand = '#'
    left = [1, 4, 7, '*']
    right = [3, 6, 9, '#']
    center = [2, 5, 8, 0]
    for i in range(len(numbers)):
        if numbers[i] in left:
            answer.append('L')
            leftHand = numbers[i]
            continue
        if numbers[i] in right:
            answer.append('R')
            rightHand = numbers[i]
            continue
        else:
            if leftHand not in center:
                leftR = center.index(numbers[i]) - left.index(leftHand)
                if leftR < 0:
                    leftR = -leftR
                leftR += 1
            else:
                leftR = center.index(numbers[i]) - center.index(leftHand)
                if leftR < 0:
                    leftR = -leftR
            if rightHand not in center:
                rightR = center.index(numbers[i]) - right.index(rightHand)
                if rightR < 0:
                    rightR = -rightR
                rightR += 1
            else:
                rightR = center.index(numbers[i]) - center.index(rightHand)
                if rightR < 0:
                    rightR = -rightR

            if leftR > rightR:
                answer.append('R')
                rightHand = numbers[i]
                continue
            if leftR < rightR:
                answer.append('L')
                leftHand = numbers[i]
                continue
            else:
                if hand == 'right':
                    answer.append('R')
                    rightHand = numbers[i]
                    continue
                else:
                    answer.append('L')
                    leftHand = numbers[i]
                    continue
    result = ''.join(answer)
    return result

프로그래머스/1단계/키패드 누르기.py


#!/home/namphuong/Code/news-search-engine/myvenv/bin/python
import logging
import sys
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import crawlers
from crawler.newschannels import NewsChannels

class USATodayCrawler:

    def __init__(self, selected_date):
        self.selected_date = selected_date

    def get_link_articles(self):
        aritcle_url_list = []
        page_url_list = []
        targeted_url = self.generate_targeted_url(self.selected_date)
        html = requests.get(targeted_url)
        html.encoding = 'utf-8'
        sp = BeautifulSoup(html.text, 'lxml')
        pagination = sp.find(
            'ul', {'class': 'sitemap-list sitemap-pagination'})

        for page in pagination.find_all('li', {'class': 'sitemap-list-item'}):
            page_url_list.append(page.find('a').get('href'))

        # get article url in page 1
        aritcle_url_list.extend(self.get_link_article_pagination(None, sp))
        # get article url from page 2
        for i in range(1, len(page_url_list)):
            aritcle_url_list.extend(self.get_link_article_pagination(
                page_url_list[i], None))

        return aritcle_url_list

    def get_link_article_pagination(self, page_url=None, soup=None):
        artile_url_list = []
        if (soup == None):
            html = requests.get(page_url)
            html.encoding = 'utf-8'
            soup = BeautifulSoup(html.text, 'lxml')
        main_content = soup.find('div', {'class': 'sitemap-column-wrapper'})
        article_list = main_content.find('ul', {'class': 'sitemap-list'})
        for article_element in article_list.find_all('li'):
            artile_url_list.append(article_element.find('a').get('href'))

        return artile_url_list

    @staticmethod
    def generate_targeted_url(selected_date, page=None):
        year = selected_date.split('-')[0]
        month_num = selected_date.split('-')[1]
        # Mapping month number to full month name in lowercase(Eg: 09 -> september)
        month_name = datetime(1, int(month_num), 1).strftime("%B")
        # Convert number in string to short style (Eg: 01 to 1)
        day = int(selected_date.split('-')[2])
        if (page == None):
            page = 1
        return "https://www.usatoday.com/sitemap/{}/{}/{}/?page={}".format(year, month_name, day, page)

if __name__ == '__main__':
    selected_date = sys.argv[1]
    selected_date_obj = datetime.strptime(selected_date, '%Y-%m-%d')
    if (selected_date_obj <= datetime.today()):
        usa_today_crawler = USATodayCrawler(selected_date)
        url_list = usa_today_crawler.get_link_articles()
        print(len(url_list))
        crawlers.crawl_articles(url_list, NewsChannels.USATODAY.value, selected_date)
    else:
        logging.error("Selected date is invalid")


import numpy as np

def fdiff_lat_1d(x,lat):
    # One dimensional meridional gradient
    # x: 1d data
    # lat: latitude

    dx = x * 0
    dx[1:-1] = (x[2:]-x[0:-2]) / ((lat[2:]-lat[0:-2])*np.pi/180.0)
    dx[0]    = (x[1]-x[0])     / ((lat[1]-lat[0])*np.pi/180.0)
    dx[-1]   = (x[-1]-x[-2])   / ((lat[-1]-lat[-2])*np.pi/180.0)
    return dx

def fdiff_lon_1d(x,lon):
    # One dimensional zonal gradient
    # x: 1d data
    # lon: longitude

    dx = x * 0
    dx[1:-1] = (x[2:]-x[0:-2]) / ((lon[2:]-lon[0:-2])*np.pi/180.0)
    dx[0]    = (x[1]-x[0])     / ((lon[1]-lon[0]+360)*np.pi/180.0)
    dx[-1]   = (x[-1]-x[-2])   / ((lon[-1]-lon[-2]+360)*np.pi/180.0)
    return dx

def fdiff_lat(x,lat2d):
    # Two dimensional meridional gradient
    # x: 2d data
    # lat2d: 2d latitude
    dx = x * 0
    dx[1:-1,:] = (x[2:,:] - x[0:-2,:]) / ((lat2d[2:,:] - lat2d[0:-2,:]) * np.pi/180.0)
    dx[0,:]    = (x[1,:]  - x[0,:])    / ((lat2d[1,:]  - lat2d[0,:]) * np.pi/180.0)
    dx[-1,:]   = (x[-1,:] - x[-2,:])   / ((lat2d[-1,:] - lat2d[-2,:]) * np.pi/180.0)
    return dx

def fdiff_lon(x,lon2d):
    # Two dimensional zonal gradient
    # x: 2d data
    # lon2d: 2d longitude

    dx = x * 0
    dx[:,1:-1] = (x[:,2:] - x[:,0:-2]) / ((lon2d[:,2:] - lon2d[:,0:-2]) * np.pi/180.0)
    dx[:,0]    = (x[:,1]  - x[:,-1])   / ((lon2d[:,1]  - lon2d[:,-1] + 360) * np.pi/180.0)
    dx[:,-1]   = (x[:,0]  - x[:,-2])   / ((lon2d[:,0]  - lon2d[:,-2] + 360) * np.pi/180.0)
    return dx

def fuvtodiv(u,v,lon,lat):
    # Calculate the divergence div (1/s), given zonal wind u (m/s) and meridional wind v (m/s)
    # lon: 1d longitude
    # lat: 1d latitude

    nlon = np.size(lon)
    nlat = np.size(lat)
    a = 6371000.0       # Earth's radius (m)
    lat2d  = u * 0
    lon2d  = u * 0
    clat2d = u * 0      # cosine(latitude)
    for ilat in range(nlat):
        lat2d[ilat,:]  = lat[ilat]
        lon2d[ilat,:]  = lon + 0
        clat2d[ilat,:] = np.cos(np.pi*lat[ilat]/180.0)

    divlon = fdiff_lon(u,lon2d)/a/clat2d
    divlat = fdiff_lat(v*clat2d,lat2d)/a/clat2d
    div = divlon + divlat
    return div

def fzonalsmooth(x):
    # 3-point zonal smoothing on x
    z = x * 0
    z[:,1:-1] = 0.5*x[:,1:-1] + 0.25*(x[:,:-2]+x[:,2:])
    z[:,0] = 0.5*x[:,0] + 0.25*(x[:,1]+x[:,-1])
    z[:,-1] = 0.5*x[:,-1] + 0.25*(x[:,-2]+x[:,0])
    return z

def fLN87(ts, lon, lat, h0=3000, tau=30*60, ntrun=15, eps=1/(2.5*86400)):
    # linear wind balanced model, based on Lindzen and Nigam, 1987

    # -------------------  input arguments  ---------------------
    #   ts:  2d surface virsual temperture      [K]
    #   lon: 1d longitude
    #   lat: 1d latitude
    #   h0: mean top of boundary layer          [m]
    #   tau: convection adjustment time scale   [s]
    #   ntrun: truncated zonal wavenumber
    #   eps: drag coefficient                   [1/s]

    # -------------------  output arguments  ---------------------
    #   ug: eddy zonal wind             (m/s)
    #   vg: eddy meridional wind        (m/s)
    #   hg: back-pressure field         (m)
    #   psg: eddy sea-level pressure    (Pa)

    # prevent cosine(latitude) reaching zero
    if (abs(lat[0]) - 90 < 0.01):
        lat[0] = 0.5*(lat[0] + lat[1])
    if (abs(lat[-1]) - 90 < 0.01):
        lat[-1] = 0.5*(lat[-1] + lat[-2])

    nlon = np.size(lon)
    nlat = np.size(lat)
    ntrun = min(ntrun,nlon/2)

    T0 = 288.0      # reference temperature: K
    rou0 = 1.225    # reference densisty: kg/m3
    alpha = 0.003   # vertical lapse rate of mean temperature: K/m
    gama  = 0.3     # vertical lapse rate of perturbation temperature
    omg = 7.272e-5  # Earth rotation angular velocity (1/s)
    a = 6371000.0   # Earth radius (m)
    g = 9.8         # gravitation (m/s2)
    n = 1.0 / T0
    B = g*n*h0*(1.0 - 2.0*gama/3.0)/(2.0*a)

    # specific zonal wavenumbers to match the FFT
    #   Indexes ------ [0,1,2, ..., nlon/2-1,  nlon/2,    nlon/2+1, ..., nlon-2, nlon-1]
    #   Wavenumbers -- [0,1,2, ..., nlon/2-1, -nlon/2, -(nlon/2-1), ...,     -2,     -1]
    m = np.linspace(0,nlon-1,nlon)
    m[nlon/2:nlon] = -1 * np.linspace(1,nlon/2,nlon/2)[::-1]

    clat  = np.cos(np.pi*lat/180.0)         # cosine(latitude)
    flat  = 2*omg*np.sin(np.pi*lat/180.0)   # Coriolis parameter (1/s)
    tsm   = np.mean(ts,axis=1)              # zonal mean temperature (K)
    dtsmdlat = fdiff_lat_1d(tsm,lat)        # meridional gradient of zonal mean temperature (K/m)
    Alat = g*(2.0 - n*tsm + n*alpha*h0) / a

    lat2d  = ts * 0
    lon2d  = ts * 0
    clat2d = ts * 0
    tsm2d  = ts * 0
    A2d    = ts * 0

    for ilat in range(nlat):
        lat2d[ilat,:]  = lat[ilat]
        lon2d[ilat,:]  = lon + 0
        clat2d[ilat,:] = np.cos(np.pi*lat[ilat]/180.0)
        tsm2d[ilat,:]  = np.mean(ts[ilat,:])
        A2d[ilat,:]    = g*(2.0 - n*tsm2d[ilat,:] + n*alpha*h0) / a

    tsp      = ts - tsm2d   # temperature perturbation from zonal mean (K)
    dtsdlon  = fdiff_lon(tsp,lon2d) # zonal gradient of temperature perturbation (K/m)
    dtsdlat  = fdiff_lat(tsp,lat2d) # meridional gradient of temperature perturbation (K/m)

    Flon = np.fft.fft(B*dtsdlon/clat2d,axis=1)  # forcing term 1 (in spectral space)
    Flat = np.fft.fft(B*dtsdlat,axis=1)         # forcing term 2 (in spectral space)

    # rearrange the matrix and vectors, and solve the algebra equations
    ug = 0.0 * ts
    vg = 0.0 * ts
    hg = 0.0 * ts
    psg = 0.0 * ts
    us = (0 + 0j) * ts
    vs = (0 + 0j) * ts
    hs = (0 + 0j) * ts

    x0 = np.zeros([3*nlat,3*nlat]) + (0+0j)
    y0 = np.zeros([3*nlat]) + (0+0j)
    x0[0,0] = 1
    y0[0]   = 0
    x0[nlat-1,nlat-1] = 1
    y0[nlat-1]        = 0
    x0[nlat,nlat] = 1
    y0[nlat]      = 0
    x0[2*nlat-1,2*nlat-1] = 1
    y0[2*nlat-1]          = 0
    x0[2*nlat,2*nlat] = 1
    y0[2*nlat]        = 0
    x0[3*nlat-1,3*nlat-1] = 1
    y0[3*nlat-1]          = 0

    # Specify the coefficients in the 3*3 block matrix, except for the dependent values on wavenumber m

    for ilat in range(1,nlat-1):
        # the first row, except for the coefficients of h
        i = ilat
        x0[i,i] = eps
        x0[i,i+nlat] = -flat[ilat]

    for ilat in range(1,nlat-1):
        # the second row
        i = ilat + nlat
        x0[i,i-nlat] = flat[ilat]
        x0[i,i] = eps
        x0[i,i+nlat-1] = -Alat[ilat]/((lat[ilat+1]-lat[ilat-1]) * np.pi/180.0)
        x0[i,i+nlat]   = -0.5*g*n* dtsmdlat[ilat] / a
        x0[i,i+nlat+1] =  Alat[ilat]/((lat[ilat+1]-lat[ilat-1]) * np.pi/180.0)

    for ilat in range(1,nlat-1):
        # the third row, except for the coefficient of u
        i = ilat + 2*nlat
        x0[i,i-nlat-1] = -clat[ilat-1]/((lat[ilat+1]-lat[ilat-1]) * np.pi/180.0)
        x0[i,i-nlat+1] =  clat[ilat+1]/((lat[ilat+1]-lat[ilat-1]) * np.pi/180.0)
        x0[i,i] = a*clat[ilat]/(tau*h0)
        y0[i] = 0 + 0j

    # solve the algebra equation on truncated range of wavenumber: [-M,M] without m=0
    for im in range(1,ntrun+1) + range(nlon-ntrun,nlon):
        x = x0 + 0
        y = y0 + 0

        for ilat in range(1,nlat-1):
            # the coefficients that depends on wavenumber m (zonal gradient terms)
            x[ilat,ilat+2*nlat] = 1.0j * m[im] * Alat[ilat]/clat[ilat]
            x[ilat+2*nlat,ilat] = 1.0j * m[im]

        # forcing terms
        y[1:nlat-1] = Flon[1:nlat-1,im] + 0
        y[nlat+1:2*nlat-1] = Flat[1:nlat-1,im] + 0

        # solve the algebra equations
        temp = np.linalg.solve(x,y)

        # u,v,h in spectral space
        us[:,im] = temp[0:nlat] + 0
        vs[:,im] = temp[nlat:2*nlat] + 0
        hs[:,im] = temp[2*nlat:3*nlat] + 0

    # get the values on grid points (physical space)
    for ilat in range(nlat):
        ug[ilat,:] = np.fft.ifft(us[ilat,:]).real
        vg[ilat,:] = np.fft.ifft(vs[ilat,:]).real
        hg[ilat,:] = np.fft.ifft(hs[ilat,:]).real
        psg[ilat,:] = g*rou0*n*h0*(gama/2.0 - 1)*tsp[ilat,:] + g*rou0*(2 - n*tsm[ilat] + n*alpha*h0)*hg[ilat,:]

    return  ug,vg,hg,psg


import json
textData = []
splitTextData = str()
filename = "no_punctuationText"
with open("tweets.json",encoding="UTF-8") as f:
    data = json.load(f)

for i in range(len(data)):
    textData.append(data[i]["text"])
# print(textData)
for i in textData:
    a = i.split()
    for j in a:
        splitTextData += j + " "
# print(splitTextData)

punc = '''!()-[]{};:"'\,<>./?@#$%^&*_~'''
no_punct = ""
for char in splitTextData:
    if char not in punc:
        no_punct += char
f = open(filename, "r+", encoding="UTF-8")

f.write(no_punct)

def readFile(f):
    fileObj = open(f, "r", encoding="UTF-8")
    w = fileObj.read().splitlines()  # puts the file into an array
    fileObj.close()
    return w

newarray = readFile(filename)
splitarr = []
words = {}

for i in newarray:
    a = i.split()
    for j in a:
        if j != "RT":
            splitarr.append(j)

uniquewords = set(splitarr)
for i in uniquewords:
    words[i] = splitarr.count(i)

sort_order = sorted(words.items(), key=lambda x:x[1], reverse=True)
# print(sort_order)
result = []
for i in sort_order:
    a = str(i[0]) + " = " + str(i[1])
    result.append(a)
#print(result)

for i in range(10):
    print(result[i])

# f.truncate(0) #remore everything
f.close()


"""Consider a shop UMKC with dictionary of all book items with their prices.
Write a program to find the books from the dictionary in the range given by user.
Sample Input: {“python”:50,”web”:3   0,”c”:20,”java”:40}
For range 30 to 40
Sample Output: You can purchase books (web, java) """

    # start Entering the price range Min and Max
print('Enter price range to find the books list ')
    #enter Min
price_Min=input('Min : ')
    #enter max
price_Max=input('Max : ')
    #the books are the keys and the price is the values in this dictionary.
Books_List = { "Introduction to Computing": 120, "Introduction Python": 95, "Introduction C++": 100}
    # the loop for to check the conditions to apply.
for key in Books_List:

    # the condition to make sure the entered values are >= Min and <= Max
    if Books_List[key] >= int(price_Min) and Books_List[key] <= int(price_Max):
        print(str(key) +' Book,  is within the range you entered, its price is $' + str(Books_List[key]))
        # print the books name and it price that are within our range


def auth_in_stage2(self,stanza):
        """Handle the second stage (<iq type='set'/>) of legacy ("plain" or
        "digest") authentication.

        [server only]"""
        self.lock.acquire()
        try:
            if "plain" not in self.auth_methods and "digest" not in self.auth_methods:
                iq=stanza.make_error_response("not-allowed")
                self.send(iq)
                return

            username=stanza.xpath_eval("a:query/a:username",{"a":"jabber:iq:auth"})
            if username:
                username=from_utf8(username[0].getContent())
            resource=stanza.xpath_eval("a:query/a:resource",{"a":"jabber:iq:auth"})
            if resource:
                resource=from_utf8(resource[0].getContent())
            if not username or not resource:
                self.__logger.debug("No username or resource found in auth request")
                iq=stanza.make_error_response("bad-request")
                self.send(iq)
                return

            if stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"}):
                if "plain" not in self.auth_methods:
                    iq=stanza.make_error_response("not-allowed")
                    self.send(iq)
                    return
                else:
                    return self._plain_auth_in_stage2(username,resource,stanza)
            if stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}):
                if "plain" not in self.auth_methods:
                    iq=stanza.make_error_response("not-allowed")
                    self.send(iq)
                    return
                else:
                    return self._digest_auth_in_stage2(username,resource,stanza)
        finally:
            self.lock.release()


class ClassVar: # 자료형을 구성할때 필드, 생성자 메서드는 필수 구성요소가 아니다.
    text_list = []   # 클래스 멤버
    # * java 에서 static 으로 선언된 변수는 참조변수 선언에 의해 메모리 할당이 되는 것이 아니라 만나자마자 메모리에 할당된다. class 이름으로 접근할 수 있다.
    # 이러한 것을 class 변수라고 불렀다
    # python 에서는 이러한 형태를 만나면 먼저 메모리에 할당한다. java의 static과 똑같은 동작.

    def add(self, text):  # 인스턴스 멤버
        self.text_list.append(text)

    def print_list(self):
        print(self.text_list) # 미리 정의 되어 있기 때문에 얼마든지 꺼내 쓸 수 있다.

if __name__ == '__main__':
    a = ClassVar()
    a.add('a')
    a.print_list() # ['a']

    b = ClassVar()
    b.add('b')
    b.print_list() # ['a', 'b']  변수를 공유한다.