import codecs
import re

from .compat import IS_TYPE_CHECKING, to_text

if IS_TYPE_CHECKING:
    from typing import (  # noqa:F401
        IO, Iterator, Match, NamedTuple, Optional, Pattern, Sequence, Text,
        Tuple
    )

def make_regex(string, extra_flags=0):
    # type: (str, int) -> Pattern[Text]
    return re.compile(to_text(string), re.UNICODE | extra_flags)

_newline = make_regex(r"(\r\n|\n|\r)")
_multiline_whitespace = make_regex(r"\s*", extra_flags=re.MULTILINE)
_whitespace = make_regex(r"[^\S\r\n]*")
_export = make_regex(r"(?:export[^\S\r\n]+)?")
_single_quoted_key = make_regex(r"'([^']+)'")
_unquoted_key = make_regex(r"([^=\#\s]+)")
_equal_sign = make_regex(r"(=[^\S\r\n]*)")
_single_quoted_value = make_regex(r"'((?:\\'|[^'])*)'")
_double_quoted_value = make_regex(r'"((?:\\"|[^"])*)"')
_unquoted_value_part = make_regex(r"([^ \r\n]*)")
_comment = make_regex(r"(?:[^\S\r\n]*#[^\r\n]*)?")
_end_of_line = make_regex(r"[^\S\r\n]*(?:\r\n|\n|\r|$)")
_rest_of_line = make_regex(r"[^\r\n]*(?:\r|\n|\r\n)?")
_double_quote_escapes = make_regex(r"\\[\\'\"abfnrtv]")
_single_quote_escapes = make_regex(r"\\[\\']")

try:
    # this is necessary because we only import these from typing
    # when we are type checking, and the linter is upset if we
    # re-import
    import typing

    Original = typing.NamedTuple(
        "Original",
        [
            ("string", typing.Text),
            ("line", int),
        ],
    )

    Binding = typing.NamedTuple(
        "Binding",
        [
            ("key", typing.Optional[typing.Text]),
            ("value", typing.Optional[typing.Text]),
            ("original", Original),
            ("error", bool),
        ],
    )
except ImportError:
    from collections import namedtuple
    Original = namedtuple(  # type: ignore
        "Original",
        [
            "string",
            "line",
        ],
    )
    Binding = namedtuple(  # type: ignore
        "Binding",
        [
            "key",
            "value",
            "original",
            "error",
        ],
    )

class Position:
    def __init__(self, chars, line):
        # type: (int, int) -> None
        self.chars = chars
        self.line = line

    @classmethod
    def start(cls):
        # type: () -> Position
        return cls(chars=0, line=1)

    def set(self, other):
        # type: (Position) -> None
        self.chars = other.chars
        self.line = other.line

    def advance(self, string):
        # type: (Text) -> None
        self.chars += len(string)
        self.line += len(re.findall(_newline, string))

class Error(Exception):
    pass

class Reader:
    def __init__(self, stream):
        # type: (IO[Text]) -> None
        self.string = stream.read()
        self.position = Position.start()
        self.mark = Position.start()

    def has_next(self):
        # type: () -> bool
        return self.position.chars < len(self.string)

    def set_mark(self):
        # type: () -> None
        self.mark.set(self.position)

    def get_marked(self):
        # type: () -> Original
        return Original(
            string=self.string[self.mark.chars:self.position.chars],
            line=self.mark.line,
        )

    def peek(self, count):
        # type: (int) -> Text
        return self.string[self.position.chars:self.position.chars + count]

    def read(self, count):
        # type: (int) -> Text
        result = self.string[self.position.chars:self.position.chars + count]
        if len(result) < count:
            raise Error("read: End of string")
        self.position.advance(result)
        return result

    def read_regex(self, regex):
        # type: (Pattern[Text]) -> Sequence[Text]
        match = regex.match(self.string, self.position.chars)
        if match is None:
            raise Error("read_regex: Pattern not found")
        self.position.advance(self.string[match.start():match.end()])
        return match.groups()

def decode_escapes(regex, string):
    # type: (Pattern[Text], Text) -> Text
    def decode_match(match):
        # type: (Match[Text]) -> Text
        return codecs.decode(match.group(0), 'unicode-escape')  # type: ignore

    return regex.sub(decode_match, string)

def parse_key(reader):
    # type: (Reader) -> Optional[Text]
    char = reader.peek(1)
    if char == "#":
        return None
    elif char == "'":
        (key,) = reader.read_regex(_single_quoted_key)
    else:
        (key,) = reader.read_regex(_unquoted_key)
    return key

def parse_unquoted_value(reader):
    # type: (Reader) -> Text
    value = u""
    while True:
        (part,) = reader.read_regex(_unquoted_value_part)
        value += part
        after = reader.peek(2)
        if len(after) < 2 or after[0] in u"\r\n" or after[1] in u" #\r\n":
            return value
        value += reader.read(2)

def parse_value(reader):
    # type: (Reader) -> Text
    char = reader.peek(1)
    if char == u"'":
        (value,) = reader.read_regex(_single_quoted_value)
        return decode_escapes(_single_quote_escapes, value)
    elif char == u'"':
        (value,) = reader.read_regex(_double_quoted_value)
        return decode_escapes(_double_quote_escapes, value)
    elif char in (u"", u"\n", u"\r"):
        return u""
    else:
        return parse_unquoted_value(reader)

def parse_binding(reader):
    # type: (Reader) -> Binding
    reader.set_mark()
    try:
        reader.read_regex(_multiline_whitespace)
        if not reader.has_next():
            return Binding(
                key=None,
                value=None,
                original=reader.get_marked(),
                error=False,
            )
        reader.read_regex(_export)
        key = parse_key(reader)
        reader.read_regex(_whitespace)
        if reader.peek(1) == "=":
            reader.read_regex(_equal_sign)
            value = parse_value(reader)  # type: Optional[Text]
        else:
            value = None
        reader.read_regex(_comment)
        reader.read_regex(_end_of_line)
        return Binding(
            key=key,
            value=value,
            original=reader.get_marked(),
            error=False,
        )
    except Error:
        reader.read_regex(_rest_of_line)
        return Binding(
            key=None,
            value=None,
            original=reader.get_marked(),
            error=True,
        )

def parse_stream(stream):
    # type: (IO[Text]) -> Iterator[Binding]
    reader = Reader(stream)
    while reader.has_next():
        yield parse_binding(reader)


def distinct_values_bt(bin_tree):
    """Find distinct values in a binary tree."""
    distinct = {}
    result = []

    def _walk(node=None):
        if node is None:
            return

        if node.left is not None:
            _walk(node.left)

        if distinct.get(node.val):
            distinct[node.val] = distinct[node.val] + 1
        else:
            distinct[node.val] = 1

        if node.right is not None:
            _walk(node.right)

    _walk(bin_tree.root)

    # for key in list(distinct):
    #     if distinct[key] != 1:
    #         del distinct[key]

    # return list(distinct.keys())

    # lesser of 2 evils:
    for key in distinct:
        if distinct[key] == 1:
            result.append(key)

    return result

    # or cut 5 lines of code into 1 using list comprehension:
    # return [key for key, val in distinct.items() if val == 1]

    # Big O:
    # time: O(N)
    # space: O(2N) = O(N)


#HWPython18_09_GloCngChk_정승현.py

#전역변수 (global variable)
	#함수 외에 선언
	#모든 함수와 공유
# 지역변수 (local variable)
	#함수 내에 선언
	#함수와 생명력을 같이한다.
#함수 안에서 사용하는 매개변수는 지역변수이다.

a=1
def vartest(a):
	a=a+3
	print(a)
	print()

vartest(a)
print(a)
print()
#2. global 명령어 사용하기
	#global 명렁어 : 함수 안에서 함수 밖의 변수를 직접 사용할 때 사용
	#외부 변수에 종속적인 함수는 그다지 좋은 함수가 아니다
a = 1
def vartest():
	global a
	a= a+1
vartest()
print(a)


from twilio.rest import TwilioRestClient
from twilio import twiml
from datetime import date

# To find these visit https://www.twilio.com/user/account
ACCOUNT_SID = "ACf0757674cd3d5092237f0ee7afca722e"
AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY"

client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

message = client.messages.create(
    body=input('Enter message to be sent\n'),  # Message body, if any #input('Enter message to be sent\n')
    to=input('Enter your phone number\n'),
    from_="+13023856046",
    media_url="http://www.hdwallpapers.in/walls/pawan_kalyan-wide.jpg"
)

'''
media_url=[  # List of media URLs, if any
        "http://example.com/image1.jpg",
        "http://example.com/image2.jpg",

'''
print(message.sid)

for message in client.messages.list():
    print(message.body)

messages = client.messages.list(
    to="+16692261830",
    date_sent=date(2015,4,18),
)
#input('Enter the phone number\n'),"+16692261830","+13015260890"

for message in messages:
    print(message.body)

'''

Redacting or Deleting Message Records

To protect your users’ privacy and/or comply with legal requirements, Twilio allows you to redact your Message bodies or delete the records outright.

from twilio.rest import TwilioRestClient

# To find these visit https://www.twilio.com/user/account
ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX"
AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY"

client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
message_sid = "MM123"

client.messages.redact(message_sid)
message = client.messages.get(message_sid)
print message.body  # Will be an empty string

client.messages.delete(message_sid)  # Deletes record entirely, subsequent requests will return 404

'''


from configparser import ConfigParser
from fantastic.exercises.choose.choose_class import Choose

class VraiFaux(Choose):
    """See Exercise class documentation to understand the different parameters"""

    def __init__(self, json_path: str, config: ConfigParser) -> None:
        super().__init__(
            json_path,
            config,
            output_folder_name="vrai-faux",
        )

    def find_choices(self):
        self.choices = [["vrai", "faux"]]
        return self.choices


"""
    Quick Sort with a queue/stack
"""

class Solution:
    # pylint: disable=too-few-public-methods
    """
    Solution
    """

    @staticmethod
    def _partition(start, end, arr):
        pivot = start
        while True:
            # keep looking for a value > the pivot
            # from the left
            while start <= end and arr[start] <= arr[pivot]:
                start += 1

            # keep looking for a value <= the pivot
            # from the right
            while start <= end and arr[end] > arr[pivot]:
                end -= 1

            if start < end:  # swap
                arr[start], arr[end] = arr[end], arr[start]
            if start >= end:
                break
        # move the pivot to the correct location.
        arr[end], arr[pivot] = arr[pivot], arr[end]
        # return the new location of the pivot value.
        return end

    def get_submission(self, arr):
        # pylint: disable=no-self-use
        """
        Quick Sort
        """
        queue = [(0, len(arr) - 1)]
        while queue:
            start, end = queue.pop(0)
            if start < end:
                pivot = self._partition(start, end, arr)
                queue.append((start, pivot - 1))
                queue.append((pivot + 1, end))
        return arr


from django.urls import path

from . import views

app_name = 'contacts'
urlpatterns = [
    path('api/contact/list/account/<slug:account>/', views.ContactList.as_view(), name='contact_list'),
    path('api/contact/create/', views.ContactCreate.as_view(), name='contact_create'),
    path('api/contact/retrieve/<slug:ucid>/account/<slug:account>/', views.ContactRetrieve.as_view(), name='contact_rud'),
    path('api/address/create/', views.AddressCreate.as_view(), name='address_create'),
    path('api/address/<int:id>/', views.AddressRetrieve.as_view(), name='address_rud'),
]


__author__ = "Will Hannon"
__copyright__ = "Copyright 2020 Will Hannon"
__email__ = "wwh22@uw.edu"
__license__ = "MIT"

## === Import Libraries === ##
import pysam #count variant alleles from BAM
import pandas as pd #data frames
import numpy as np #arrays
import os #interacting with files
from Bio import SeqIO #reading fasta format
import re #regular expressions

## === Functions === ##

def check_read(read):
    """
    Helper function to decide what reads should
    be keep when parsing alignment file with `pysam`.

    Parameters
    ----------
    read : AlignedSegment
        read from alignment file parsed with `pysam`.

    Returns
    -------
    bool
        True/False if read should be included

    """
    # Exclude Quality Failures
    if read.is_qcfail:
        return False
    # Exclude Secondary Mappings
    if read.is_secondary:
        return False
    # Exclude Unmapped Reads
    if read.is_unmapped:
        return False
    else:
        return True

def get_day(path):
    """
    If the samples are downloaded from the SRA, use the
    SRA accession to get the day the sample was collected on.

    Parameters
    ----------
    path : str
        path to the sample

    Returns
    -------
    int
        the day the sample was collected

    """

    day_mapping = {
    'SRR13160722':152,
    'SRR13160723':146,
    'SRR13160724':143,
    'SRR13160725':130,
    'SRR13160726':128,
    'SRR13160727':81,
    'SRR13160728':75,
    'SRR13160729':25,
    'SRR13160730':18
    }

    basename = os.path.basename(path)

    regex = re.compile("(?P<run>SRR\d+)\.BWA")

    m = regex.match(basename)

    return day_mapping[str(m.group('run'))]

def phase_variants(aa_change_list, joined_spike_count_df, filepath, contig = "NC_045512.2"):
    """
    Uses a list of variant alleles, a data-frame of SNPs corresponding to BAM, and an alignment file to make a N (SNPs) X P (Reads)
    dataframe with the read support for every obseved phase of varaints.

    Parameters
    ----------
    joined_spike_count_df : Pandas.DataFrame
        Dataframe with SNPs summarized over a region.

    filepath : str
        path to the bam file to be parsed

    aa_change_list : list
        a list of alleles to phase

    conitg : str
        name of the chromosome, in this case the whole reference.

    Returns
    -------
    Pandas.DataFrame
       A Pandas.DataFrame of 0, 1, or NaN, describing read support for a given phase.

    """

    ## ===== Format inputs and get SNP list ===== ##

    # Get the SNPs to query over specific day
    SNPs_df = joined_spike_count_df[joined_spike_count_df.AA_CHANGE.isin(aa_change_list)]
    SNPs_set = set(pair for pair in zip(SNPs_df.POS, SNPs_df.ALT))

    ## ===== Move through the BAM file and get haplotypes ===== ##

    # Save the haplotypes in a dictionary
    haplotype_dict = {}

    # Get the start and stop
    start = sorted([pos for pos, alt in SNPs_set])[0]
    stop = sorted([pos for pos, alt in SNPs_set])[-1]

    # Open alignment with pysam
    with pysam.AlignmentFile(filepath, "rb") as bamfile:

        # Get the pileup column for a specific region
        for pileupcolumn in bamfile.pileup(contig, start = start, stop = stop, stepper = 'nofilter'):

            # Check the if the position has a target SNP (converted to 0-indexed)
            if pileupcolumn.pos in [pos-1 for pos, alt in SNPs_set]:

                # Iterate over every alignment in the pileup column.
                for pileupread in pileupcolumn.pileups:

                    # Check if the read is valid and can be parsed
                    if check_read(pileupread.alignment) and not pileupread.is_del and not pileupread.is_refskip:

                        # Save the query name
                        qname = pileupread.alignment.query_name

                        # Save the 1-indexed position
                        pos = pileupcolumn.pos + 1

                        # Save the base at that position in the read
                        alt = pileupread.alignment.query_sequence[pileupread.query_position]

                        # Check if this read has the SNP or not
                        if (pos, alt) in SNPs_set:
                            phase = 1 # The read has the SNP

                        else:
                            phase = 0 # The read doesn't have the SNP

                        # Add the readname to the dictionary
                        if qname in haplotype_dict.keys():
                            haplotype_dict[qname].append((pos, phase, alt))
                        else:
                            haplotype_dict[qname] = [(pos, phase, alt)]

    ## ===== Convert the haplotype dictionary to a dataframe filling in missings ===== ##

    # Save the haplotypes with missing values (not covered by reads) filled
    completed_haplotype_dict = {}

    # Iterate over the haplotype dictionary created above
    for qname, alleles in haplotype_dict.items():

        # Make a dictionary to fill with observed SNPs for each read
        aa_dict = {tup:"-" for tup in SNPs_set}

        # Iterate over all observed alleles
        for allele in alleles:

            # If it's 1, then an allele was observed
            if allele[1] == 1:
                # Add this observation based on the key
                aa_dict[(allele[0], allele[2])] = 1
            # If it's a wild type allele
            elif allele[1] == 0:
                # Check every possible wt allele
                for key in aa_dict.keys():
                    # Check by position
                    if key[0] == allele[0]:
                        # If it's the same positon add a 0
                        aa_dict[key] = 0

        # Add this populated dictionary to the haplotype dictionary
        completed_haplotype_dict[qname] = aa_dict

    # Convert this dicitonary into a dataframe and take the transpose
    haplotype_df = pd.DataFrame(completed_haplotype_dict).T

    ## ===== Format the dataframe ===== ##

    # * FIX THE BUG WITH ALLELES IN SAME BASE *

    # Dict to format the column names
    aa_conversion = {pair:aa for pair, aa in zip(zip(SNPs_df.POS, SNPs_df.ALT),SNPs_df.AA_CHANGE)}

    # Flatten the column indicies
    haplotype_df.columns = [aa_conversion[(pos,alt)] for pos,alt in haplotype_df.columns.values]

    # Replace the '-' with 'NaN'
    haplotype_df = haplotype_df.replace('-', np.nan)

    # Return the phased SNP df
    return haplotype_df

## === Main === ##

# Input path to SNP df
inputpath_csv = str(snakemake.input.csv)
inputpath_bam = str(snakemake.input.bam)

# Output path to csv file
outpath = str(snakemake.output)

# Name of sample
accession = os.path.basename(inputpath_bam)

# Get the day of the sample
if accession.startswith("Day"):

    regex = re.compile("Day(?P<Day>\d+)_")
    m = regex.match(accession)
    day = int(m.group('Day'))

else:

   day = get_day(inputpath)

# Read in the join_calling df
input_snp_df = pd.read_csv(inputpath_csv)

# List of SNPs to phase
snp_list = ["N440D", "E484A", "F486I", "F486L", "Y489H", "Q493K"]

# Phase the SNPs
haplotypes_df = phase_variants(snp_list, input_snp_df, inputpath_bam, contig = "NC_045512.2")

# Add accession and day to data frame
haplotypes_df.insert(0, 'ACCESSION', accession)
haplotypes_df.insert(1, 'DAY', day)

# Write out the results
haplotypes_df.to_csv(outpath, index=False)


import json
import torch
import os

# load vocabulary
vocab_path = os.path.join("app", "saved_models", "vocab", "char2int_2.json")
with open(vocab_path, "r") as f:
    char2int = json.load(f)

int2char = {v: k for k, v in char2int.items()}

# define parameters
VOCAB_SIZE = len(int2char)
HIDDEN_SIZE = 512
N_LAYERS = 3
P_DROPOUT = 0.4
BATCH_FIRST = True
# PATH = os.path.join("app", "saved_models", "charRNN_questions_epoch_20.pt")
PATH = "C:/Users/feress/Documents/myprojects/Chat-response-suggestions/notebooks/response_sugg_v1/deep-autocomplete-master/backend/app/saved_models/char_rnn_epoch_20.pt"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


import numpy as np
import random
import copy

from baseEnv import HBDenv
from baseAgent import HBDagent

BOARD_SIZE = 6

class Pentago(HBDenv):
    def __init__(self, size, agents, history_file):

        self.size = size
        self.board = np.zeros((self.size, self.size), dtype = np.int)

        self.done = False
        self.agents = []
        self.winner = 0
        self.agents = agents
        self.file = open(history_file, 'w')

        for agent in self.agents:
            self.file.write(agent.__class__.__name__ + ' ')
        self.file.write('\n')
        self.file.write(self.logging() + '\n')

    def game_step(self):
        for i, agent in enumerate(self.agents):
            action = agent.step(copy.deepcopy(self.board))
            self.agent_step(i+1, action)
            if self.done == True:
                if self.winner:
                    self.file.write(f" {self.agents[self.winner-1].__class__.__name__} wins")
                else:
                    self.file.write("Its a draw &__& ")
                break

    def agent_step(self, agentID, action):
        x, y, quadrant, direction = action
        if not self.checkValidMove(x, y, quadrant, direction):
            #If the bot makes an invalid move, a random move is generated
            while True:
                x, y = random.randint(0,5), random.randint(0,5)
                quadrant = random.randint(1,4)
                direction = random.choice([1, -1])
                if self.checkValidMove(x, y, quadrant, direction):
                    break

        self.addPiece(x, y, agentID)
        self.rotate(quadrant, direction)

        self.file.write(self.logging() + '\n')
        self.GameOver()

    def addPiece(self, x, y, value):
        '''
            x is the X coordinate and y is the Y coordinate on the board.

            Value is the value to be placed on that position. The bot does not have to assaign any value here. It's turn based
        '''
        self.board[x,y] = value

    def rotate(self, quadrant, direction):
        '''
        quadrant:
            The board is divided into 4 quadrants - 1,2,3,4
            Each quadrant has 9 blocks annd is arranged in the manner: [1,2
                                                                        3,4]
        direction:
            It is the direction you want to rotate that particular quadrant
            1 = anticlockwise, -1 = clockwise
        '''
        if quadrant == 1:
            self.board[:3, :3] = np.rot90(self.board[:3, :3], direction)
        elif quadrant == 2:
            self.board[:3, 3:] = np.rot90(self.board[:3, 3:], direction)
        elif quadrant == 3:
            self.board[3:, :3] = np.rot90(self.board[3:, :3], direction)
        elif quadrant ==4:
            self.board[3:, 3:] = np.rot90(self.board[3:, 3:], direction)

    def checkValidMove(self, x, y, quadrant, direction):
        '''
            Checks whether the move suggested by the bot is valid or not
        '''
        if x < self.size and y < self.size and x >= 0 and y >= 0  and not self.board[x][y]:
            if quadrant in [1, 2, 3, 4] and direction in [1, -1]:
                return True
        return False

    def GameOver(self):
        '''
            Checks whether the game is over or not.
            It also specifies the winner of the game so that the result can be later stored in history
        '''
        if (len(set(np.diag(self.board)[:-1])) == 1 and np.diag(self.board)[0] != 0) or (len(set(np.diag(self.board)[1:])) == 1 and np.diag(self.board)[1] != 0):
            if np.diag(self.board)[1] == 1:
                self.winner = 1
                self.done = True

            elif np.diag(self.board)[1] == 2:
                self.winner = 2
                self.done = True
            return

        if (len(set(np.diag(np.fliplr(self.board))[:-1])) == 1 and np.diag(np.fliplr(self.board))[0] != 0) or (len(set(np.diag(np.fliplr(self.board))[1:])) == 1 and np.diag(self.board)[1] != 0):
            if np.diag(np.fliplr(self.board))[1] == 1:
                self.winner = 1
                self.done = True
            elif np.diag(np.fliplr(self.board))[1] == 2:
                self.winner = 2
                self.done = True
            return

        # Checking for other diagonals
        if (len(set(np.diag(self.board[:5, :5])[:])) == 1 and np.diag(self.board)[0] != 0):
            if np.diag(self.board[:5,:5])[1] == 1:
                self.winner = 1
                self.done = True

            elif np.diag(self.board)[1] == 2:
                self.winner = 2
                self.done = True
            return

        if (len(set(np.diag(self.board[1:, :5])[:])) == 1 and np.diag(self.board[1:, :5])[0] != 0):
            if np.diag(self.board[1:,:5])[1] == 1:
                self.winner = 1
                self.done = True

            elif np.diag(self.board[1:,:5])[1] == 2:
                self.winner = 2
                self.done = True
            return

        if (len(set(np.diag(np.fliplr(self.board[:5, 1:]))[:-1])) == 1 and np.diag(np.fliplr(self.board[:5, 1:]))[0] != 0):
            if np.diag(np.fliplr(self.board[:5, 1:]))[1] == 1:
                self.winner = 1
                self.done = True
            elif np.diag(np.fliplr(self.board[:5, 1:]))[1] == 2:
                self.winner = 2
                self.done = True
            return

        if (len(set(np.diag(np.fliplr(self.board[1:, 1:]))[:-1])) == 1 and np.diag(np.fliplr(self.board[1:, 1:]))[0] != 0):
            if np.diag(np.fliplr(self.board[1:, 1:]))[1] == 1:
                self.winner = 1
                self.done = True
            elif np.diag(np.fliplr(self.board[1:, 1:]))[1] == 2:
                self.winner = 2
                self.done = True
            return

        for i in range(6):
            if (len(set(self.board[i][:-1])) == 1 or len(set(self.board[i][1:])) == 1) and self.board[i][1] != 0:
                if self.board[i][1] == 1:
                    self.done = True
                    self.winner = 1
                    return

                elif self.board[i][1] == 2:
                    self.done = True
                    self.winner = 2
                    return

            if (len(set(self.board[:, i][:-1])) == 1 or len(set(self.board[:, i][1:])) == 1) and self.board[:, i][1] != 0:
                if self.board[:, i][1] == 1:
                    self.done = True
                    self.winner = 1
                    return

                elif self.board[:, i][1] == 2:
                    self.done = True
                    self.winner = 2
                    return

        if 0 not in self.board:
            self.done = True
            self.winner = None
            return

    def logging(self):
        '''
            logs the entire state of the game
        '''
        serialString =""
        for row in self.board:
            for value in row:
                serialString += str(value)
                serialString += ','
            #serialString += '\n'
        serialString = serialString[:-1]
        return serialString

class randomAgent(HBDagent):
    def __init__(self):
        pass
    def step(self, state):
        '''
            Input:
                state - It's a 2D array of the entire board at the current time

            This function should return :
                x - the x coordinate on the board
                y - the y coordinate on the board
                quadrant - the quadrant that the user wants to rotate
                            This is divided into 4 parts
                            1 - board[:3, :3]
                            2 - board[:3, 3:]
                            3 - board[3:, :3]
                            4 - board[3:, 3:]
                direction -  this is the direction in which the quadrant should rotate in
                            1 - anticlockwise
                           -1 - clockwise
        '''
        x, y = random.randint(0,5), random.randint(0,5)
        quadrant = random.randint(1,4)
        direction = random.choice([1, -1])

        return [x, y, quadrant, direction]

if __name__ == "__main__":
    env = Pentago(BOARD_SIZE,[randomAgent(), randomAgent()], 'history.hbd')
    while not env.done:
        env.game_step()


import sys
import json

writer_data = json.loads(sys.stdin.read())

def write():
     path = writer_data.get('path')
     mimetype = writer_data.get('mimetype', '')
     properties = writer_data.get('properties', '')

     output = open(path, 'w')
     output.write(json.dumps(properties))

     return_status = {}
     return_status['status'] = 'OK'
     return_status['error'] = ''

     print(json.dumps(return_status))

if __name__ == "__main__":
    write()


import json
import logging
import os
from collections import defaultdict
from typing import Dict, List, Tuple
from glob import glob

from pydantic import BaseModel, ValidationError

from data_types import CodeData, ForumData, ParallelData, QaData, MultiQaData, CommonData

class DataChecker:
    def __init__(self) -> None:
        self.type_list: List[BaseModel] = [QaData, CodeData, ForumData, ParallelData, CommonData]

    def read_head(self, dataset_path: str, k: int):
        with open(dataset_path, 'r', encoding='utf-8') as f:
            for idx, line in enumerate(f):
                if k is not None and k > 0 and idx >= k:
                    break
                yield json.loads(line)

    def get_keys(self, data: Dict, prefix='', depth=1, max_depth=1):
        if depth > max_depth:
            return []
        keys = []
        for key, value in data.items():
            if prefix:
                key = f"{prefix}.{key}"
            keys.append(key)
            if isinstance(value, dict):
                sub_keys = self.get_keys(value, prefix=key, depth=depth+1, max_depth=max_depth)
                keys = keys + sub_keys
        return set(keys)

    def get_data_type(self, data: Dict) -> Tuple[BaseModel, float]:
        type_cls = None
        for data_type in self.type_list:
            try:
                data_type(**data)
                type_cls = data_type
            except:
                continue

        if type_cls:
            return type_cls, 1.0

        keys = self.get_keys(data, depth=1)
        type_match_scores = []
        for data_type in self.type_list:
            type_keys = set(data_type.model_fields.keys())
            distance = len(type_keys - keys) + len(keys - type_keys)
            score = 1 - (distance / len((type_keys | keys)))
            type_match_scores.append((data_type, score))
        type_match_scores = sorted(type_match_scores, key=lambda x: x[1], reverse=True)
        type_cls, score = type_match_scores[0]
        if 'id' in data and isinstance(data['id'], str):
            type_cls = MultiQaData
        return type_cls, score

    def parser_errors(self, validation_error: ValidationError):
        error_map = defaultdict(set)
        for error in validation_error.errors():
            if isinstance(error['loc'], str):
                error_info = error['loc']
            else:
                error_info = '.'.join(filter(lambda x: isinstance(x, str), error['loc']))
            error_map[error['type']].add(error_info)
        errors = []
        for key, values in error_map.items():
            error_info = ", ".join(list(values)[:3])
            if len(values) >= 3:
                error_info += ', ...'
            if key == 'missing':
                errors.append(f'missing error, missing keys: [{error_info}]')
            elif 'type' in key:
                expected_type, _ = key.split('_')
                errors.append(f'type error, error keys: [{error_info}], expected type `{expected_type}`')
            else:
                errors.append(f'other error, error keys: [{error_info}], error info: {key}')
        return '; '.join(errors)

    def check_line(
        self,
        data: Dict,
        type_cls: BaseModel,
    ):
        try:
            type_cls(**data)
            return True, ''
        except ValidationError as e:
            error_info = self.parser_errors(e)
            return False, error_info

    def check_file(self, dataset_path: str, k: int):
        logger.info(f'checking dataset: {dataset_path}')
        dataset_name = os.path.basename(dataset_path)
        datasets = self.read_head(dataset_path, k)
        right_num_line = 0
        for idx, line_data in enumerate(datasets):
            if idx == 0:
                first = line_data
                type_cls, score = self.get_data_type(first)
                if score == 1.0:
                    logger.info(f"the type of dataset {dataset_name} is {type_cls.name()}")
                elif score > 0:
                    logger.warning(f"can not match data type, the most similar type of dataset {dataset_name} is {type_cls.name()}, similar score is {score:.4f}.")
                else:
                    logger.error("can not match any data type and can not find similar data type.")
            is_matched, info = self.check_line(line_data, type_cls)
            if not is_matched:
                logger.error(f" dataset {dataset_name} line {idx}: {info}")
            else:
                right_num_line += 1
        logger.info(f"check dataset {dataset_name} finished, right line {right_num_line} / total check line {idx + 1}")

    def check_folder(
        self,
        dataset_dir: str,
        k: int=10
    ):
        for file_path in sorted(glob(f"{dataset_dir}/*.json*")):
            if not os.path.isfile(file_path):
                continue
            self.check_file(file_path, k = k)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--dataset', type=str, required=True, help='dataset path or dataset dir')
    parser.add_argument('--k', type=int, required=False, help='check top k line of each file')
    args = parser.parse_args()

    fh = logging.FileHandler('logs/check_log.txt')
    fh.setLevel(logging.INFO)
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)

    logger = logging.getLogger(name='__checker__')
    logger.setLevel(logging.INFO)
    logger.addHandler(fh)
    if args.k:
        logger.addHandler(ch)

    dk = DataChecker()
    if os.path.isfile(args.dataset):
        dk.check_file(args.dataset, k=args.k)
    elif os.path.isdir(args.dataset):
        dk.check_folder(args.dataset, k=args.k)


# -*- encoding: utf-8 -*-
import pyaudio
import threading
from google.cloud import speech
from voicebot.utils.gcp_utils import get_credentials

CHUNK_SIZE = 1024
RATE = 16000
pyaudio_conf = {
    'format': pyaudio.paInt16,
    'channels': 1,
    'rate': RATE,
    'frames_per_buffer': CHUNK_SIZE,
    'input': True
}

def _init_stt_context():
    p = None
    def stt_init():
        nonlocal p
        p = pyaudio.PyAudio()
    def stt_stop():
        nonlocal p
        p.terminate()
    def recording_stream():
        nonlocal p
        return p.open(**pyaudio_conf)
    return (stt_init, stt_stop, recording_stream)

init, stop, get_recording_stream = _init_stt_context()

def is_enter_pressed(msg):
    t = None
    def _myinput():
        input(msg)
    def _is_enter_pressed():
        nonlocal t
        if t:
            if t.is_alive():
                return False
            else:
                t = None
                return True
        else:
            t = threading.Thread(target=_myinput)
            t.start()
            return False

    return _is_enter_pressed

def recording_message(is_recording):
    if is_recording:
        print('\nRecording started')
    else:
        print('\nRecording stopped')

def ready_message(is_prompting):
    if is_prompting:
        print('\nReady to start recording...', end='')

def record_voice(start_recording=is_enter_pressed('Press <Enter> to start...'), stop_recording=is_enter_pressed('Press <Enter> to stop...'), ready_prompt=ready_message, recording_prompt=recording_message):
    """
    The function to get the recorded voice.

    Arguments:
    start_recording -- the non-blocking function that returns True if the recorder can be started.
    stop_recording -- the non-blocking function that returns True if the recorder should be stopped.
    ready_prompt -- the function that prints the message when it is ready to record voice (when True)
    recording_prompt -- The function to show prompt message/indicator when recording (True) or when not recording (False)
    """
    ready_prompt(True)
    while not start_recording():
        pass
    ready_prompt(False)
    recording_prompt(True)
    stream = get_recording_stream()
    frames = []
    while not stop_recording():
        data = stream.read(CHUNK_SIZE)
        frames.append(data)
    stream.stop_stream()
    stream.close()
    recording_prompt(False)

    return b''.join(frames)

def google_stt(voice_data, lang='zh-tw'):
    audio = speech.RecognitionAudio(content=voice_data)
    config = speech.RecognitionConfig(
        encoding = speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz = RATE,
        language_code = lang,
        enable_automatic_punctuation = True
    )
    client = speech.SpeechClient(credentials=get_credentials('google-stt.json'))
    response = client.recognize(config=config, audio=audio)
    if len(response.results)==0:
        return ''
    else:
        return response.results[0].alternatives[0].transcript


from itertools import product

import numpy as np
import pandas as pd

# map JRC/our sectors to hotmaps sector, where mapping exist
sector_mapping = {
    "Electric arc": "Iron and steel",
    "Integrated steelworks": "Iron and steel",
    "DRI + Electric arc": "Iron and steel",
    "Ammonia": "Chemical industry",
    "Basic chemicals (without ammonia)": "Chemical industry",
    "Other chemicals": "Chemical industry",
    "Pharmaceutical products etc.": "Chemical industry",
    "Cement": "Cement",
    "Ceramics & other NMM": "Non-metallic mineral products",
    "Glass production": "Glass",
    "Pulp production": "Paper and printing",
    "Paper production": "Paper and printing",
    "Printing and media reproduction": "Paper and printing",
    "Alumina production": "Non-ferrous metals",
    "Aluminium - primary production": "Non-ferrous metals",
    "Aluminium - secondary production": "Non-ferrous metals",
    "Other non-ferrous metals": "Non-ferrous metals",
}

def build_nodal_industrial_energy_demand():
    fn = snakemake.input.industrial_energy_demand_per_country_today
    industrial_demand = pd.read_csv(fn, header=[0, 1], index_col=0)

    fn = snakemake.input.industrial_distribution_key
    keys = pd.read_csv(fn, index_col=0)
    keys["country"] = keys.index.str[:2]

    nodal_demand = pd.DataFrame(
        0.0, dtype=float, index=keys.index, columns=industrial_demand.index
    )

    countries = keys.country.unique()
    sectors = industrial_demand.columns.levels[1]

    for country, sector in product(countries, sectors):
        buses = keys.index[keys.country == country]
        mapping = sector_mapping.get(sector, "population")

        key = keys.loc[buses, mapping]
        demand = industrial_demand[country, sector]

        outer = pd.DataFrame(
            np.outer(key, demand), index=key.index, columns=demand.index
        )

        nodal_demand.loc[buses] += outer

    nodal_demand.index.name = "TWh/a"

    nodal_demand.to_csv(snakemake.output.industrial_energy_demand_per_node_today)

if __name__ == "__main__":
    if "snakemake" not in globals():
        from _helpers import mock_snakemake

        snakemake = mock_snakemake(
            "build_industrial_energy_demand_per_node_today",
            simpl="",
            clusters=48,
        )

    build_nodal_industrial_energy_demand()


import copy
import gym
import random
import numpy as np

from lib.rrt.rrt_continuous import run_rrt
from lib.environments.helpers.intersection_mujoco import *
from lib.environments.maze_generation.maze_generation import objects_from_occupancy

import xml.etree.ElementTree as ET

class GoalManagementMonitor:

    def __init__(self):
        self.start = None
        self.goal = None
        self.way_points_coarse = []
        self.way_points = []
        self.num_way_points = 0
        self.way_point_current = 0
        self.target_vec = None
        self.path_segment_len_list = None
        self.remaining_path_len_list = None
        self.waypoint_avail = None

    def reset(self, start, goal, grid):
        self.start = (start[0] / 4, start[1] / 4)
        self.goal = (goal[0] / 4, goal[1] / 4)

        path, rrt_success, _, _ = run_rrt(grid_world=grid,
                                          max_iter=1000,
                                          start_p=self.start,
                                          goal_p=self.goal,
                                          max_step_size=0.25,
                                          mode='ant')

        self.way_points_coarse = copy.deepcopy(path)
        path = [(element[0] * 4, element[1] * 4) for element in path]

        if not rrt_success:
            path = [start, goal]

        self.way_points = path
        self.num_way_points = len(path)
        self.way_point_current = 1
        self.waypoint_avail = np.ones((self.num_way_points, ))
        self.waypoint_avail[0] = 0
        self.target_vec = np.array(self.way_points[self.way_point_current]) - \
                          np.array(self.way_points[self.way_point_current - 1])

        self.path_segment_len_list = np.zeros((self.num_way_points - 1, ))
        for w in range(1, self.num_way_points):
            wp_dist = np.linalg.norm(np.array(self.way_points[w]) - np.array(self.way_points[w - 1]))
            self.path_segment_len_list[w - 1] = wp_dist
        self.remaining_path_len_list = np.zeros((self.num_way_points, ))
        for idx in reversed(range(self.num_way_points - 1)):
            self.remaining_path_len_list[idx] = self.remaining_path_len_list[idx + 1] + self.path_segment_len_list[idx]

        return self.path_segment_len_list

    def update_way_point(self, grid, curr_pos, success):

        if success:
            self.waypoint_avail[self.way_point_current] = 0
            if np.sum(self.waypoint_avail) > 0:
                self.way_point_current += 1
            grid.old_distance = np.linalg.norm(np.array(self.way_points[self.way_point_current]) - np.array(curr_pos))
            return True
        else:
            return False

    def get_target_vec(self, state):
        self.target_vec = np.array(self.way_points[self.way_point_current]) - state
        return self.target_vec

class Ant44Env0:
    def __init__(self, mj_ant_path,
                 waypoint=False,
                 re_init=False,
                 structure=None,
                 objects=None,
                 obstacle_list=None,
                 occupancy_map=None,
                 default_starts=None,
                 state_cache=None,
                 occupancy_map_padded=None,
                 occupancy_map_un_padded=None,
                 occupancy_map_original=None
                 ):
        self.env = gym.make('Ant-v2')
        self.start = (6.0, 18.0)
        self.goal = (14.0, 18.0)
        self.x_size = 24
        self.y_size = 24
        self.mj_ant_path = mj_ant_path

        self.visitation_map = np.zeros((self.x_size, self.y_size))
        self.rp_map = np.zeros((self.x_size, self.y_size))
        self.iter_count = 0

        if not re_init:

            # The following snippet is derived from rllab-curriculum
            #   (https://github.com/florensacc/rllab-curriculum)
            # Copyright (c) 2016 rllab contributors, licensed under the MIT license,
            # cf. 3rd-party-licenses.txt file in the root directory of this source tree.

            ant_path = self.mj_ant_path + 'ant.xml'
            tree = ET.parse(ant_path)
            tree.write(self.mj_ant_path + 'ant_copy.xml')

            ant_path = self.mj_ant_path + 'ant_copy.xml'
            tree = ET.parse(ant_path)
            worldbody = tree.find(".//worldbody")

            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 0, 1, 1, 1],
                [1, 0, 1, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]

            for i in range(len(structure)):
                for j in range(len(structure[0])):
                    if str(structure[i][j]) == '1':
                        # offset all coordinates so that coordinates start at 0
                        ET.SubElement(
                            worldbody, "geom",
                            name="block_%d_%d" % (i, j),
                            pos="%f %f %f" % (i * 4 + 2,
                                              j * 4 + 2,
                                              2),
                            size="%f %f %f" % (2,
                                               2,
                                               2),
                            type="box",
                            material="",
                            contype="1",
                            conaffinity="1",
                            rgba="0.4 0.4 0.4 0.5"
                        )

            root = tree.getroot()
            root[1].attrib["timestep"] = "0.02"

            tree.write(self.mj_ant_path + 'ant.xml')

            # End of snippet.

            self.structure = np.array(structure)
            self.obstacle_list = []
            for i in range(len(structure)):
                for j in range(len(structure[0])):
                    if str(structure[i][j]) == '1':
                        self.obstacle_list.append((i * 4 + 2, j * 4 + 2))

            self.occupancy_map = np.zeros((self.x_size, self.y_size))
            for i in range(6):
                for j in range(6):
                    if structure[i][j] == 1:
                        for inner_i in range(i * 4, min(i * 4 + 4, 24)):
                            for inner_j in range(j * 4, min(j * 4 + 4, 24)):
                                self.occupancy_map[inner_i, inner_j] = 1
            # print(self.occupancy_map)

            self.default_starts = []
            self.state_cache = np.zeros((self.x_size, self.y_size, 8))
            for x_coord in range(self.x_size):
                for y_coord in range(self.y_size):
                    if self.occupancy_map[x_coord][y_coord] == 0:
                        self.default_starts.append((x_coord, y_coord))
                        self.state_cache[x_coord, y_coord, :] = list(self.get_neighborhood((x_coord, y_coord)))

            # print(self.default_starts)

            self.occupancy_map_padded = \
                np.logical_not(np.pad(np.array(self.occupancy_map), 1, 'constant', constant_values=1)).astype(int)
            self.occupancy_map_un_padded = \
                np.logical_not(np.array(self.occupancy_map)).astype(int)
            self.occupancy_map_original = copy.deepcopy(self.occupancy_map)

            self.objects = objects_from_occupancy(self.structure)
            for obj_idx in range(len(self.objects)):
                at = self.objects[obj_idx][0] - 0.2
                bt = self.objects[obj_idx][1] - 0.2
                ct = self.objects[obj_idx][2] + 0.4
                dt = self.objects[obj_idx][3] + 0.4
                self.objects[obj_idx] = (at, bt, ct, dt)

            # print(self.objects)
        else:
            self.structure = structure
            self.objects = objects
            self.obstacle_list = obstacle_list
            self.occupancy_map = occupancy_map
            self.default_starts = default_starts
            self.state_cache = state_cache
            self.occupancy_map_padded = occupancy_map_padded
            self.occupancy_map_un_padded = occupancy_map_un_padded
            self.occupancy_map_original = occupancy_map_original

        if waypoint:
            self.goal_management = GoalManagementMonitor()
            self.old_distance = 0.

    def lls2hls(self, state, robust=False, old_state=None):
        hls = tuple([int(np.clip(state[0], 0, 23)), int(np.clip(state[1], 0, 23))])
        if robust:
            # if self.occupancy_map[hls[0], hls[1]]
            pass
        else:
            return hls

    def lls2hls4(self, state):
        return tuple([np.clip(int(state[0] / 4), 0, 5), np.clip(int(state[1] / 4), 0, 5)])

    def hls2lls(self, state):
        return float(state[0]), float(state[1])

    def reset_env_random(self, set_grid=False, grid_type=0):
        self.start = None
        self.goal = None
        self.x_size = 24
        self.y_size = 24

        if not set_grid:
            grid_type = random.randint(0, 24)
        if grid_type == 0:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 0, 1, 1, 1],
                [1, 0, 1, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 1:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 0, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 2:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 1, 1, 1, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 1, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 3:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 0, 0, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 4:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 0, 0, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 1, 1, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 5:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 0, 1, 1],
                [1, 1, 1, 0, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 6:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 0, 1],
                [1, 1, 1, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 7:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 8:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 9:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 10:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 1, 0, 0, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 1, 0, 0, 1, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 11:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 1, 1, 0, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 12:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 0, 0, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 13:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 1, 1, 1, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 14:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 15:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 16:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 17:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 1, 0, 1, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 18:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 0, 0, 1, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 19:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 1, 1, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 20:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 0, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 0, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 21:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 0, 0, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 22:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 0, 1, 1, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 23:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 0, 0, 1],
                [1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]
        elif grid_type == 24:
            structure = [
                [1, 1, 1, 1, 1, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 0, 1, 1, 0, 1],
                [1, 0, 1, 1, 0, 1],
                [1, 0, 0, 0, 0, 1],
                [1, 1, 1, 1, 1, 1],
            ]

        # The following snippet is derived from rllab-curriculum
        #   (https://github.com/florensacc/rllab-curriculum)
        # Copyright (c) 2016 rllab contributors, licensed under the MIT license,
        # cf. 3rd-party-licenses.txt file in the root directory of this source tree.

        ant_path = self.mj_ant_path + 'ant_copy.xml'
        tree = ET.parse(ant_path)
        worldbody = tree.find(".//worldbody")

        for i in range(len(structure)):
            for j in range(len(structure[0])):
                if str(structure[i][j]) == '1':
                    # offset all coordinates so that coordinates start at 0
                    ET.SubElement(
                        worldbody, "geom",
                        name="block_%d_%d" % (i, j),
                        pos="%f %f %f" % (i * 4 + 2,
                                          j * 4 + 2,
                                          2),
                        size="%f %f %f" % (2,
                                           2,
                                           2),
                        type="box",
                        material="",
                        contype="1",
                        conaffinity="1",
                        rgba="0.4 0.4 0.4 0.5"
                    )

        root = tree.getroot()
        root[1].attrib["timestep"] = "0.02"

        tree.write(self.mj_ant_path + 'ant.xml')

        # End of snippet.

        self.structure = np.array(structure)
        self.objects = objects_from_occupancy(self.structure)
        for obj_idx in range(len(self.objects)):
            at = self.objects[obj_idx][0] - 0.2
            bt = self.objects[obj_idx][1] - 0.2
            ct = self.objects[obj_idx][2] + 0.4
            dt = self.objects[obj_idx][3] + 0.4
            self.objects[obj_idx] = (at, bt, ct, dt)

        self.obstacle_list = []
        for i in range(len(structure)):
            for j in range(len(structure[0])):
                if str(structure[i][j]) == '1':
                    self.obstacle_list.append((i * 4 + 2, j * 4 + 2))

        self.occupancy_map = np.zeros((self.x_size, self.y_size))
        for i in range(6):
            for j in range(6):
                if structure[i][j] == 1:
                    for inner_i in range(i * 4, min(i * 4 + 4, 24)):
                        for inner_j in range(j * 4, min(j * 4 + 4, 24)):
                            self.occupancy_map[inner_i, inner_j] = 1
        # print(self.occupancy_map)

        self.visitation_map = np.zeros((self.x_size, self.y_size))
        self.rp_map = np.zeros((self.x_size, self.y_size))
        self.iter_count = 0

        self.default_starts = []
        self.state_cache = np.zeros((self.x_size, self.y_size, 8))
        for x_coord in range(self.x_size):
            for y_coord in range(self.y_size):
                if self.occupancy_map[x_coord][y_coord] == 0:
                    self.default_starts.append((x_coord, y_coord))
                    self.state_cache[x_coord, y_coord, :] = list(self.get_neighborhood((x_coord, y_coord)))

        # print(self.default_starts)

        self.occupancy_map_padded = \
            np.logical_not(np.pad(np.array(self.occupancy_map), 1, 'constant', constant_values=1)).astype(int)
        self.occupancy_map_un_padded = \
            np.logical_not(np.array(self.occupancy_map)).astype(int)
        self.occupancy_map_original = copy.deepcopy(self.occupancy_map)

        return self.structure, self.objects, self.obstacle_list, self.occupancy_map, self.default_starts, \
               self.state_cache, self.occupancy_map_padded, self.occupancy_map_un_padded, self.occupancy_map_original

    def observation(self):
        return np.concatenate([self.env.sim.data.qpos.flat, self.env.sim.data.qvel.flat, ]).reshape(-1)

    def reset(self, start):
        self.env.reset()
        qpos = self.env.data.qpos
        qpos[0] = start[0]
        qpos[1] = start[1]
        qvel = self.env.data.qvel
        self.env.set_state(qpos, qvel)
        return self.observation()

    def step(self, a, goal):
        _, _, _, _ = self.env.step(action=a)
        s_new = self.observation()
        reward = 0
        done = False
        goal_dist = np.linalg.norm(s_new[:2] - goal)
        if goal_dist < 0.5:
            reward = 1.0
            done = True
        return s_new, reward, done, dict(no_goal_reached=not done)

    def sample_random_pos(self, number):
        start_list = []
        while len(start_list) < number:
            x_coord = random.uniform(0.0, 24.0)
            y_coord = random.uniform(0.0, 24.0)
            admissible = True
            for obstacle in self.obstacle_list:
                if obstacle[0] - 2.75 < x_coord < obstacle[0] + 2.75 and \
                        obstacle[1] - 2.75 < y_coord < obstacle[1] + 2.75:
                    admissible = False
            if admissible:
                start_list.append((x_coord, y_coord))
        return start_list

    def check_collision(self, line_seg):
        collision_total = False
        obj = 0
        coll_obj = []
        coll_seg_list = []
        for obstacles in self.objects:
            collision, coll_seg = check_intersection_object(geom_object=obstacles, line_seg=line_seg)
            if collision:
                coll_obj.append(obj)
                coll_seg_list.append(coll_seg)
            collision_total = collision_total or collision
            obj += 1
        return not collision_total, coll_obj, coll_seg_list

    def get_occupancy(self, s_in):
        if 0 <= s_in[0] < self.x_size and 0 <= s_in[1] < self.y_size:
            return self.occupancy_map[s_in[0], s_in[1]]
        else:
            return 1

    def get_neighborhood(self, state):

        return self.get_occupancy(s_in=(state[0]-1, state[1]+1)), self.get_occupancy(s_in=(state[0], state[1]+1)), \
               self.get_occupancy(s_in=(state[0]+1, state[1]+1)), self.get_occupancy(s_in=(state[0]-1, state[1])), \
               self.get_occupancy(s_in=(state[0]+1, state[1])), self.get_occupancy(s_in=(state[0]-1, state[1]-1)), \
               self.get_occupancy(s_in=(state[0], state[1]-1)), self.get_occupancy(s_in=(state[0]+1, state[1]-1))


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

"""
    Provide command line analysis and verification
"""

import argparse
import os

def read_args(args):
    """ Read cli argument """

    parser = __create_parser()
    arg = vars(parser.parse_args(args))

    return arg

def __create_parser():
    """ Create the args parser """

    parser = argparse.ArgumentParser(
        usage       = "./%(prog)s [-h] [--example] [--c '#'] [-b '@export'] [-m '<TAG2INCLUDE>'] [--tagname '@name'] [--tagdesc '@title'] -i DIRECTORY \n",
        description = "Automatic update of documentation for R scripts",
        formatter_class = argparse.ArgumentDefaultsHelpFormatter
    )

    parser.add_argument("--example", action = "store_true", help = "Run example")
    parser.add_argument("--comment", default = "#\'", help = "define comment symbol")
    parser.add_argument("-i", type = __isdir, required = True,
        help = "Directory where the files to update are located")
    parser.add_argument("-b", "--block", default = "@export",
        help = "tag for filtering comment blocks to insert")
    parser.add_argument("-m", "--main", default = "<TAG2INCLUDE>",
        help = "tag for finding the main comment block where the --blocks will be inserted")
    parser.add_argument("--tagname", default = "@name",
        help = "in a bloc, tag to identify function name")
    parser.add_argument("--tagdesc", default = "@title",
        help = "in a bloc, tag to identify function desc")
    return parser

def __isfile(val):
    """Check  if the path is leading to a file."""
    val = str(val)

    if not os.path.isfile(val):
        raise argparse.ArgumentTypeError(val + " is not a file")

    return val

def __isdir(val):
    """Check  if the path is leading to a directory."""
    val = str(val)

    if not os.path.isdir(val):
        raise argparse.ArgumentTypeError(val + " is not a directory")

    return val


import random

#set user and computer initial scores to zero
user_wins = 0
comp_wins = 0

#create array of options for game
options = ["rock", "paper", "scissors"]

#start game
while True:
    #have user pick rock, paper, scissors or quit the game
    user_input = input("Pick Rock, Paper, Scissors or Q to quit.   ").lower()
    #if user picks q quit the game
    if user_input == "q":
        break
    #continue if not q
    if user_input not in options:
        continue
    #have the computer generate random number between 0 and 2
    random_number = random.randint(0,2)
    #0: rock, 1: paper, 2: scissors
    #have computer pick go from number to rock, paper, or scissors
    comp_pick = options[random_number]
    print("Computer picked: ", comp_pick)

    #check the different winning scenarios and +1 to count for each win
    if user_input == "rock" and comp_pick == "scissors":
        print('You won!')
        user_wins += 1

    if user_input == "paper" and comp_pick == "rock":
        print('You won!')
        user_wins += 1

    if user_input == "scissors" and comp_pick == "paper":
        print('You won!')
        user_wins += 1
    #if none of the winning scenarios are true then you lost the round. Add 1 to computer score each
    #time user loses
    else:
        print("You lost")
        comp_wins += 1
#When user quits the game print out the final scores
print("You won ", user_wins, "times. Computer won", comp_wins, "times.")


from random import choice, shuffle
n1 = str(input('Primeiro aluno: '))
n2 = str(input('Segundo aluno: '))
n3 = str(input('Terceiro aluno: '))
n4 = str(input('Quarto aluno: '))
lista = [n1, n2, n3, n4]
e = choice(lista)
shuffle(lista)
print('A ordem de apresentação será {}, {}, {}, {}'.format(lista[0], lista[1], lista[2], lista[3]))


import cv2
import numpy as np
from config import *

img1 = cv2.imread(PATH_ACTUAL)
img2 = cv2.imread(PATH_PLANOGRAM)

img1 = cv2.resize(img1, (1920, 1440))
img2 = cv2.resize(img2, (1920, 1440))

#ORB Detector
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)

#Brute Force
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck = True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x:x.distance)

matching_result = cv2.drawMatches(img1, kp1, img2, kp2, matches[:50], None)

# cv2.imshow("img1",img1)
# cv2.imshow("img2",img2)
cv2.imshow("matching result", cv2.resize(matching_result, None, fx=0.4, fy=0.4))
cv2.imwrite("../output/ORB_TOP_50_MATCHES.png", matching_result)
cv2.waitKey(0)


import datetime as dt
from typing import Callable
from typing import Optional

import click
import pytz
from click.core import Context as ClickContext
from click.core import Parameter as ClickParameter

from suncal.models.astro import Event

class IANATimeZoneString(click.ParamType):
    name = "IANATimeZoneString"

    def convert(
        self,
        value: str,
        param: Optional[ClickParameter],
        ctx: Optional[ClickContext],
    ):

        iana_timezones = pytz.all_timezones
        iana_timezones_lower = [timezone.lower() for timezone in iana_timezones]

        try:
            idx = iana_timezones_lower.index(value.lower())
            return iana_timezones[idx]

        except ValueError:
            self.fail(
                f"{value!r} is not a valid IANA time zone string!", param, ctx
            )

class ClickDate(click.ParamType):
    name = "Date"

    def convert(
        self,
        value: str,
        param: Optional[ClickParameter],
        ctx: Optional[ClickContext],
    ):

        try:
            return dt.datetime.strptime(value, '%Y-%m-%d').date()

        except ValueError:
            self.fail(
                f"{value!r} could not be parsed to a date. Required input format is '%Y-%m-%d'!",
                param,
                ctx,
            )

def common_suncal_options(function: Callable) -> Callable:
    """Create decorator for click sub-commands that holds all options that are common to the
    api and ics subcommands."""

    function = click.option(
        "--from",
        "from_date",
        type=ClickDate(),
        help="First date for which to create events.",
        required=True,
    )(function)

    function = click.option(
        "--to",
        "to_date",
        type=ClickDate(),
        help="Last date for which to create events.",
        required=True,
    )(function)

    function = click.option(
        "--event",
        "event_name",
        type=click.Choice([e.value for e in list(Event)], case_sensitive=False),
        required=True,
        help="Sun/Moon parameter for which to create calendar events.",
    )(function)

    function = click.option(
        "--long",
        "longitude",
        type=click.FloatRange(min=-180.0, max=180.0),
        help="Longitude as float.",
        required=True,
    )(function)

    function = click.option(
        "--lat",
        "latitude",
        type=click.FloatRange(min=-90.0, max=90.0),
        help="Latitude as float.",
        required=True,
    )(function)

    function = click.option(
        "--timezone",
        "timezone",
        type=IANATimeZoneString(),
        help="IANA timezone string. Only provide this argument if you want to override the timezone which is set "
        "according to your GPS coordinates automatically. Case-insensitive matching enabled.",
        required=False,
    )(function)

    function = click.option('--dev/--no-dev', 'dev_mode', default=False)(
        function
    )

    return function


# 10001st prime
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

# What is the 10 001st prime number?

# BRUTE FORCE
def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
            break
    return True

c = 0
for i in range(2, 120000):
    if is_prime(i):
        c += 1
        print(c, ': ', i)
        if c == 10001:
            print(c, ':', i)
            break

#ELEGENT

import itertools
def erat2( ):
    D = {  }
    yield 2
    for q in itertools.islice(itertools.count(3), 0, None, 2):
        p = D.pop(q, None)
        if p is None:
            D[q*q] = q
            yield q
        else:
            x = p + q
            while x in D or not (x&1):
                x += p
            D[x] = p

def get_primes_erat(n):
  return list(itertools.takewhile(lambda p: p<n, erat2()))

res = get_primes_erat(104749)
print(len(res))


import json
import boto3
from boto3.dynamodb.types import TypeDeserializer, TypeSerializer

dynamodb = boto3.client('dynamodb')

# Define a custom deserializer to convert DynamoDB items to Python dictionaries
deserializer = TypeDeserializer()

# Define a custom serializer to convert Python dictionaries to DynamoDB items
serializer = TypeSerializer()

def create_conversation(conversation):
    response = dynamodb.put_item(
        TableName='chats',
        Item={
            'conversation_id': serializer.serialize(conversation['conversation_id']),
            'messages': serializer.serialize(conversation['messages'])
        }
    )
    return response

def update_conversation(conversation):
    response = dynamodb.update_item(
        TableName='chats',
        Key={
            'conversation_id': serializer.serialize(conversation['conversation_id'])
        },
        UpdateExpression='SET messages = :messages',
        ExpressionAttributeValues={
            ':messages': serializer.serialize(conversation['messages'])
        }
    )
    return response

def get_conversation(conversation_id):
    response = dynamodb.get_item(
        TableName='chats',
        Key={
            'conversation_id': serializer.serialize(conversation_id)
        }
    )
    item = response.get('Item')
    if item:
        return {
            'conversation_id': deserializer.deserialize(item['conversation_id']),
            'messages': deserializer.deserialize(item['messages'])
        }
    return None


import sublime
import sublime_plugin
import os.path
import platform

def compare_file_names(x, y):
    if platform.system() == 'Windows' or platform.system() == 'Darwin':
        return x.lower() == y.lower()
    else:
        return x == y

class MySwitchFileCommand(sublime_plugin.WindowCommand):
    def run(self, extensions=[]):
        if not self.window.active_view():
            return

        fname = self.window.active_view().file_name()
        if not fname:
            return

        pData = sublime.active_window().project_data()
        if pData is not None:
            file = ProjectSearch(pData, fname, extensions)
        else:
            file = DefaultSearch(fname, extensions)

        if file is not None:
            OpenFile(file)

def SearchFolder(searchFolder, fname, extensions):
    ext = ExtractSearchExtensions(extensions, fname)
    base, _ = os.path.splitext(fname)
    filename = os.path.basename(base)

    if not os.path.isabs(searchFolder):
        pfn = sublime.active_window().project_file_name()

        if pfn is None:
            return None

        projectPath = os.path.dirname(pfn)
        searchFolder = os.path.join(projectPath, searchFolder)

    for root, dirs, files in os.walk(searchFolder):
        for e in ext:
            newFile = root + "\\" + filename + "." + e
            if os.path.exists(newFile):
                return newFile

    return None

def ExtractSearchExtensions(extensions, fname):
    base, ext = os.path.splitext(fname)
    ext = ext[1:]
    return [e for e in extensions if e != ext]

def ProjectSearch(projectData, fname, extensions):
    paths = [f["path"] for f in projectData["folders"]]
    for p in paths:
        match = SearchFolder(p, fname, extensions)
        if match is not None:
            return match

    return None

def DefaultSearch(fname, extensions):
    base = os.path.dirname(fname)
    return SearchFolder(base, fname, extensions)

def OpenFile(fname):
    windows = sublime.windows()
    for w in windows:
        view = w.find_open_file(fname)
        if view is not None:
            w.focus_view(view)
            if w != sublime.active_window():
                # Hack to get focus on other window
                # https://github.com/SublimeTextIssues/Core/issues/444
                w.run_command("focus_neighboring_group")
                w.focus_view(view)

    sublime.active_window().open_file(fname)


# 提取文件中的所有单词和标签
from instence import *
class Read_inst:
    def read(self, path):
        sentence = []
        # f = open('D:\\classifier\\data\\raw.clean.dev', encoding="UTF-8")
        f = open(path, encoding="UTF-8")
        for line in f.readlines():
            m_1 = inst()
            x = line.strip().split('|||')
            m_1.m_word = x[0].strip().split(' ')
            m_1.m_label = x[1].strip()
            sentence.append(m_1)
        f.close()
        return sentence


from flask import Flask
from .s3_obj_upload.basic.views import basic
from .s3_obj_upload.form_data.views import form_data
from .s3_obj_upload.pre_signed_url.views import pre_signed_url

app = Flask(__name__)

app.register_blueprint(basic)
app.register_blueprint(form_data)
app.register_blueprint(pre_signed_url)

@app.before_request
def before_request():
    return

@app.after_request
def after_request(response):
    print(f'response: {response}')
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = ['POST']
    return response

@app.route('/', methods=['GET'])
def main():
    return 'main'


'''

'''

def gcd(a,b):
    return a if b==0 else gcd(b,a%b)

def gcdall(a):
    b = a[0]
    for i in range(1,len(a)):
        b = gcd(b,a[i])
    return b

def fun(a):
    if(gcdall(a)>1):
        return 0
    else:
        m = max(a)
        ans = -1
        for i in range(1,m+1):
            if(gcdall(a+[i])>1):
                ans = i
                break
        if(ans==-1):
            return -1
        else:
            return 1+fun(a+[i])

for _ in range(int(input())):
    n = int(input())
    l = [int(x) for x in input().split()]
    print(fun(l))


# remove noise from image

import cv2 as cv
import numpy as np

img = cv.imread('face_with_noise.png')
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
_, mask = cv.threshold(img_gray, 100, 255, cv.THRESH_BINARY)
mask_dilated = cv.dilate(mask, None, iterations=6)
background_mean = cv.mean(img, cv.bitwise_not(mask_dilated))
print(background_mean)
background = np.full(img.shape, background_mean[0:3], dtype=np.uint8)
mask_eroded = cv.erode(mask, None, iterations=3)
mask_eroded_dilated = cv.dilate(mask_eroded, None, iterations=6)
mask_eroded_dilated_not = cv.bitwise_not(mask_eroded_dilated)
face = cv.bitwise_and(img, img, mask=mask_eroded_dilated)
not_face = cv.bitwise_and(background, background, mask=mask_eroded_dilated_not)
img_without_noise = cv.add(face, not_face)

face_without_noise = cv.imread('face_without_noise.png')
print('Success =', np.array_equal(img_without_noise, face_without_noise))

face_mask = cv.bitwise_and(mask, mask_eroded_dilated)

cv.imshow('img', img)
cv.imshow('img_gray', img_gray)
cv.imshow('mask', mask)
cv.imshow('mask_eroded', mask_eroded)
cv.imshow('mask_eroded_dilated', mask_eroded_dilated)
cv.imshow('mask_eroded_dilated_not', mask_eroded_dilated_not)
cv.imshow('face', face)
cv.imshow('not_face', not_face)
cv.imshow('img_wighout_noise', img_without_noise)
cv.imshow('face_mask', face_mask)
cv.waitKey()


from tkinter import *
import random
from functools import partial

root = Tk()

root.title("Yahtzee")

# Variables Start

roll = 0

dicenames = ["one", "two", "three", "four", "five"]

dicenumbers = [0,0,0,0,0]

diceclicked = [1,1,1,1,1]

score = 0

def click(n):
    diceclicked[n] = diceclicked[n] + 1
    if (diceclicked[n] % 2) == 0:
        dicenames[n].configure(background="red", activebackground="red")
    else:
        dicenames[n].configure(background="black", activebackground="black")

for i in range(5):
    dicenames[i] = Button(root, state="normal", relief="raised", text=dicenumbers[i], padx=15, pady=15, command=partial(click, i))
    dicenames[i].grid(row=10, column=i)

root.mainloop()


"""Calculate the inference of a CNN model in ONNX format with the self defined
functions."""

import math

from fpbinary import FpBinary
import numpy as np
import onnx
from onnx import numpy_helper

from common import NotSupportedError
import cnn_reference
from cnn_onnx import model_zoo, parse_param
from fp_helper import to_fixed_point_array

def numpy_inference(onnx_model, input_):
    """Calculate the inference of a given input with a given model."""
    weights_dict = {}
    for init in onnx_model.graph.initializer:
        weights_dict[init.name] = numpy_helper.to_array(init)

    next_input = input_
    for node in onnx_model.graph.node:
        params = parse_param.parse_node_attributes(node)

        if node.op_type == "Conv":
            raise NotSupportedError(f"Layer {node.op_type} not supported.")
        if node.op_type == "QLinearConv":
            pad = parse_param.get_pad(params)
            if pad:
                next_input = cnn_reference.zero_pad(next_input, pad)

            ksize, stride = parse_param.get_kernel_params(params)

            int_bits_weights = 8 - int(math.log2(weights_dict[node.input[4]]))
            frac_bits_weights = int(math.log2(weights_dict[node.input[4]]))
            weights = to_fixed_point_array(
                weights_dict[node.input[3]], int_bits=int_bits_weights,
                frac_bits=frac_bits_weights)
            bias = to_fixed_point_array(
                weights_dict[node.input[8]], int_bits=int_bits_weights,
                frac_bits=frac_bits_weights)

            bitwidth_out = (
                8 - int(math.log2(weights_dict[node.input[6]])),
                int(math.log2(weights_dict[node.input[6]])),
            )
            next_input = cnn_reference.conv(
                next_input, weights, bias, (ksize, stride), bitwidth_out)
        elif node.op_type == "MaxPool":
            ksize, stride = parse_param.get_kernel_params(params)
            next_input = cnn_reference.max_pool(next_input, ksize, stride)
        elif node.op_type == "GlobalAveragePool":
            next_input = cnn_reference.avg_pool(next_input)
        elif node.op_type == "Relu":
            next_input = cnn_reference.relu(next_input)
        elif node.op_type == "LeakyRelu":
            next_input = cnn_reference.leaky_relu(
                next_input, FpBinary(int_bits=0, frac_bits=3, value=0.125))
    return next_input

if __name__ == "__main__":
    # save arbitrary cnn model to file in onnx format
    MODEL_DEF = model_zoo.conv_3x1_1x1_max_2x2()
    onnx.save(MODEL_DEF, MODEL_DEF.graph.name + ".onnx")

    # load model and calculate inference
    MODEL = onnx.load(MODEL_DEF.graph.name + ".onnx")
    onnx.checker.check_model(MODEL)
    SHAPE = parse_param.parse_param(MODEL)
    OUTPUT = numpy_inference(
        MODEL, np.random.randint(256, size=SHAPE).astype(np.uint8))


import os

CXX_TYPES = (".c",".cpp",".cxx",".h",".hpp",".hxx")

def walk_dir(a_dir, types):
	temp = []
	for root, dirs, files in os.walk(a_dir):
		for file in files:
			if file.endswith(types):
				path = os.path.join(root, file)
				norm = os.path.normpath(path)
				slash = norm.replace("\\", "/")
				temp.append(slash)

	temp.sort()
	return temp

def make_cmake(a_dir):
	cxx = walk_dir(a_dir, CXX_TYPES)
	out = open(os.path.join("etc", "cmake", "source-list.cmake"), "w")
	out.write("set(CXX_FILES\n")
	for source in cxx:
		out.write(f"\t{source}\n")
	out.write(")\n")

def main():
	cur = os.path.dirname(os.path.realpath(__file__))
	os.chdir(cur + "/../..")
	make_cmake("src")

if __name__ == "__main__":
	main()


#! -*- coding: utf8 -*-

from Graph import *
from TPGenerator import *

g = 'DAG'
path = r"D:\Workspace\python3\tpGenerator\test"
file_name = "test"
exe_name = "ttest.exe"
gener = TPGenerator()
gener.GenerateTP(path, file_name, exe_name, g, node_num=100, edge_num=500)


import logging

def init_logging(level = logging.ERROR):
  # create logger with 'spam_application'
  logger = logging.getLogger('clyde2')
  logger.setLevel(logging.INFO)
  # create file handler which logs even debug messages
  fh = logging.FileHandler('clyde2.log')
  fh.setLevel(logging.DEBUG)
  # create console handler with a higher log level
  ch = logging.StreamHandler()
  ch.setLevel(level)
  # create formatter and add it to the handlers
  formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  plain_formatter = logging.Formatter('%(message)s')
  fh.setFormatter(formatter)
  ch.setFormatter(plain_formatter)
  # add the handlers to the logger
  logger.addHandler(fh)
  logger.addHandler(ch)

def get_logger():
  return logging.getLogger('clyde2')


# Напишите программу вычисления арифметического выражения заданного строкой. Используйте операции +,-,/,*.
# приоритет операций стандартный.

def Calc(str1):
    string = str1.split()
    for i in range(len(string)):
        if string[i].isdigit():
            string[i] = int(string[i])
    pr1 = {'*': lambda x, y: x * y,
            '/': lambda x, y: x / y,}
    pr2 = {'+': lambda x, y: x + y,
            '-': lambda x, y: x - y,}
    j = 0
    while ('*' in string) or ('/' in string):
        if string[j] in pr1:
            temp = pr1[string[j]](string[j - 1], string[j + 1])
            del string[j - 1 : j + 2]
            string.insert(j - 1, temp)
            j = 0
        else:
            j += 1
    j = 0
    while ('+' in string) or ('-' in string):
        if string[j] in pr2:
            temp = pr2[string[j]](string[j - 1], string[j + 1])
            del string[j - 1 : j + 2]
            string.insert(j - 1, temp)
            j = 0
        else:
            j += 1
    print(*string)
Calc('1 - 2 * 3')

# Дана последовательность чисел. Получить список уникальных элементов заданной последовательности.
# Пример:
# [1, 2, 3, 5, 1, 5, 3, 10] => [2, 10]

def UniqSearch(List1):
    someDict = {}
    someList = []
    for i in List1:
        if i not in someDict:
            someDict[i] = 1
        else:
            someDict[i] += 1
    for key, val in someDict.items():
        if val == 1:
            someList.append(key)
    return someList

print(UniqSearch([1, 2, 3, 5, 1, 5, 3, 10]))


x=int(input("On a scale of 1 to 10, how do you feel today, with 10 being the highest?"))
if x<=3:
    input("Why? What's wrong?")
    print("I feel you! You will be better soon!")
elif x>3 and x<=5:
    print("Pretty average, eh?")
elif x>5 and x<8:
    print("All right! You can feel better!")
elif x>=8 and x<=10:
    print("AYY! Have a great day!")

Class XI- Python Programs/Feeling Chatbot.py