class node(object):    #创建哈夫曼树结点类
    def __init__(self):
        self.name = None
        self.weight = None
        self.leftchild = None
        self.rightchild = None
        self.parent = None

class code_node(object):     #创建编码结点类
    def __init__(self, code, name, weight):
        self.code = code
        self.name = name
        self.weight = weight

# 哈夫曼类: HuffmanTree,
# 类内主要成员有：
# text: 本次压缩处理的文本，多行字符串，由外部text变量传过来。
# code_dict: 编码字典，key是字符，value是编码。
# final_01data: 编码后的文章列表， 每段的压缩码(01字符串)依次存放在列表里。
# final_byte: 压缩码转换成字节数据的文章列表，每段的字节数据依次存放在列表里
# decode_01data： 字节数据转换成的待解码的01串列表，与原压缩码相同，每段的待解码01串依次存放在列表里
# 类内主要方法有：
# buildtree: 建哈夫曼树
# make_code: 对字符编码（不含"\n"）
# compress & print_compress: 压缩文本，保存压缩码（01串）到final_01data
# data_to_byte: 压缩码经处理转换成字节数据，保存到final_byte
# byte_to_data: 字节数据转换成去处理的待解压码，保存到decode_01data
# data_to_text: 解压01串，返回分段后的文章列表

class HuffmanTree(object):    #哈夫曼树类
    def __init__(self):
        self.root = node()

    def buildtree(self, name_set, weight_set):    #创建哈夫曼树
        self.nodes = []                   #以降序存储新结点
        while len(name_set) > 0:
            max_weight = max(weight_set)
            max_pos = weight_set.index(max_weight)
            max_name = name_set[max_pos]
            newnode = node()
            newnode.name = max_name
            newnode.weight = int(max_weight)   #权值为整型
            self.nodes.append(newnode)
            name_set.remove(max_name)
            weight_set.remove(max_weight)    #创建新结点，填入name和weight属性，且按降序入列
        self.nodes_copy = self.nodes[:]
        #备份self.nodes，用于自底向上编码，不能使用self.nodes_copy = self.nodes，这会导致两者始终同步
        while len(self.nodes) > 2:
            l = self.nodes.pop()
            r = self.nodes.pop()
            newnode = node()
            newnode.weight = l.weight + r.weight
            newnode.leftchild = l
            newnode.rightchild = r
            l.parent = newnode
            r.parent = newnode
            self.insert(newnode)    #将新结点根据weight大小插入self.nodes
        left = self.nodes.pop()
        right = self.nodes.pop()
        self.root.weight = left.weight + right.weight
        self.root.leftchild = left
        self.root.rightchild = right
        left.parent = self.root
        right.parent = self.root   #列表中最后两个结点连接Haffuman树的根节点

    def insert(self, newnode):
        for i in range(len(self.nodes)):
            if self.nodes[i].weight < newnode.weight:
                self.nodes.insert(i, newnode)
                return
        self.nodes.append(newnode)

    def make_code(self):  # 对不同字符编码，编码字典存在code_dict
        codes = []
        while len(self.nodes_copy) > 0:
            code = ''
            precode_node = self.nodes_copy.pop()
            t = precode_node
            while t.parent != self.root:  # 自底向上编码
                p = t.parent
                if t == p.leftchild:
                    code = '0' + code
                elif t == p.rightchild:
                    code = '1' + code
                t = t.parent
            if t == self.root.leftchild:
                code = '0' + code
            elif t == self.root.rightchild:
                code = '1' + code
            codes.append(code_node(code, precode_node.name, precode_node.weight))  # 编码结点存入编码库self.nodes
        self.code_dict = {}
        for i in range(len(codes)):
            self.code_dict[codes[i].name] = codes[i].code
        print("编码表：")
        print(self.code_dict)

    def data_preprocessing(self, text):  # 文本预处理，统计文本内字符及频率（不含"\n"）
        self.text = text
        self.data = list(self.text)  # 数据转列表，单个字符存储
        dict = {}
        for i in set(self.data):
            dict[i] = self.data.count(i)
        dict.pop('\n')
        self.base_name = []
        self.base_num = []
        for i in dict.keys():
            self.base_name.append(i)
            self.base_num.append(dict[i])

    def data_make_code(self):  # 制作编码并输出编码表
        self.buildtree(self.base_name, self.base_num)
        self.make_code()

    def compress(self):  # 压缩
        self.compress_data_part = []
        compress_data = []
        self.text_part = self.text.split('\n')
        self.data_part = []
        for i in range(len(self.text_part)):
            self.data_part.append(list(self.text_part[i]))
        for i in range(len(self.data_part)):
            for j in range(len(self.data_part[i])):
                compress_data.append(self.code_dict[self.data_part[i][j]])
            cpd_copy = compress_data[:]
            self.compress_data_part.append(cpd_copy)
            compress_data.clear()

    def print_compress(self):  # 输出压缩码，分段存入final_01data
        print("分段后压缩码为：")
        self.final_01data = []
        for i in range(len(self.compress_data_part)):
            p = ''.join(self.compress_data_part[i])
            self.final_01data.append(p)
        print(self.final_01data)

    def pad_encoded_text(self, encoded_text):  # 对压缩码进行预处理，尾部补齐8的倍数，头部加信息头表示尾部补了多少0
        extra_padding = 8 - len(encoded_text) % 8
        for i in range(extra_padding):
            encoded_text += "0"
        padded_info = "{0:08b}".format(extra_padding)
        encoded_text = padded_info + encoded_text
        return encoded_text

    def get_byte_array(self, padded_encoded_text):  # 01串转byte
        if (len(padded_encoded_text) % 8 != 0):
            print("Encoded text not padded properly")
            exit(0)
        b = bytearray()
        for i in range(0, len(padded_encoded_text), 8):
            byte = padded_encoded_text[i:i + 8]
            b.append(int(byte, 2))
        return b

    def data_to_byte(self):  # 生成压缩完成且转码的分段的字节数据，存入final_byte列表
        self.final_byte = []
        for i in range(len(self.final_01data)):
            b = self.get_byte_array(self.pad_encoded_text(self.final_01data[i]))
            self.final_byte.append(b)
        print(self.final_byte)

    def byte_to_data(self):  # 转码的字节数据转换成待解码的01串，并且去掉预处理补加的字符串，分段存入decode_01data
        self.decode_01data = []
        for i in range(len(self.final_byte)):
            bb0 = self.final_byte[i]
            num = bb0[0]
            bb = bb0[1:]
            str0 = str(bin(int(bb.hex(), 16))[2:])
            if len(str0) % 8 != 0:
                extra0 = 8 - len(str0) % 8
                for j in range(extra0):
                    str0 = '0' + str0
            str1 = str0[0: len(str0) - num]
            self.decode_01data.append(str1)
        print(self.decode_01data)

    def cmp_ok(self, a, b):   #从头比较，判断b是否为a的子字符串
        l = len(b)
        k = 0
        if len(a) < len(b):
            return False
        while k < l:
            if a[k] == b[k]:
                k += 1
            else:
                return False
        return True

    def data_to_text(self):  # 解压，01串转换成文本，分段存入result列表并返回
        result = []
        for i in range(len(self.decode_01data)):
            result_part = ""
            uncompress_code = self.decode_01data[i]
            while len(uncompress_code) > 0:
                for j in self.code_dict:
                    if self.cmp_ok(uncompress_code, self.code_dict[j]) == True:
                        h = len(self.code_dict[j])
                        uncompress_code = uncompress_code[h:]
                        result_part += j
            result.append(result_part)
        return result

text = """The Tokyo 2020 Olympics torch lighting ceremony in ancient Olympia will be the first in more than 35 years to be held without spectators after organizers on Monday introduced tighter measures to protect against the coronavirus.
Greece's Olympic Committee said spectators would be excluded from both the dress rehearsal at the ancient site on Wednesday and the widely broadcast ceremony on Thursday.
This is the first time since the 1984 Los Angeles Olympics that the ceremony will be held without any spectators lounging on the grassy slopes of the ancient stadium in the tiny Peloponesian hamlet. The ceremony — held both for summer and winter Games — usually attracts several thousand spectators, including Greeks and foreign visitors.
"The lighting ceremony of the Olympic flame will be done without the presence of spectators and only 100 invited and accredited guests," the Greek Olympic Committee said in a statement.
"The dress rehearsal on March 11 will be closed to spectators and media."
The Olympic torch will be lit in Olympia at a scaled-down ceremony on March 12 before a seven-day relay that culminates with a handover ceremony in Greece on March 19.
The number of people inside the ancient stadium will also be reduced with only a few dozen representatives of the Tokyo Games from a group of about 150 allowed access to the ceremony.
Organizers will also shut the press center following the ceremony to avoid the gathering of many people in an indoor area and will stage Wednesday's dress rehearsal without the presence of media. Tokyo had already stopped 340 children from attending.
Greece on Sunday announced a two-week ban on sporting events with spectators and on school field trips, as its number of coronavirus cases rose by seven to 73. The prefecture of Ilia, of which Olympia is part, is among areas of the country hardest hit by the coronavirus.
The Mayor of Olympia has written to International Olympic Committee President Thomas Bach, proposing the postponement of the ceremony until May.
"The danger of staging the torch lighting with only a handful of spectators, limited number of officials and delegations, and under a cloud of fear and concern will damage the greatness and prestige of this event," Olympia mayor Giorgos Georgiopoulos said in his letter."""

if __name__ == '__main__':

    htree = HuffmanTree()  #创建Huffman空树
    #压缩
    htree.data_preprocessing(text)   #输入序列信息并预处理
    htree.data_make_code()   #制作编码并输出编码表
    htree.compress()    #压缩
    htree.print_compress()   #输出分好段的压缩码，按顺序存在列表里
    htree.data_to_byte()     #压缩码分段转换成字节数据
    #解压
    htree.byte_to_data()    #字节数据分段转换成待解压码
    text_part = htree.data_to_text()    #保存经分段解压后的文章列表到text_part
    #输出解压后的文本
    final_text = ""
    for i in range(len(text_part)):
        final_text += text_part[i]
        final_text += "\n"
    print(final_text)
    #分段验证解压后的文章与原文是否一致
    origin_text = text.split("\n")
    for i in range(len(origin_text)):
        if origin_text[i] == text_part[i]:
            print("same")
        else:
            print("no")


#Bibliotecas importadas
import cv2
import numpy as np

#Función de convolución
def convolucion(IOriginal, Kernel):
    #Variables:
    fr = len(IOriginal) - (len(Kernel) - 1)           #Número de filas de la matriz resultante
    cr = len(IOriginal[0]) - (len(Kernel[0]) - 1)     #Número de columnas de la matriz resultante
    Res = np.zeros((fr, cr), np.uint8)                          #Matriz resultante

    #For para recorrer las filas
    for i in range(len(Res)):
        #For para recorrer las columnas
        for j in range(len(Res[0])):
            suma = 0  #Resultado de la multiplicación de la imagen con el Kernel
            #For para recorrer las filas del Kernel
            for m in range(len(Kernel)):
                #For para recorrer las columnas del Kernel
                for n in range(len(Kernel[0])):
                    suma += Kernel[m][n] * IOriginal[m + i][n + j] #Multiplicación de matrices
            if suma <= 255:
                Res[i][j] = round(suma) #Sustituyendo el valor de la multiplicación en su celda correspondiente
            else:
                Res[i][j] = 255
    return Res #Se regresa la matriz resultante

#Probando la función
#Variables
K = [[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]                                                   #Kernel
I = [[2, 0, 1, 1, 1], [3, 0, 0, 0, 2], [1, 1, 1, 1, 1], [3, 1, 1, 1, 2], [1, 1, 1, 1, 1]]   #Imágen
In = np.array(I)  #Array de la imagen en numpy
Kn = np.array(K)  #Array del Kernel en numpy

#Pipeline
IRGB = cv2.imread('004.jpg')                     #Imágen real
IGS = cv2.cvtColor(IRGB, cv2.COLOR_BGR2GRAY)     #Convirtiendo la imagen a escala de grises
print(IGS.shape) #Imprimiendo las dimensiones de la imagen antes de la convolución

#Realizndo la convolución
R = convolucion(IGS, Kn) #Se hace la matriz resultante mandando a llamar la función de convolución
print(R)   #Se imprime la matriz resultante de la convolución
print(R.shape) #Imprimiendo dimensiones de la imagen después de la convolución

#Guardando la impagen
cv2.imwrite('004C.jpg', R)


from pathlib import Path
from unittest.mock import patch, call

import pytest

from pdoc import pdoc
from pdoc.__main__ import cli

here = Path(__file__).parent

def test_cli(tmp_path):
    cli([str(here / "testdata" / "demo_long.py"), "-o", str(tmp_path)])
    assert (tmp_path / "demo_long.html").read_text().startswith("<!doctype html>")
    assert (tmp_path / "index.html").read_text().startswith("<!doctype html>")

def test_cli_version(capsys):
    cli(["--version"])
    assert "pdoc:" in capsys.readouterr().out

def test_cli_web(monkeypatch):
    with patch("pdoc.web.open_browser") as open_browser:
        with patch(
            "pdoc.web.DocServer.serve_forever", side_effect=KeyboardInterrupt
        ) as serve_forever:
            cli([str(here / "testdata" / "demopackage" / "_child_d.py")])
            assert open_browser.call_args == call(
                "http://localhost:8080/demopackage/_child_d.html"
            )
            assert serve_forever.call_args == call()
            cli([])

def test_api(tmp_path):
    assert pdoc(here / "testdata" / "demo_long.py").startswith("<!doctype html>")
    with pytest.raises(ValueError, match="Invalid rendering format"):
        assert pdoc(here / "testdata" / "demo_long.py", format="invalid")
    with pytest.raises(ValueError, match="Module not found"):
        with pytest.warns(RuntimeWarning, match="Cannot find spec"):
            assert pdoc(
                here / "notfound.py",
            )

    # temporarily insert syntax error - we don't leave it permanently to not confuse mypy, flake8 and black.
    (here / "syntax_err" / "syntax_err.py").write_bytes(b"class")
    with pytest.warns(
        RuntimeWarning, match="Error importing test.syntax_err.syntax_err"
    ):
        pdoc(here / "syntax_err", output_directory=tmp_path)
    (here / "syntax_err" / "syntax_err.py").write_bytes(
        b"# syntax error will be inserted by test here\n"
    )


# 309 ms, faster than 31.60%
# 13.9 MB, less than 65.84%
class Solution:
    def maxLength(self, arr: List[str]) -> int:
        return self.helper(arr, "")
    def helper(self, arr, sub_seq):
        if len(arr) == 0:
            return len(sub_seq)
        res = len(sub_seq)
        for i in range(len(arr)):
            word = arr[i]
            if self.comp(word, sub_seq):
                sub_seq += word
                part_res = self.helper(arr[i+1:], sub_seq)
                sub_seq = sub_seq[0:len(sub_seq)-len(word)]
                if part_res > res:
                    res = part_res
        return res
    def comp(self, word1, word2):
        if len(set(word1).union(set(word2))) == len(word1) + len(word2):
            return True
        return False


from classes.game import Person, bcolors
from classes.magic import Spell
from classes.inventory import Item
import random

fire = Spell('fire',10,100,'black')
thunder = Spell('Thunder',10,100,'black')
blizzard = Spell('Blizzard',10,100,'black')
meteor = Spell('Meteor',20,200,'black')
quake = Spell('Quake',14,140,'black')

cure = Spell('Cure',12,120,'white')
cura = Spell('Cura',18,200,'white')

potion = Item("Potion", "potion", "heals 50 HP", 50)
hipotion = Item("Hi-Potion", "potion", "heals 100 HP",100)
superpotion = Item("Super-Potion", "potion", "heals 500 HP",500)
elixer = Item("Elxier","elxier","Fully restores HP/MP of one party member", 9999)
hielixer = Item("MegaElxier", "elxier", "Fully restores party's MP/HP", 9999)
grenade = Item("Grenade", "attack", "Deals 500 damage", 500)

player_magic = [fire,thunder,blizzard,meteor,cure,cura]
player_items = [{'item':potion,'quantity': 5},{'item':hipotion,'quantity': 5},
                {'item':superpotion,'quantity': 5},{'item':elixer,'quantity': 5},
                {'item':hielixer,'quantity': 5},{'item':grenade,'quantity': 5}]
enemy_magic = [ fire,meteor,cure]

player1 = Person('Jay',4600,65,500,34,player_magic,player_items)
player2 = Person('Red',4600,65,500,34,player_magic,player_items)
player3 = Person('Kil',4600,65,500,34,player_magic,player_items)

enemy1 = Person('Mean',11200,65,750,25,enemy_magic,[])
enemy2 = Person('Weak',1250,130,560,300,enemy_magic,[])
enemy3 = Person('Weak',1250,130,560,300,enemy_magic,[])

players=[player1,player2,player3]
enemies = [enemy1,enemy2,enemy3]

running = True

print(bcolors.FAIL + bcolors.BOLD + "An enemy attacks" + bcolors.ENDC)

while running:
    print('+++++++++++++++++')
    print('\n\n')
    print('NAME                 HP                                     MP')

    for player in players:
        player.get_stats()

    print('\n\n')
    for enemy in enemies:
        enemy.get_enemy_stats()

    for player in players:
        player.choose_action()
        choice = input("    Choose Action:")
        index = int(choice) - 1
        print('You chose', choice)

        if index == 0:
            dmg = player.generate_damage()
            enemy = player.choose_target(enemies)

            enemies[enemy].take_damage(dmg)
            print('You attacked ' + enemies[enemy].name + ' for', dmg, "points of damage.")

            if enemies[enemy].get_hp() == 0:
                print(enemies[enemy].name + ' has been defeated')
                del enemies[enemy]
        elif index == 1:
            player.choose_magic()
            magic_choice = int(input('    Choose Magic:')) - 1

            if magic_choice == -1:
                continue

            spell = player.magic[magic_choice]
            magic_dmg = spell.generate_dmg()

            current_mp = player.get_mp()

            if spell.cost > current_mp:
                print(bcolors.FAIL +"\nNot enough MP\n" +bcolors.ENDC)
                continue

            player.reduce_mp(spell.cost)

            if spell.type == 'white':
                player.heal(magic_dmg)
                print(bcolors.OKBLUE + '\n' + spell.name + ' heals for', str(magic_dmg), 'HP' + bcolors.ENDC)
            elif spell.type == 'black':
                enemy = player.choose_target(enemies)
                enemies[enemy].take_damage(magic_dmg)
                print(bcolors.OKBLUE + "\n" + spell.name + " deals", str(magic_dmg), "points of damage to " + enemies[enemy].name + bcolors.ENDC)

                if enemies[enemy].get_hp() == 0:
                    print(enemies[enemy].name + ' has been defeated')
                    del enemies[enemy]
        elif index == 2:
            player.choose_item()
            item_choice = int(input("    Choose Item: ")) - 1

            if item_choice == -1:
                continue

            item = player.items[item_choice]['item']
            if player.items[item_choice]['quantity'] == 0:
                print(bcolors.FAIL + '\n' + 'None left...' + bcolors.ENDC)
                continue

            player.items[item_choice]['quantity'] -= 1

            if item.type == "potion":
                player.heal(item.prop)
                print( bcolors.OKGREEN + "\n" + item.name + " Heals for", str(item.prop), "HP" + bcolors.ENDC)
            elif item.type == 'elxier':
                player.hp = player.maxhp
                player.mp = player.maxmp
                print(bcolors.OKGREEN + '\n' + item.name + ' fully restores MP/HP' + bcolors.ENDC)
            elif item.type == 'attack':
                enemy = player.choose_target(enemies)

                enemies[enemy].take_damage(item.prop)
                print(bcolors.FAIL + '\n' + item.name + ' deals', str(item.prop), 'points of damage to ' + enemies[enemy].name + bcolors.ENDC)

                if enemies[enemy].get_hp() == 0:
                    print(enemies[enemy].name + ' has been defeated')
                    del enemies[enemy]

            print('---------------')
            print('Enemy HP:', bcolors.FAIL + str(enemy.get_hp()) + '/' + str(enemy.get_max_hp()) + bcolors.ENDC + '\n')
            print('Your HP:', bcolors.OKGREEN +str(player.get_hp())+ '/' + str(player.get_max_hp()) + bcolors.ENDC + '\n')
            print('Your MP:', bcolors.OKBLUE + str(player.get_mp())+ '/' + str(player.get_max_mp()) + bcolors.ENDC + '\n')

    defeated_enemies = 0
    defeated_players = 0

    for enemy in enemies:
        if enemy.get_hp() == 0:
            defeated_enemies += 1

    for player in players:
        if player.get_hp() == 0:
            defeated_players += 1

    if defeated_enemies == 2:
        print(bcolors.OKGREEN + 'You win!' + bcolors.ENDC)
        running = False

    elif defeated_players == 2:
        print(bcolors.FAIL + 'You Lost' + bcolors.ENDC)
        running = False
    print('\n')
    for enemy in enemies:
        enemy_choice = random.randrange(0,2)

        if enemy_choice == 0:
            target = random.randrange(0, 3)
            enemy_dmg = enemy.generate_damage()
            players[target].take_damage(enemy_dmg)
            print(enemy.name.replace(' ', '') + 'attacks ' + players[target].name.replace(' ','') + 'for', enemy_dmg)
        elif enemy_choice ==1:
            spell, magic_dmg = enemy.choose_enemy_spell()
            enemy.reduce_mp(spell.cost)
            if spell.type == 'white':
                enemy.heal(magic_dmg)
                print(bcolors.OKBLUE + spell.name + ' heals '+ enemy.name + 'for', str(magic_dmg), 'HP' + bcolors.ENDC)
            elif spell.type == 'black':
                target = random.randrange(0, 3)
                players[target].take_damage(magic_dmg)
                print(bcolors.OKBLUE + "\n" + enemy.name.replace(' ','') +  spell.name + " deals", str(magic_dmg), "points of damage to " + players[target].name + bcolors.ENDC)

                if players[target].get_hp() == 0:
                    print(players[target].name + ' has been defeated')
                    del players[player]
            print("Enemy choose", spell, 'damage is', magic_dmg)


#!/usr/bin/env python

from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

class plural:
    """
    The format string has three sections, separated by '/'.  The first section
    is always printed, the second (optional) section is printed if the number
    is singular, and the third section is printed if the number is plural.  Any
    '?' in the format string are replaced with the actual number.

    >>> "{:? thing/s}".format(plural(1))
    1 thing
    >>> "{:? thing/s}".format(plural(2))
    2 things

    >>> "{:/a cactus/? cacti}".format(plural(1))
    a cactus
    >>> "{:/a cactus/? cacti}".format(plural(2))
    2 cacti

    From Veedrac on Stack Overflow:
    http://stackoverflow.com/questions/21872366/plural-string-formatting

    """
    def __init__(self, value):
        self.value = value

    def __format__(self, formatter):
        formatter = formatter.replace("?", str(self.value))
        always, _, suffixes = formatter.partition("/")
        singular, _, plural = suffixes.rpartition("/")
        return "{}{}".format(always, singular if self.value == 1 else plural)

def oxford_comma(items, conj='and'):
    if len(items) == 2:
        return '{0[0]} {1} {0[1]}'.format(items, conj)

    result = ''
    for i, item in enumerate(items):
        if i == len(items) - 1:
            result += '{}'.format(item)
        elif i == len(items) - 2:
            result += '{}, {} '.format(item, conj)
        else:
            result += '{}, '.format(item)
    return result

def pretty_range(x):
    blocks = []
    current_seq = []

    def make_blocks(seq):
        if len(seq) == 0:
            return []
        elif len(seq) == 1:
            return [str(seq[0])]
        elif len(seq) == 2:
            return [str(seq[0]), str(seq[1])]
        else:
            return ['{}-{}'.format(seq[0], seq[-1])]

    for i in sorted(x):
        if current_seq and i != current_seq[-1] + 1:
            blocks += make_blocks(current_seq)
            current_seq = []
        current_seq.append(i)

    blocks += make_blocks(current_seq)
    return ','.join(blocks)

def indices_from_str(x, start=0):
    import re

    blocks = x.split(',')
    numbers = re.compile(r'(\d+)(-(\d+))?')
    indices = []

    for block in blocks:
        block = block.strip()

        if not block:
            continue

        match = numbers.match(block)
        i, j = match.group(1), match.group(3)

        if j:
            indices += [k - start for k in range(int(i), int(j)+1)]
        else:
            indices.append(int(i) - start)

    return indices


# The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will
# almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey
# with a Python function. How long do you think it would take for a Python function to generate just one sentence of
# Shakespeare? The sentence we’ll shoot for is: “methinks it is like a weasel”
#
# The way we’ll simulate this is to write a function that generates a string that is 27 characters long by choosing
# random letters from the 26 letters in the alphabet plus the space. We’ll write another function that will score each
# generated string by comparing the randomly generated string to the goal.
#
# A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done.
# If the letters are not correct then we will generate a whole new string.To make it easier to follow your program’s
# progress this third function should print out the best string generated so far and its score every 1000 tries.

import random

def generateString(strlen):
    """
    This function generate a random string with lenght of len
    :param strlen:
    :return: newstring
    """
    newstring = ""
    alphabet = "abcdefghijklmnopqrstuvwxyz "

    for i in range(strlen):
        newstring += alphabet[random.randrange(len(alphabet))]

    return newstring

def scoreResult(goal, newstring):
    """
    This function score a new generated string with the goal result and returns a %
    :param goal:
    :param newstring:
    :return:
    """
    success = 0
    for i in range(len(goal)):
        if goal[i] == newstring[i]:
            success += 1

    return  success / len(goal)

def main():
    goalstring = "methinks it is like a weasel"
    newstring = generateString(28)
    beststring = ""
    best = 0
    attempt = 0
    newscore = scoreResult(goalstring,newstring)
    result = {"bestscore":0, "beststr":'',"att":0}
    while newscore < 1:
        if newscore > best:
            best = newscore
            beststring = newstring

        newstring = generateString(28)
        newscore = scoreResult(goalstring,newstring)
        attempt += 1
        if attempt % 100000 == 0:
            if result["bestscore"] != best and result["beststr"] != beststring:
                result["bestscore"] = best
                result["bestst"] = beststring
                result["att"] = attempt
                print(best, attempt, beststring)

main()


import keyboard
import threading
from sound import *

hero = None
pressed_key = ""
is_stereo_on = False
key_list = ['', '+k', '+g', '+capslock', '+shift', '+w', '+a', '+s', '+d']

def key_on_press(name):
    global pressed_key
    print(name)
    pressed_key = name

keyboard.on_press(key_on_press)

def stereoKeyBind():
    keyboard.add_hotkey('Ctrl + Alt + Up', soundProfile, args=('/Enable', False))
    keyboard.add_hotkey('Ctrl + Alt + Down', soundProfile, args=('/Disable', True))

def heroKeyBind(count, name):
    keyboard.unhook_all_hotkeys()
    for i in range(count):
        for extra_key in key_list:
            keyboard.add_hotkey('Ctrl + {}{}'.format(i, extra_key),
                                lambda i=i: threading.Thread(target=heroSound, args=(name, i)).start())


"""HeyFoodie_api URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.views.i18n import JavaScriptCatalog
from rest_framework import routers
from HeyFoodie import views
from django.views.generic import TemplateView
from HeyFoodie.views import FacebookLogin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('jsi18n', JavaScriptCatalog.as_view(), name='javascript-catalog'),
    path('accounts/', include('django.contrib.auth.urls')),
    path('', views.index, name='index'),
    path('home/', views.home, name='home'),
    path('contact/', views.contact, name='contact'),
    path('ability/', views.ability, name='ability'),

    path('history/', views.history, name='history'),
    path('editprofile/', views.editProfile, name='editprofile'),
    path('editprofile/update/', views.editProfile_update, name='editprofile_update'),
    url(r'^password/$', views.change_password, name='change_password'),
    path('editshop/', views.editshop, name='editshop'),
    path('editshop/update/', views.editshop_update, name='editshop_update'),
    path('editmenu/', views.editmenu, name='editmenu'),
    path('editmenu/create/', views.editmenu_create, name='editmenu_create'),
    path('editmenu/<int:pk>/update/', views.editmenu_update, name='editmenu_update'),
    path('editmenu/<int:pk>/delete/', views.editmenu_delete, name='editmenu_delete'),

    path('createcategory/', views.createCategory, name='createCategory'),
    path('createsalesize/', views.createSalesize, name='createSalesize'),
    path('createIngredient/', views.createIngredient, name='createIngredient'),
    path('createingcategory/', views.createIngCategory, name='createIngCategory'),

    path('editingredient/', views.editingredient, name='editingredient'),
    path('editingredient/create/', views.editingredient_create, name='editingredient_create'),
    path('editingredient/<int:pk>/update/', views.editingredient_update, name='editingredient_update'),
    path('editingredient/<int:pk>/delete/', views.editingredient_delete, name='editingredient_delete'),
    path('editcategory/', views.editcategory, name='editcategory'),
    path('editcategory/create', views.editcategory_create, name='editcategory_create'),
    path('editcategory/<int:pk>/update/', views.editcategory_update, name='editcategory_update'),
    path('editcategory/<int:pk>/delete/', views.editcategory_delete, name='editcategory_delete'),
    path('editingcategory/', views.editingcategory, name='editingcategory'),
    path('editingcategory/create', views.editingcategory_create, name='editingcategory_create'),
    path('editingcategory/<int:pk>/update/', views.editingcategory_update, name='editingcategory_update'),
    path('editingcategory/<int:pk>/delete/', views.editingcategory_delete, name='editingcategory_delete'),
    path('editsalesize/', views.editsalesize, name='editsalesize'),
    path('editsalesize/create', views.editsalesize_create, name='editsalesize_create'),
    path('editsalesize/<int:pk>/update/', views.editsalesize_update, name='editsalesize_update'),
    path('editsalesize/<int:pk>/delete/', views.editsalesize_delete, name='editsalesize_delete'),
    path('order/', views.order, name='order'),
    path('order/changeStatus/<int:pk>', views.changeStatus, name='changeStatus'),
    path('order/cancelOrder/<int:pk>', views.cancelOrder, name='cancelOrder'),

    path('bestsellmenuday/', views.bestsellmenuday, name='bestsellmenuday'),
    path('bestsellmenuweek/', views.bestsellmenuweek, name='bestsellmenuweek'),
    path('bestsellmenumonth/', views.bestsellmenumonth, name='bestsellmenumonth'),

    path('hfapi/', include('HeyFoodie.urls')),

    path('rest-auth/registration/', include('rest_auth.registration.urls')),
    path('rest-auth/facebook/', FacebookLogin.as_view(), name='fb_login')

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# Definition for singly-linked list with a random pointer.
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None
class Solution:
    # @param head: A RandomListNode
    # @return: A RandomListNode
    def copyRandomList_hqi(self, head):
        # write your code here
        # copy nodes first and use a hashmap
        # TLE
        node_map = {}
        dummy = head
        while head:
            new_head = RandomListNode(head.label)
            node_map[head] = new_head
            head = head.next

        head = dummy
        while head:
            if head.next:
                node_map[head].next = node_map[head.next]
            if head.random:
                node_map[head].random = node_map[head.random]

            head = head.next

        return node_map

    def copyRandomList(self, head):

        dummy = head
        while head:
            next = head.next
            new_head = RandomListNode(head.label)
            head.next = new_head
            new_head.next = next
            head = next

        head = dummy
        while head:
            next = head.next
            if head.random:
                next.random = head.random.next
            head = next.next

        new_head = dummy.next
        dummy = new_head
        while new_head and new_head.next:
            new_head.next = new_head.next.next
            new_head = new_head.next

        return dummy


import fnmatch
import argparse
import os
import mc2xml
import visa2xml
import logging
from matching_db import *

__version_info__ = ('2018','09','27')
__version__ = '-'.join(__version_info__)

def _parse_arguments():
    """
    argparse parser

    :return: parsed arguments
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("filenames", action='append', nargs='+', help="Enter filenames")
    parser.add_argument('-V', '--version', action='version', version='%(prog)s ' + __version__)
    parser.add_argument('-u', dest='unmask', help='Unmask PAN', action='store_false')
    parser.add_argument('-c', dest='comment', help='Comment to add in result XML file')
    parser.add_argument('-l', dest='logging', action='store_true', help='Enable full logging mode')
    parser.add_argument('-v', dest='visa', action='store_true', help='parse as VISA')
    parser.add_argument('-m', dest='mc', action='store_true', help='parse as MasterCard')
    parser.add_argument('-t', dest='test', choices=['prime_acq_tst', 'prime_acq_openstack', 'greenplum'],
                        help='Check ARN by Database')
    parser.add_argument('-o', dest='oracle', default="C:\\app\\instantclient_12_2",
                        help='Oracle instant client datapath')

    return parser

def open_in_mps(filename, unmask, mes_comment, visa, mc):
    """
    Jacket will try to parse file in all parsers
    :param filename: import filename
    :param unmask: bool value unmasking PAN
    :param mes_comment: comment to add to file
    :param visa: parse file only as VISA
    :param mc: parse file only as MC

    """

    mc2xml.comment = mes_comment
    mc2xml.unmask = unmask

    visa2xml.unmask = unmask
    visa2xml.comment = mes_comment

    if visa:
        visa2xml.exctract_visa(filename)
    elif mc:
        mc2xml.extract_mc(filename)
    else:
        try:
            mc2xml.extract_mc(filename)
        except KeyError:
            visa2xml.exctract_visa(filename)

def isASCII(data):
    try:
        data[:200].decode('ASCII')
    except UnicodeDecodeError as exc:
        return False
    else:
        return True

def _main_mps2xml(args):
    """
    mc2xml main processing
    :param args: argparse arguments
    :return: exit code
    """

    if hasattr(args, 'unmask'):
        unmask = args.unmask
    else:
        unmask = True

    mc2xml.unmask = unmask
    visa2xml.unmask = unmask

    if hasattr(args, 'comment'):
        comment = args.comment
        mc2xml.comment = comment
        visa2xml.comment = comment

    if hasattr(args, 'visa'):
        is_visa = True

    if hasattr(args, 'mc'):
        is_visa = False

    if hasattr(args, 'test'):
        test = args.test

    if hasattr(args, 'oracle'):
        oracle = args.oracle

    if hasattr(args, 'logging'):
        if args.logging:
            logging.basicConfig(filename=os.path.join("mps2xml.log"), level=logging.DEBUG,
                                format='%(asctime)s - %(message)s')

    # exit if input file does not exist
    if not hasattr(args, 'filenames'):
        print("Input file not found")
        exit(8)

    filenames = args.filenames[0]

    for file in filenames:
        # Search files by mask
        if '*' in file:
            dir = os.path.dirname(os.path.abspath(file))
            onlyfiles = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f))]
            for cfile in onlyfiles:
                if fnmatch.fnmatch(cfile, file):
                    print("Processed file {}".format(cfile))
                    process_file(file, is_visa, test, oracle)

        # Processed current file
        else:
            if os.path.isfile(file):
                print("Processed file {}".format(file))
                try:
                    process_file(file, is_visa, test, oracle)
                except Exception as exc:
                    print (str(exc))
            else:
                print("File {} not found!".format(file))

def process_file(filename, is_visa, testDB, oracle):
    # Get input data
    # Read input file
    with open(filename, 'rb') as infile:
        input_file = infile.read()
    if isASCII(input_file) or is_visa or input_file[:2] == '90':
        #context = [line for line in input_file.decode('ascii').split('\n') if line]
        try:
            return_xml = visa2xml.process_visa(filename)
            is_visa = True
        except Exception:
            return_xml = mc2xml.process_mc(input_file)
            is_visa = False
    else:
        try:
            return_xml = mc2xml.process_mc(input_file)
            is_visa = False
        except KeyError:
            context = [line for line in input_file.decode('ascii').split('\n') if line]
            return_xml = visa2xml.process_visa(context)
            is_visa = True

    if testDB:
        rough_string = ElementTree.tostring(return_xml, 'utf-8')
        if testDB == 'greenplum':
            return_xml = checkXMLbyDWH(rough_string, is_visa)
        else:
            return_xml = checkXMLbyOracle(testDB, rough_string, oracle, is_visa)

    # Make XML pretty
    xmlstr = prettify(return_xml)

    # Write to file
    output_filename = filename + ".xml"
    try:
        with open(output_filename, "w") as f:
            f.write(xmlstr)
        print("Successfully write to file: {}".format(output_filename))
    except Exception as exc:
        print("Cannot write to XML file: {} {}".format(output_filename, exc))

if __name__ == '__main__':
    _main_mps2xml(_parse_arguments().parse_args())


# Shows fast visualization within python Open3D
import numpy
import open3d

# define the input cloud and output cloud directories
#input_path = 'C:/Users/shabe/OneDrive/Documents/GitHub/IAAC_studio_1_2/studio workshop support/STUDIO SUPPORT WORKSHOP -20210302T100019Z-001/STUDIO SUPPORT WORKSHOP/point-cloud/data/fused.ply'
#input_path = "/media/shabelson/BC507DA2507D63D4/Documents and Settings/shabe/OneDrive/Documents/GitHub/IAAC_studio_1_2/studio workshop support/STUDIO SUPPORT WORKSHOP -20210302T100019Z-001/STUDIO SUPPORT WORKSHOP/point-cloud/data/fused.ply"
# Read the input cloud
fname = "./soft2_compiled_1615307126_734546.csv"

xyz = numpy.genfromtxt(fname,dtype=float,delimiter=' ')
locPts = open3d.cpu.pybind.utility.Vector3dVector(xyz)
locPts = open3d.geometry.PointCloud(locPts)

# View pointcloud
open3d.visualization.draw_geometries([locPts])


import sys
from collections import OrderedDict

import os
import torch
from torch import nn
from torch.autograd import Variable
from torchvision import transforms

class MarrNet(nn.Module):
    def __init__(self, cuda=False):
        super(MarrNet, self).__init__()
        from marrnet.models.step1 import step1
        from marrnet.models.step2 import step2
        self.step1 = step1
        self.step2 = step2
        script_dir = os.path.join(os.path.dirname(__file__), 'models')
        self.step1.load_state_dict(torch.load(os.path.join(script_dir, 'step1.pth')))
        self.step2.load_state_dict(torch.load(os.path.join(script_dir, 'step2.pth')))
        self.silhouette_threshold = 30
        if cuda is not False:
            self.cuda(cuda if cuda is not True else None)

    def forward(self, input):
        step1_out = self.step1(input)
        masked_normal_depth = self.mask(step1_out)
        step2_out = self.step2(masked_normal_depth)
        assert list(step2_out.size())[-3:] == [128, 128, 128]
        return step2_out

    def mask(self, input):
        normal = input[0]
        depth = input[1]
        silhouette = input[2][:, 0, :, :]
        silhouette_mask = torch.le(silhouette, self.silhouette_threshold)

        # TODO: solve this within PyTorch. Work around in-place limitation
        masked_normal = normal.data.numpy()
        masked_depth = depth.data.numpy()
        silhouette_mask = silhouette_mask.data.numpy().astype(bool)
        for i in range(3):
            masked_normal[:, i, :, :][silhouette_mask] = 100
        masked_depth[:, 0, :, :][silhouette_mask] = 0
        return torch.cat((Variable(torch.FloatTensor(masked_normal)), Variable(torch.FloatTensor(masked_depth))), 1)

def preprocess(normalize_mean=[0.485, 0.456, 0.406], normalize_std=[0.229, 0.224, 0.225], scale_dim=256):
    return transforms.Compose([
        transforms.Scale(scale_dim),
        transforms.ToTensor(),
        transforms.Normalize(mean=normalize_mean, std=normalize_std),
        lambda img: img.unsqueeze(0)
    ])

def summary(model, x, file=sys.stdout):
    """
    adapted from https://github.com/pytorch/pytorch/pull/3043
    Use input x directly instead of creating from input_size
    """

    def register_hook(module):
        def hook(module, input, output):
            if module._modules:  # only want base layers
                return
            class_name = str(module.__class__).split('.')[-1].split("'")[0]
            module_idx = len(summary)
            m_key = '%s-%i' % (class_name, module_idx + 1)
            summary[m_key] = OrderedDict()
            summary[m_key]['input_shape'] = list(input[0].size())
            summary[m_key]['input_shape'][0] = None
            if output.__class__.__name__ == 'tuple':
                summary[m_key]['output_shape'] = list(output[0].size())
            else:
                summary[m_key]['output_shape'] = list(output.size())
            summary[m_key]['output_shape'][0] = None

            params = 0
            # iterate through parameters and count num params
            for name, p in module._parameters.items():
                params += torch.numel(p.data) if p is not None else 0
                summary[m_key]['trainable'] = p.requires_grad if p is not None else False

            summary[m_key]['nb_params'] = params

        if not isinstance(module, torch.nn.Sequential) and \
                not isinstance(module, torch.nn.ModuleList) and \
                not (module == model):
            hooks.append(module.register_forward_hook(hook))

    # create properties
    summary = OrderedDict()
    hooks = []
    # register hook
    model.apply(register_hook)
    # make a forward pass
    model(x)
    # remove these hooks
    for h in hooks:
        h.remove()

    # print out neatly
    def get_names(module, name, acc):
        if not module._modules:
            acc.append(name)
        else:
            for key in module._modules.keys():
                p_name = key if name == "" else name + "." + key
                get_names(module._modules[key], p_name, acc)

    names = []
    get_names(model, "", names)

    col_width = 25  # should be >= 12
    summary_width = 61

    def crop(s):
        return s[:col_width] if len(s) > col_width else s

    print('_' * summary_width, file=file)
    print('{0: <{3}} {1: <{3}} {2: <{3}}'.format(
        'Layer (type)', 'Output Shape', 'Param #', col_width), file=file)
    print('=' * summary_width, file=file)
    total_params = 0
    trainable_params = 0
    for (i, l_type), l_name in zip(enumerate(summary), names):
        d = summary[l_type]
        total_params += d['nb_params']
        if 'trainable' in d and d['trainable']:
            trainable_params += d['nb_params']
        print('{0: <{3}} {1: <{3}} {2: <{3}}'.format(
            crop(l_name + ' (' + l_type[:-2] + ')'), crop(str(d['output_shape'])),
            crop(str(d['nb_params'])), col_width), file=file)
        if i < len(summary) - 1:
            print('_' * summary_width, file=file)
    print('=' * summary_width, file=file)
    print('Total params: ' + str(total_params), file=file)
    print('Trainable params: ' + str(trainable_params), file=file)
    print('Non-trainable params: ' + str((total_params - trainable_params)), file=file)
    print('_' * summary_width, file=file)


"""instapro URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.urls import path,include

from . import views

# ndcbndvgkVG

from .viewsets import UploadedImagesViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register('images', UploadedImagesViewSet, 'images')
from django.conf.urls import url

urlpatterns = [

    path('follower/',views.Follower.as_view()),
    path('following/',views.Following.as_view()),
    path('post/',views.Post.as_view()),
    path('userAuth/',views.userAuth.as_view()),
    path('userImage/',views.userImage.as_view()),
    path('search/',views.Search.as_view()),
    path('comments/',views.Comments.as_view()),
    path('likes/',views.Likes.as_view()),
    path('registor/',views.Registor.as_view()),
    # path('editprofile/<int:pk>',views.EditProfile.as_view()),
    path('newpost/',views.NewPost.as_view()),    #future task
    path('newcomment/',views.NewComment.as_view()),
    path('newlike/',views.NewLike.as_view()),
    path('tagdetail/',views.TagDetail.as_view()),
    path('checkfollower/',views.CheckFollower.as_view()),
    path('unfollow/',views.UnFollow.as_view()),
    path('follow/',views.Follow.as_view()),

    url('', include(router.urls)),

]


import multiprocessing
import time

def depositMoney(money,lock):
    for i in range(4000):
        lock.acquire()
        money.value +=1
        lock.release()
        print("deposit ", money.value())

def withdrawMoney(money,lock):
    for i in range(4000):
        lock.acquire()
        money.value -=1
        lock.release()
        print("Withdraw ", money.value())

if __name__ == "__main__":
    lockprocess=multiprocessing.Lock()
    balanceMoney=multiprocessing.Value('i',0)
    process1=multiprocessing.Process(target=depositMoney,args=(balanceMoney,lockprocess))
    process2=multiprocessing.Process(target=withdrawMoney,args=(balanceMoney,lockprocess))

    process1.start()
    process2.start()

    process1.join()
    process2.join()

    print("Final Balance :" ,balanceMoney.value())


from base.Parser import *
from base.NodeVisitor import NodeVisitor
from type.BinOperation import BinaryOperation
from type.Numeric import Numeric
from type.UnaryOperation import UnaryOperation
from type.Compound import Compound
from type.Variable import Variable
from type.Assign import Assign
from type.NoOperation import NoOperation
from type.Print import Print
from base_object.HTMLAnalyzer import *
import threading as th

class Interpreter(NodeVisitor):

    GLOBAL_SCOPE = {}

    def __init__(self, parser: Parser):
        self.parser = parser

        self.GLOBAL_SCOPE['document'] = HTMLAnalyzer()
        self.lock = th.Lock()

    def visit_BinaryOperation(self, node: BinaryOperation):

        if node.operation.type == PLUS:
            return self.visit(node.left) + self.visit(node.right)

        elif node.operation.type == MINUS:
            return self.visit(node.left) - self.visit(node.right)

        elif node.operation.type == MUL:
            return self.visit(node.left) * self.visit(node.right)

        elif node.operation.type == DIV:
            return self.visit(node.left) / self.visit(node.right)

        elif node.operation.type == EQUAL:
            return self.visit(node.left) == self.visit(node.right)

        elif node.operation.type == LESS:
            return self.visit(node.left) < self.visit(node.right)

        elif node.operation.type == GREAT:
            return self.visit(node.left) > self.visit(node.right)

    def visit_Numeric(self, node: Numeric):
        return node

    def visit_String(self, node: String):
        return node

    def visit_UnaryOperation(self, node: UnaryOperation):
        operation = node.operation.type

        if operation == PLUS:
            return +self.visit(node.expr)
        elif operation == MINUS:
            return -self.visit(node.expr)

    def visit_Compound(self, node: Compound):
        for child in node.children:
            self.visit(child)

    def visit_Token(self, node: Token):
        return node.value

    def visit_Assign(self, node: Assign):
        var_name = node.left.value
        self.GLOBAL_SCOPE[var_name] = self.visit(node.right)

    def visit_Variable(self, node: Variable):
        var_name = node.value

        value = self.GLOBAL_SCOPE.get(var_name)

        if value is None:
            raise NameError(repr(var_name))
        else:
            return value

    def visit_Print(self, node: Print):
        print_info = self.visit(node.print)

        output_file = open("F:/Github/Interpret/gui/output.txt", 'at')

        if type(print_info) == List:
            result = "["
            for item in print_info.value:
                print_a = self.visit(item)
                result += str(print_a) + ", "

            print(result + "]", file=output_file)
        else:
            if hasattr(print_info, "value"):
                print(print_info.value, file=output_file)
            else:
                print(print_info, file=output_file)

        output_file.close()

    def visit_Length(self, node: Length):
        return len(self.visit(node.node))

    def visit_StrT(self, node: StrT):
        return String.create_string(str(self.visit(node.node)))

    def visit_NumT(self, node: NumT):
        return Numeric.create_num(float(self.visit(node.node)))

    def visit_List(self, node: List):
        return node

    def visit_MethodCall(self, node: MethodCall):
        variable = node.variable_name
        method = node.method_name

        called_method = getattr(self.visit(variable), method)

        arg_list = []

        for arg in node.arg:
            arg_list.append(self.visit(arg))

        return called_method(*arg_list)

    def visit_If(self, node: If):
        result_condition = self.visit(node.condition)

        if bool(result_condition):
            self.visit(node.body)
        elif node.else_body is not None:
            self.visit(node.else_body)
        else:
            pass

    def visit_While(self, node: While):
        while bool(self.visit(node.condition)):
            self.visit(node.body)

    def visit_For(self, node: For):
        self.visit(node.assignment)

        while bool(self.visit(node.condition)):
            self.visit(node.body)
            self.visit(node.change_node)

    def visit_Thread(self, node: Thread):
        return th.Thread(target=self.visit_Compound, args=(node.body,))

    def visit_NoOperation(self, node: NoOperation):
        pass

    def visit_Import(self, node: Import):
        with open(node.file_name.value, 'r') as file:
            lines_list = file.readlines()

        new_lines = "".join(lines_list)

        lexer = Lexer(new_lines)
        parser = Parser(lexer)
        interpret = Interpreter(parser)
        interpret.interpret()

    def interpret(self):
        tree = self.parser.parse()

        if tree is None:
            return ""

        return self.visit(tree)


#encoding: utf-8

import logging

logger = logging.getLogger(__name__)

if __name__ == '__main__':
    logging.basicConfig(
        level=logging.DEBUG,
        filename='info.log',
        filemode='w',
        format='%(asctime)s - %(name)s - %(levelname)s:%(message)s',
        )
    logger.debug('debug')
    logger.exception('ex')
    logger.error('error')


#!/usr/bin/python3

from evdev import uinput, ecodes as e
from time import sleep
from random import random
import sys

def scaleTime(time):
	return time * (random() * 2)

try:
	logName = sys.argv[1]
except IndexError:
	print("Please pass in a log file to use.")
	sys.exit(1)

log = []
with open(logName) as f:
	for line in f.read().split('\n'):
		if line == '': continue
		time, key, event = line.split(' ')
		log.append({"time": float(time), "key": int(key), "event": int(event)})

sleep(5)

for event in log:
	sleep(scaleTime(event["time"]))
	with uinput.UInput() as ui:
		print(event)
		ui.write(e.EV_KEY, event["key"], event["event"])
		ui.syn()


def consumer():
	r = ''
	print ('.....')
	while True:
		print (0)
		n = yield r
		print(1)
		print (str(n)+'..\n')
		if not n:
			print ('Initialized!\n')
			# return '000'
		print ('[Consumer] Consuming %s...' % n)
		r = '200 OK'

def produce(c):
	r = c.send(999)
	print ('send None to consumer...', r)
	n = 0
	while n < 2:
		n = n + 1
		print ('{Producer} Producing %s...' % n)
		r = c.send(n)
		print ('{Producer} Consumer return %s\n' % r)
		# n = n + 1
	c.close()

con = consumer()
produce(con)


from ShelterSmartHome.apps.lead_node.models import LeadNode, LeadInterface
from ShelterSmartHome.apps.dataset_manager.models import WebChart

def get_created_charts():
    response = {'resp_created_charts': {}}
    for saved_chart in WebChart.objects.all():
        chart = WebChart.objects.get(name=saved_chart.name)
        response['resp_created_charts'][chart.name] = {'name': chart.name,
                                                       'type_chart': chart.type_chart,
                                                       'added_items_to_chart': chart.added_items_to_chart,
                                                       'saved_period': chart.saved_period,
                                                       'x_y_placed_on_screen': chart.x_y_placed_on_screen
                                                       }
    return response

def get_rt_leads():
    leads = []
    for item in LeadNode.objects.all():
        if item.data == 'inf' and item.path.find('.') != -1:
            leads.append({item.name: item.path})
    response = {'resp_rt_leads': leads}
    return response

def dataset_manager_request(request):
    try:
        if request['text'] == 'get_created_charts':
            return get_created_charts()
        if request['text'] == 'get_rt_leads':
            return get_rt_leads()
    except:
        pass


from django.db import models

class Owner(models.Model):
    name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    age = models.IntegerField()
    # 주인은 누군가를 팔로잉 할 수 있고, 또 다른 사람을 팔로잉 할 수 있다
    following = models.ManyToManyField('self')
    followers = models.ManyToManyField('self')

nicolas = Owner.objects.get(pk=1)
pedro = Owner.objects.get(pk=2)
jisu = Owner.objects.get(pk=3)

# 여기서 PK는 primary key를 의마함 OR 장고의 ID를 뜻함

nicolas.followers.add(jisu. pedro)
# followers 칼럼 -> 2,3