#!/usr/bin/env python3

import os, sys, tarfile

def parcours(repertoire, tarliste) :
    if (repertoire[-1:] == '/' and repertoire[-2:] == '\\') :
        repertoire = repertoire[:-1];

    liste = os.listdir(repertoire)
    for fichier in liste :
        if os.path.isdir(repertoire+"/"+fichier) :
            parcours(repertoire+"/"+fichier, tarliste)
        if os.path.isfile(repertoire+"/"+fichier) :
            os.system("./huf "+repertoire+"/"+fichier+" "+fichier+".huff"+" >> /dev/null")
            tarliste.append(fichier+".huff")

if (len(sys.argv) != 3) :
    print("Format : ", sys.argv[0], " [directory] [output]")
else :
    tarliste = [];
    parcours(sys.argv[1], tarliste)
    tar = tarfile.open(sys.argv[2]+".tar.gz", "w:gz")
    for file in tarliste :
        tar.add(file);
        os.remove(file)
    tar.close()


#!/usr/bin/python3
# 提交到codeup报错，在pat上面是正确的
import sys

while True:
    str = sys.stdin.readline()
    if not str:
        break
    N = len(str) - 1
    n1 = (N+2) // 3
    n2 = N+2 - 2*n1
    mid_apd = n2 - 2
    for i in range(n1-1):
        print(str[i] + ' '*mid_apd + str[N-1 - i])
    print(str[n1-1:n1+n2-1])


# Taller 8
#
# Presentado por:
#       Juan Pablo Vidal C.
#       Alejandro Murillo G.
#

print("Presentado por:\n\tJuan Pablo Vidal C.\n\tAlejandro Murillo G.")

# --- Stack ----------------------------------------------------------

stack = []
stack.append(1)
stack.append(2)
stack.append(3)

stack2 = []
while len(stack) > 0:
    stack2.append(stack.pop())

print("\n--- Punto 1 ---")
print(stack2)

# --- Queue ----------------------------------------------------------

from collections import deque

queue = deque([])
queue.append("Juan")
queue.append("Maria")
queue.append("Pedro")

print("\n--- Punto 2 ---")
while len(queue) > 0:
    print("Atendiendo a: " + queue.popleft())

# --- Punto 3 --------------------------------------------------------

stackCalculator = []

operations = str(input("Ingrese la cadena (dentro de comillas) de operaciones en Notacion Polaca: "))

for c in operations:
    stackCalculator.append(c)

while len(stackCalculator) > 0:
    b = stackCalculator.pop()
    a = stackCalculator.pop()
    operation = str(a) + stackCalculator.pop() + str(b)
    stackCalculator.append(eval(operation))
    if (len(stackCalculator) == 1):
        print(stackCalculator.pop())


from pymongo import MongoClient
import yahoo_fin.stock_info as si
import pandas as pd

class StockInfoCollector:
    def __init__(self, stock_list):
        # Making a Connection with MongoClient
        self.client = MongoClient("mongodb://localhost:27017/")
        self.db = self.client["stocks_database"]
        self.stock_list = stock_list

    def collect_balance_sheet(self):
        dow_stats = {}
        collection = self.db["company_balancesheets"]
        for ticker in self.stock_list:
            try:
                # get the balance sheet
                balance_sheet = si.get_balance_sheet(ticker)
                balance_sheet = balance_sheet.transpose()
                balance_sheet.reset_index(inplace=True)
                # transposed["ticker"] = ticker
                balance_sheet.insert(loc=0, column='ticker', value=[ticker for _ in range(balance_sheet.shape[0])])
                data_dict = balance_sheet.to_dict("records")
                collection.insert_many(data_dict)
            except Exception as e:
                print(f'failed to get balance sheet due to  {e}')

    def retrieve_balance_sheet(self, ticker):
        # extract data from mongo db
        collection = self.db["company_balancesheets"]
        data_from_db = collection.find({"ticker": ticker})
        df = pd.DataFrame(data_from_db)
        return df

    def delete_balance_sheet(self, ticker=None):
        collection = self.db["company_balancesheets"]
        if (ticker):
            collection.delete_many({{"ticker": ticker}})
        else:
            # extract data from mongo db
            collection.drop()

    def collect_income_statement(self):
        collection = self.db["company_incomestatements"]
        for ticker in self.stock_list:
            try:
                # get the income statement
                income_statement = si.get_income_statement(ticker)
                transposed = income_statement.transpose()
                transposed.reset_index(inplace=True)
                # transposed["ticker"] = ticker
                transposed.insert(loc=0, column='ticker', value=[ticker for _ in range(transposed.shape[0])])
                data_dict = transposed.to_dict("records")
                collection.insert_many(data_dict)
            except Exception as e:
                print(f'failed to get income statement due to  {e}')

    def retrieve_income_statement(self, ticker):
        # extract data from mongo db
        collection = self.db["company_incomestatements"]
        data_from_db = collection.find({"ticker": ticker})
        df = pd.DataFrame(data_from_db)
        return df

    def delete_income_statement(self, ticker=None):
        collection = self.db["company_incomestatements"]
        if (ticker):
            collection.delete_many({{"ticker": ticker}})
        else:
            # extract data from mongo db
            collection.drop()

    def collect_cashflow_statement(self):
        collection = self.db["company_cashflowstatements"]
        for ticker in self.stock_list:
            try :
                # get the cashflow statement
                cashflow_statement = si.get_cash_flow(ticker)
                cashflow_statement = cashflow_statement.transpose()
                cashflow_statement.reset_index(inplace=True)
                cashflow_statement.insert(loc=0, column='ticker',
                                        value=[ticker for _ in range(cashflow_statement.shape[0])])
                data_dict = cashflow_statement.to_dict("records")
                # insert into mongodb
                collection.insert_many(data_dict)
            except Exception as e:
                print(f'failed to get cashflow statement due to  {e}')

    def retrieve_cashflow_statement(self, ticker):
        # extract data from mongo db
        collection = self.db["company_cashflowstatements"]
        data_from_db = collection.find({"ticker": ticker})
        df = pd.DataFrame(data_from_db)
        return df

    def delete_cashflow_statement(self, ticker=None):
        collection = self.db["company_cashflowstatements"]
        if (ticker):
            collection.delete_many({{"ticker": ticker}})
        else:
            # extract data from mongo db
            collection.drop()


import pytest
import shutil
import numpy as np
from concrete.compiler import (
    LibrarySupport,
    PublicArguments,
    SimulatedValueExporter,
    SimulatedValueDecrypter,
    CompilationOptions,
)

def assert_result(result, expected_result):
    """Assert that result and expected result are equal.

    result and expected_result can be integers on numpy arrays.
    """
    assert type(expected_result) == type(result)
    if isinstance(expected_result, int):
        assert result == expected_result
    else:
        assert np.all(result == expected_result)

def run_simulated(engine, args_and_shape, compilation_result):
    client_parameters = engine.load_client_parameters(compilation_result)
    sim_value_exporter = SimulatedValueExporter.new(client_parameters)
    values = []
    pos = 0
    for arg, shape in args_and_shape:
        if shape is None:
            assert isinstance(arg, int)
            values.append(sim_value_exporter.export_scalar(pos, arg))
        else:
            assert isinstance(arg, list)
            assert isinstance(shape, list)
            values.append(sim_value_exporter.export_tensor(pos, arg, shape))
        pos += 1
    public_arguments = PublicArguments.new(client_parameters, values)
    server_lambda = engine.load_server_lambda(compilation_result)
    public_result = engine.simulate(server_lambda, public_arguments)
    sim_value_decrypter = SimulatedValueDecrypter.new(client_parameters)
    result = sim_value_decrypter.decrypt(0, public_result.get_value(0))
    return result

def compile_run_assert(
    engine,
    mlir_input,
    args_and_shape,
    expected_result,
    options=CompilationOptions.new("main"),
):
    # compile with simulation
    options.simulation(True)
    compilation_result = engine.compile(mlir_input, options)
    result = run_simulated(engine, args_and_shape, compilation_result)
    assert_result(result, expected_result)

end_to_end_fixture = [
    pytest.param(
        """
            func.func @main(%arg0: !FHE.eint<7>, %arg1: i8) -> !FHE.eint<7> {
                %1 = "FHE.add_eint_int"(%arg0, %arg1): (!FHE.eint<7>, i8) -> (!FHE.eint<7>)
                return %1: !FHE.eint<7>
            }
            """,
        (5, 7),
        12,
        id="add_eint_int",
    ),
    pytest.param(
        """
            func.func @main(%arg0: !FHE.eint<7>) -> !FHE.eint<7> {
                %tlu = arith.constant dense<[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127]> : tensor<128xi64>
                %1 = "FHE.apply_lookup_table"(%arg0, %tlu): (!FHE.eint<7>, tensor<128xi64>) -> (!FHE.eint<7>)
                return %1: !FHE.eint<7>
            }
            """,
        (73,),
        73,
        id="apply_lookup_table",
    ),
    pytest.param(
        """
            func.func @main(%arg0: tensor<4x!FHE.eint<7>>, %arg1: tensor<4xi8>) -> !FHE.eint<7>
            {
                %ret = "FHELinalg.dot_eint_int"(%arg0, %arg1) :
                    (tensor<4x!FHE.eint<7>>, tensor<4xi8>) -> !FHE.eint<7>
                return %ret : !FHE.eint<7>
            }
            """,
        (
            np.array([1, 2, 3, 4], dtype=np.uint8),
            np.array([4, 3, 2, 1], dtype=np.uint8),
        ),
        20,
        id="dot_eint_int_uint8",
    ),
    pytest.param(
        """
            func.func @main(%a0: tensor<4x!FHE.eint<6>>, %a1: tensor<4xi7>) -> tensor<4x!FHE.eint<6>> {
                %res = "FHELinalg.add_eint_int"(%a0, %a1) : (tensor<4x!FHE.eint<6>>, tensor<4xi7>) -> tensor<4x!FHE.eint<6>>
                return %res : tensor<4x!FHE.eint<6>>
            }
            """,
        (
            np.array([31, 6, 12, 9], dtype=np.uint8),
            np.array([32, 9, 2, 3], dtype=np.uint8),
        ),
        np.array([63, 15, 14, 12]),
        id="add_eint_int_1D",
    ),
    pytest.param(
        """
            func.func @main(%arg0: !FHE.esint<7>) -> !FHE.esint<7> {
                %0 = "FHE.neg_eint"(%arg0): (!FHE.esint<7>) -> !FHE.esint<7>
                return %0: !FHE.esint<7>
            }
            """,
        (5,),
        -5,
        id="neg_eint_signed",
    ),
    pytest.param(
        """
            func.func @main(%arg0: tensor<2x!FHE.esint<7>>) -> tensor<2x!FHE.esint<7>> {
                %0 = "FHELinalg.neg_eint"(%arg0): (tensor<2x!FHE.esint<7>>) -> tensor<2x!FHE.esint<7>>
                return %0: tensor<2x!FHE.esint<7>>
            }
            """,
        (np.array([-5, 3]),),
        np.array([5, -3]),
        id="neg_eint_signed_2",
    ),
    pytest.param(
        """
        func.func @main(%arg0: tensor<4x4x!FHE.eint<13>>, %arg1: tensor<4x4xi14>) -> tensor<4x4x!FHE.eint<13>> {
            %0 = "FHELinalg.matmul_eint_int"(%arg0, %arg1) : (tensor<4x4x!FHE.eint<13>>, tensor<4x4xi14>) -> tensor<4x4x!FHE.eint<13>>
            %1 = "FHELinalg.matmul_eint_int"(%0, %arg1) : (tensor<4x4x!FHE.eint<13>>, tensor<4x4xi14>) -> tensor<4x4x!FHE.eint<13>>
            %2 = "FHELinalg.matmul_eint_int"(%1, %arg1) : (tensor<4x4x!FHE.eint<13>>, tensor<4x4xi14>) -> tensor<4x4x!FHE.eint<13>>
            %3 = "FHELinalg.matmul_eint_int"(%2, %arg1) : (tensor<4x4x!FHE.eint<13>>, tensor<4x4xi14>) -> tensor<4x4x!FHE.eint<13>>
            return %3 : tensor<4x4x!FHE.eint<13>>
        }
        """,
        (
            np.array([i // 4 for i in range(16)]).reshape((4, 4)),
            np.array([i // 4 for i in range(15, -1, -1)]).reshape((4, 4)),
        ),
        np.array(
            [
                0,
                0,
                0,
                0,
                1296,
                1296,
                1296,
                1296,
                2592,
                2592,
                2592,
                2592,
                3888,
                3888,
                3888,
                3888,
            ]
        ).reshape((4, 4)),
        id="matul_chain_with_crt",
    ),
    pytest.param(
        """
            func.func @main(%arg0: !FHE.eint<14>, %arg1: tensor<16384xi64>) -> !FHE.eint<14> {
                %cst = arith.constant 15 : i15
                %v = "FHE.add_eint_int"(%arg0, %cst): (!FHE.eint<14>, i15) -> (!FHE.eint<14>)
                %1 = "FHE.apply_lookup_table"(%v, %arg1): (!FHE.eint<14>, tensor<16384xi64>) -> (!FHE.eint<14>)
                return %1: !FHE.eint<14>
            }
        """,
        (
            81,
            np.array(range(16384), dtype=np.uint64),
        ),
        96,
        id="add_lut_crt",
    ),
]

end_to_end_parallel_fixture = [
    pytest.param(
        """
            func.func @main(%x: tensor<3x4x!FHE.eint<7>>, %y: tensor<3x4x!FHE.eint<7>>) -> tensor<3x2x!FHE.eint<7>> {
                %c = arith.constant dense<[[1, 2], [3, 4], [5, 0], [1, 2]]> : tensor<4x2xi8>
                %0 = "FHELinalg.matmul_eint_int"(%x, %c): (tensor<3x4x!FHE.eint<7>>, tensor<4x2xi8>) -> tensor<3x2x!FHE.eint<7>>
                %1 = "FHELinalg.matmul_eint_int"(%y, %c): (tensor<3x4x!FHE.eint<7>>, tensor<4x2xi8>) -> tensor<3x2x!FHE.eint<7>>
                %2 = "FHELinalg.add_eint"(%0, %1): (tensor<3x2x!FHE.eint<7>>, tensor<3x2x!FHE.eint<7>>) -> tensor<3x2x!FHE.eint<7>>
                return %2 : tensor<3x2x!FHE.eint<7>>
            }
            """,
        (
            np.array([[1, 2, 3, 4], [4, 2, 1, 0], [2, 3, 1, 5]], dtype=np.uint8),
            np.array([[1, 2, 3, 4], [4, 2, 1, 1], [2, 3, 1, 5]], dtype=np.uint8),
        ),
        np.array([[52, 36], [31, 34], [42, 52]]),
        id="matmul_eint_int_uint8",
    ),
    pytest.param(
        """
            func.func @main(%a0: tensor<4x!FHE.eint<6>>, %a1: tensor<4xi7>, %a2: tensor<4x!FHE.eint<6>>, %a3: tensor<4xi7>) -> tensor<4x!FHE.eint<6>> {
                %1 = "FHELinalg.add_eint_int"(%a0, %a1) : (tensor<4x!FHE.eint<6>>, tensor<4xi7>) -> tensor<4x!FHE.eint<6>>
                %2 = "FHELinalg.add_eint_int"(%a2, %a3) : (tensor<4x!FHE.eint<6>>, tensor<4xi7>) -> tensor<4x!FHE.eint<6>>
                %res = "FHELinalg.add_eint"(%1, %2) : (tensor<4x!FHE.eint<6>>, tensor<4x!FHE.eint<6>>) -> tensor<4x!FHE.eint<6>>
                return %res : tensor<4x!FHE.eint<6>>
            }
            """,
        (
            np.array([1, 2, 3, 4], dtype=np.uint8),
            np.array([9, 8, 6, 5], dtype=np.uint8),
            np.array([3, 2, 7, 0], dtype=np.uint8),
            np.array([1, 4, 2, 11], dtype=np.uint8),
        ),
        np.array([14, 16, 18, 20]),
        id="add_eint_int_1D",
    ),
]

@pytest.mark.parametrize("mlir_input, args, expected_result", end_to_end_fixture)
def test_lib_compile_and_run_simulation(mlir_input, args, expected_result):
    artifact_dir = "./py_test_lib_compile_and_run"
    engine = LibrarySupport.new(artifact_dir)
    args_and_shape = []
    for arg in args:
        if isinstance(arg, int):
            args_and_shape.append((arg, None))
        else:  # np.array
            args_and_shape.append((arg.flatten().tolist(), list(arg.shape)))
    compile_run_assert(engine, mlir_input, args_and_shape, expected_result)
    shutil.rmtree(artifact_dir)


"""
Parser function parse() to parse the <seedname>-shc-{fermiscan,freqscan}.dat output file of postw90.x.

"""
import inspect
import re
from collections import defaultdict

from . import show_output

def parse(fname):
    """
    Open the file, parses it and return the values.
    """
    retdict = defaultdict(list)

    if show_output:
        print("[{}.{}] Parsing file '{}'".format(
            __name__, inspect.currentframe().f_code.co_name, fname))

    with open(fname) as f:
        lines = f.readlines()

    for lno, l in enumerate(lines):

        pieces = l.split()

        if lno == 0:
            if len(pieces) < 2:
                raise ValueError("Wrong SHC dat file: header is wrong")
            else:
                if pieces[1] == 'Fermi':
                    freqscan = False
                    continue
                elif pieces[1] == 'Frequency(eV)':
                    freqscan = True
                    continue
                else:
                    raise ValueError("Wrong SHC dat file: header is wrong")

        if len(pieces) == 0:
            # skip blank line
            continue

        if freqscan:
            if len(pieces) == 4 :
                retdict['frequency'].append(float(pieces[1]))
                retdict['shc_re'].append(float(pieces[2]))
                retdict['shc_im'].append(float(pieces[3]))
            else:
                raise ValueError("Wrong line length ({}, instead of 4); line content: {}".format(
                    len(pieces), l))
        else:
            if len(pieces) == 3 :
                retdict['energy'].append(float(pieces[1]))
                retdict['shc'].append(float(pieces[2]))
            else:
                raise ValueError("Wrong line length ({}, instead of 3); line content: {}".format(
                    len(pieces), l))

    retdict = dict(retdict)
    if show_output:
        for k in sorted(retdict):
            print("  {}: {}".format(k, retdict[k]))
        print("-"*72)
    return retdict


from queue import deque
from collections import defaultdict

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:

        stack = deque()
        level = 0
        stack.append((level, root))
        d = defaultdict(list)
        while stack:
            level, node = stack.popleft()
            d[level].append(node)
            level += 1
            for child in [node.left, node.right]:
                if child is not None:
                    stack.append((level, child))
        return sum([node.val for node in d[level-1]])


import sys
import time
import string
import threading

def word_check(word):
    global alphabet1, alphabet2

    if len(word) < 5:
        return False

    for i in range(len(word) - 4):
        if word[i] in alphabet2:
            isit = True
            for j in range(i+1, i+5):
                if word[j] in alphabet1 or word[j] in string.punctuation:
                    isit = False

            if isit:
                if word[i:i+5].isupper():
                    return False
                return True
    return False

alphabet1 = "aeiouyAEIOUY"
alphabet2 = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ"

def func():
    while True:
        com = sys.stdin.readline()
        for _ in string.punctuation:
            if _ != '\'':
                com = com.replace(_, ' ')
        while '\'' in com:
            if com[com.index('\'')-1] == ' ':
                com = com[:com.index('\'')-1] + com[com.index('\'')+1:]
        com = com.split()
        if com:
            for word in com:
                if word_check(word):
                    print(word, end=' ')

start_time = time.time()
threading.Thread(target=func, daemon=True).start()
time.sleep(1-(time.time() - start_time))
sys.exit(0)


#for_check_tl
from sys import stdin, stdout

class Node:
    def __init__(self, data = None, next = None):
        self.data = data
        self.next = next

class Linked_List:
    def __init__(self):
        self.size = 0
        self.head = None

    def insert(self, x):
        if self.size == 0:
            node = Node(x)
            self.head = node
        else:
            node = Node(min(self.head.data, x), self.head)
            self.head = node
        self.size += 1

    def erase(self):
        min_el = self.head.data
        if self.size == 1:
            self.head = None
        else:
            self.head = self.head.next
        self.size -= 1
        return min_el

class Stack:
    def __init__(self):
        self.size = 0
        self.elements = Linked_List()

    def push(self, x):
        self.elements.insert(x)

    def pop(self):
        return self.elements.erase()

    def find_min(self):
        ans = self.pop()
        self.push(ans)
        return ans

    def command(self, query):
        if query[0] == '1':
            self.push(int(query[1]))
            return None
        elif query[0] == '2':
            self.pop()
            return None
        else:
            return str(self.find_min())

n = int(stdin.buffer.readline().decode())
stack = Stack()
ans = [stack.command(line.decode().strip().split()) for line in stdin.buffer.readlines()]
ans = '\n'.join(filter(lambda x: x is not None, ans))
stdout.buffer.write(ans.encode())

Стандартные структуры данных/HT4_A.py


#from check_overlap import check_overlap
from relative_pos import relative_pos
from distance2d import distance2d
import copy
import random as rand
import cv2
import numpy as np
# Written 10/27/2016

# Input: LineInteresting, P(Parameters)
# Output: ListPair

def line_match(LineInteresting, list_point_final, P):
    # Constants
    delta_angle = copy.deepcopy(P["delta_angle"])
    min_dist = copy.deepcopy(P["min_dist"])
    max_dist = copy.deepcopy(P["max_dist"])
    blank_image = copy.deepcopy(P["blank_image"])
    rowsize = LineInteresting.shape[0]
    #Number of lines in this contour

    list_pair = []
    matched_lines = []
    cntr_pairs = []
    #Goes through every line
    for i in range(0, rowsize):

        #Compares it with every other line after it
        for j in range(i+1, rowsize):

            #Checking to make sure the smaller line is at least half the size of the larger line
            if(abs(LineInteresting[i, 4]-LineInteresting[j, 4]) < .5*(max(LineInteresting[j, 4], LineInteresting[i, 4]))):

                #Checking to make sure the angles are similar, within the threshold of each other
                if abs(LineInteresting[i, 6] - LineInteresting[j, 6]) <= delta_angle or (abs(LineInteresting[i,6] - LineInteresting[j,6]) >= (180-delta_angle)):

                    #checking to make sure that they are not the same kind of lines
                    #EX: not both discontinuity rights, or discontinuity lefts, or convex
                    if(LineInteresting[i, 12] != LineInteresting[j, 12]):

                        #Checking to make sure they are not too far apart or two close together
                        d = distance2d(LineInteresting[i, :], LineInteresting[j, :])
                        if min_dist < d < max_dist:
                            list_pair.append([i,j])
                            matched_lines.append([LineInteresting[i], LineInteresting[j]])
                            cntr_pairs.append([list_point_final[i], list_point_final[j]])

    print(list_pair, "listpair")
    return list_pair, matched_lines, cntr_pairs


import pdb
from kmap import *
from kplayer import *

def main():
	print('Main')

class Game():
	def __init__(self, map, player):
		self._map = map
		self._player = player
		self._current_player = 0

	def get_map(self):
		return self._map
	def set_map(self, val):
		self._map = val
	map = property(get_map, set_map)

	def get_player(self):
		return self._player
	def set_player(self, val):
		self._player = val
	player = property(get_player, set_player)

	def get_current_player(self):
		return self._current_player
	def set_current_player(self, val):
		self._current_player = val
	current_player = property(get_current_player, set_current_player)

	def turn(self):
		for sol in self.player[self.current_player].soldier:
			while sol.action_point > 0:
				command = input(" > ")
				command = command.split()
				if command:
					if command[0] in ["move", "mv"]:
						sol.go_to(self.map, [int(command[1]), int(command[2])])
					if command[0] in ["pass", "ps"]:
						sol.pass_turn()
					if command[0] in ["position", "pos"]:
						print(sol.pos)
					if command[0] in ["shoot", "st", "sht"]:
						dammage = self.player[self.current_player].weapon[command[1]].shoot()
						if dammage > -1:
							self.player[self.current_player].get_shot(dammage, [command[2],command[3]])
				self.map.print_map(soldiers = self.player[0].soldier + self.player[1].soldier, current_soldier = sol.pos)
				print(sol.action_point)

if __name__ == '__main__':
	main()


# -*- coding: utf-8 -*-
"""
NAME
    download_gfs
KEYWORD ARGUMENTS
    Start and End date (Format: YYYYMMDD)
    Earliest date 1st January 2007 (20070101),
    there are no weather data before that date to download (status May 2019)
KEYWORD ARGUMENTS optional
    path in which the file should be placed
DESCRIPTION
    download_gfs downloads weather data (analysis 0.5 degree grid) from nomads.ncdc.noaa.gov
    linux os is required
NOTE
    The files will not be renamed and not be checked if the download succeded!

    Comments / improvements are welcome.

CONTACT
    florian.geyer@zamg.ac.at
    Version 1, May 2019

DISCLAIMER
    This software has been developed for flexpart workshop 2019 @ ZAMG

"""

def check_date(date):
    """
        checks if date is really a date
    """
    import datetime
    correctDate = None
    date = str(date)

    if (len(date)!=8):
        return False
    year = int(date[0:4])
    month = int(date[4:6])
    day = int(date[6:8])
    try:
        datetime.datetime(year,month,day)
        correctDate = True
    except ValueError:
        correctDate = False
    return correctDate

def convert_str2date(date):
    """
        converts date (as integer) to python datetime
    """
    import datetime
    date = str(date)
    year = int(date[0:4])
    month = int(date[4:6])
    day = int(date[6:8])
    return datetime.datetime(year,month,day)

def create_filenames(date):
    """
        creates filenames for givn date,
        from the runs at 0, 6, 12 and 18 UTC
        only t=0 and t=3 will be downloaded
    """

    filelist = list()
    for t in ["0000", "0600", "1200", "1800"]:
        for t2 in ["000", "003"]:
            filelist.append("gfsanl_4_"+d.strftime('%Y%m%d')+"_"+t+"_"+t2+".grb2")
    return filelist

def download_file(path, filename, destination):
    """
        downloads files from path and saves to destination
    """
    import os
    command = "wget -q -O "+destination+"/"+filename+" ftp://nomads.ncdc.noaa.gov/"+path+"/"+filename
    os.system(command)

def check_path(path):
    """
        checks if path exists
    """
    import os
    if not os.path.exists(path):
        print("Path does not exist")
        print("")
        sys.exit()

def start_ftp_date():
    """
        from this date 0.5 degree grid data exists on ftp
    """
    return 20070101

import sys
from ftplib import FTP
import datetime

print("")

# checking input arguments (1 and 2 are start and end date
try:
    start = sys.argv[1]
    end   = sys.argv[2]
except:
    print("Please give me a start and end date (format: YYYYMMDD)")
    print("")
    sys.exit()

# checking destination (optinal), if no destination givn,
# files will be saved in current directory
try:
    destination = sys.argv[3]
    if (destination[-1]!="/"):
      destination = destination+"/"
except:
    destination = "./"

# print input arguments
print("Start: ", start)
print("End:   ", end)
print("Path: ", destination)
print("")

check_path(destination)

start_ftp_date = start_ftp_date()

# check if dates are in correct format
if (check_date(start)==False):
    print("Wrong start date, please try again (Format should be YYYYMMDD)!")
    print("")
    sys.exit()
if (check_date(end)==False):
    print("Wrong end date, please try again (Format should be YYYYMMDD)!")
    print("")
    sys.exit()
start_date = convert_str2date(start)
end_date   = convert_str2date(end)
start_ftp_date   = convert_str2date(start_ftp_date)

# check if dates are in correct order
if (start_date>end_date):
    print("Your start date was after the end date, I will turn it around!")
    print("")
    start_date, end_date = end_date, start_date

if (start_date<start_ftp_date):
    print("The FTP-Server only provides data after the 1st January 2007, please choose another date!")
    print("")
    sys.exit()

print("start downloading from ", start_date, "to", end_date)

# create date list
date_list = [start_date + datetime.timedelta(days=x) for x in range(0, (end_date-start_date).days+1)]

# connect to ftp
ftp = FTP('nomads.ncdc.noaa.gov')
ftp.login()

# iter through date_list and download
for d in date_list:
    path = "GFS/analysis_only/"+d.strftime('%Y%m')+"/"+d.strftime('%Y%m%d')+"/"
    try:
        ftp.cwd(path)
        print(path, "found")
        file_list_ftp = ftp.nlst()
        file_list = create_filenames(d)
        for f in file_list:
            if f in file_list_ftp:
                print("  ", f, "found, download as "+destination+f)
                download_file(path, f, destination)
            else:
                print("  ", f, "not found")
        ftp.cwd("../../../../")
    except:
        print(d.strftime('%Y/%m/%d'), "Directory not found")
ftp.quit()
print("")


import socket

# 新建Socket
server = socket.socket()

# 绑定IP和端口
server.bind(('127.0.0.1',8999))

# 监听连接
server.listen(5)
s,addr = server.accept()
print(f'connect addr:{addr}')

while True:
    # 接受连接
    content = s.recv(1024)
    if len(content) == 0:
        break
    print(str(content,encoding='utf-8'))
    s.send(content)

s.close()


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
def fun(s):
    if s == '':
        return None
    i = s.find('(')
    if i == -1:
        return TreeNode(int(s))
    root = TreeNode(int(s[:i]))
    i += 1
    ls = i
    count = 1
    while count != 0:
        if s[i] == '(':
            count += 1
        elif s[i] == ')':
            count -= 1
        i += 1
    root.left = fun(s[ls:i-1])
    root.right = fun(s[i+1:len(s)-1])
    return root

class Solution(object):
    def str2tree(self, s):
        """
        :type s: str
        :rtype: TreeNode
        """
        return fun(s)


from manimlib import *
import numpy as np

# To watch one of these scenes, run the following:
# manimgl example_scenes.py OpeningManimExample
# Use -s to skip to the end and just save the final frame
# Use -w to write the animation to a file
# Use -o to write it to a file and open it once done
# Use -n <number> to skip ahead to the n'th animation of a scene.

class ShowInt(Scene):
    def construct(self):

        tarski= ImageMobject("/Users/BennyCohen/manim/gunk/TarskiPhoto.jpeg")
        tarski.scale(1.2)
        tarski.to_edge(RIGHT, buff=1)

        self.play(FadeIn(tarski))
        self.wait(1.0)
        self.play(tarski.animate.shift(LEFT*4))


class Solution:
    def operate(self, preSymbol, preResult, tempResult, tempNum):
        if preSymbol == "+":
            result = preResult + tempResult if tempResult is not None else preResult + int("".join(tempNum))
        else:
            result = preResult - tempResult if tempResult is not None else preResult - int("".join(tempNum))
        return result

    def cal(self, s: str, index = 0):
        left = index
        result = 0
        tempNum = []
        preSymbol = "+"
        tempResult = None
        while left < len(s):
            if s[left] == "(":
                tempResult, left = self.cal(s, left + 1)
            elif s[left] == ")":
                result = self.operate(preSymbol, result, tempResult, tempNum)
                return result, left + 1
            elif s[left] in {"+", "-"}:
                result = self.operate(preSymbol, result, tempResult, tempNum)
                tempNum = []
                tempResult = None
                preSymbol = s[left]
                left += 1
            elif s[left] == " ":
                left += 1
            else:
                tempNum.append(s[left])
                left += 1
        result = self.operate(preSymbol, result, tempResult, tempNum)
        return result, left

    def calculate(self, s: str) -> int:
        return self.cal(s)[0]


import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from matplotlib.colors import ListedColormap
from sklearn.metrics import confusion_matrix

def plot_confusion_matrix(y_true, predictions, title=None, figsize=(8,8), cmap='icefire'):
    """

    """
    plt.figure(figsize=figsize)
    sns.heatmap(confusion_matrix(y_true, predictions), annot=True, fmt='d', cmap=cmap)

    if title:
        plt.title(title)
    plt.xlabel('Actual Class')
    plt.ylabel('Predicted Class')
    plt.show()

def plot_predictions(y_true, predictions, title=None, figsize=(8,8), save_to=None):
    """
    """
    plt.figure(figsize=figsize)
    plt.scatter(predictions, y_true)

    if title:
        plt.title(title)
    plt.xlabel('Predicted Values')
    plt.ylabel('Actual Values')
    if save_to:
        plt.savefig(save_to)
    plt.show()

def plot_decision_regions(X, y, classifier, resolution=0.02, test_idx=None, xlabel='feature1',
                            ylabel='feature2', title=None, legend=None):
    """
    Conveinience function to visualize the decision boundaries
    for two-dimensional datasets
    """
    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                            np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    # plot class examples
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0],
                    y=X[y == cl, 1],
                    alpha=0.8,
                    c=colors[idx],
                    marker=markers[idx],
                    label=cl,
                    edgecolor='black')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if title:
        plt.title(title)
    if legend:
        plt.legend()

    # highlight test examples
    if test_idx:
        # plot all examples
        X_test, y_test = X[test_idx, :], y[test_idx]

        plt.scatter(X_test[:, 0], X_test[:, 1],
                    c='', edgecolor='black', alpha=1.0,
                    linewidth=1, marker='o',
                    s=100, label='test set')
    plt.show()

def plot_linear(X, y, model):
    plt.scatter(X, y, c='steelblue', edgecolor='white', s=70)
    plt.plot(X, model.predict(X), color='black', lw=2)
    plt.show()


from mako.template import Template
import unittest
import os
from mako.compat import py3k, py26, py25
from mako.util import function_named
import re
from mako.cache import CacheImpl, register_plugin
from nose import SkipTest
import sys

template_base = os.path.join(os.path.dirname(__file__), 'templates')
module_base = os.path.join(template_base, 'modules')

class TemplateTest(unittest.TestCase):

    def _file_template(self, filename, **kw):
        filepath = self._file_path(filename)
        return Template(uri=filename, filename=filepath,
                            module_directory=module_base, **kw)

    def _file_path(self, filename):
        name, ext = os.path.splitext(filename)

        if py3k:
            py3k_path = os.path.join(template_base, name + "_py3k" + ext)
            if os.path.exists(py3k_path):
                return py3k_path

        return os.path.join(template_base, filename)

    def _do_file_test(self, filename, expected, filters=None,
                        unicode_=True, template_args=None, **kw):
        t1 = self._file_template(filename, **kw)
        self._do_test(t1, expected, filters=filters,
                        unicode_=unicode_, template_args=template_args)

    def _do_memory_test(self, source, expected, filters=None,
                        unicode_=True, template_args=None, **kw):
        t1 = Template(text=source, **kw)
        self._do_test(t1, expected, filters=filters,
                        unicode_=unicode_, template_args=template_args)

    def _do_test(self, template, expected, filters=None, template_args=None,
                                unicode_=True):
        if template_args is None:
            template_args = {}
        if unicode_:
            output = template.render_unicode(**template_args)
        else:
            output = template.render(**template_args)

        if filters:
            output = filters(output)
        eq_(output, expected)

def eq_(a, b, msg=None):
    """Assert a == b, with repr messaging on failure."""
    assert a == b, msg or "%r != %r" % (a, b)

def teardown():
    import shutil
    shutil.rmtree(module_base, True)

def assert_raises(except_cls, callable_, *args, **kw):
    try:
        callable_(*args, **kw)
        success = False
    except except_cls:
        success = True

    # assert outside the block so it works for AssertionError too !
    assert success, "Callable did not raise an exception"

def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
    try:
        callable_(*args, **kwargs)
        assert False, "Callable did not raise an exception"
    except except_cls:
        e = sys.exc_info()[1]
        assert re.search(msg, str(e)), "%r !~ %s" % (msg, e)
        print(str(e))

def skip_if(predicate, reason=None):
    """Skip a test if predicate is true."""
    reason = reason or predicate.__name__

    def decorate(fn):
        fn_name = fn.__name__
        def maybe(*args, **kw):
            if predicate():
                msg = "'%s' skipped: %s" % (
                    fn_name, reason)
                raise SkipTest(msg)
            else:
                return fn(*args, **kw)
        return function_named(maybe, fn_name)
    return decorate

def requires_python_2(fn):
    return skip_if(lambda: py3k, "Requires Python 2.xx")(fn)

def requires_python_26_or_greater(fn):
    return skip_if(lambda: not py26, "Requires Python 2.6 or greater")(fn)

def requires_python_25_or_greater(fn):
    return skip_if(lambda: not py25, "Requires Python 2.5 or greater")(fn)

def requires_pygments_14(fn):
    try:
        import pygments
        version = pygments.__version__
    except:
        version = "0"
    return skip_if(lambda: version < "1.4")(fn)

def requires_no_pygments_exceptions(fn):
    def go(*arg, **kw):
        from mako import exceptions
        exceptions._install_fallback()
        try:
            return fn(*arg, **kw)
        finally:
            exceptions._install_highlighting()
    return function_named(go, fn.__name__)

class PlainCacheImpl(CacheImpl):
    """Simple memory cache impl so that tests which
    use caching can run without beaker.  """

    def __init__(self, cache):
        self.cache = cache
        self.data = {}

    def get_or_create(self, key, creation_function, **kw):
        if key in self.data:
            return self.data[key]
        else:
            self.data[key] = data = creation_function(**kw)
            return data

    def put(self, key, value, **kw):
        self.data[key] = value

    def get(self, key, **kw):
        return self.data[key]

    def invalidate(self, key, **kw):
        del self.data[key]

register_plugin("plain", __name__, "PlainCacheImpl")


"""
Implementation of Merge Sort
Merge sort is a recursive algorithm that continually splits a list in half.
If the list is empty or has one item, it is sorted by definition (the base case).
If the list has more than one item, we split the list and recursively invoke a merge sort on both halves.
Once the two halves are sorted, the fundamental operation, called a merge, is performed.
Merging is the process of taking two smaller sorted lists and combining them together into a single, sorted, new list.

Class	Sorting algorithm
Data structure	Array
Worst-case performance	O(n log n)
Best-case performance
O(n log n) typical,

O(n) natural variant
Average performance	O(n log n)
Worst-case space complexity	О(n) total, O(n) auxiliary

"""

def mergeSort(arr):

    if len(arr)>1:
        mid = len(arr)//2
        lefthalf = arr[:mid]
        righthalf = arr[mid:]
        mergeSort(lefthalf)
        mergeSort(righthalf)
        i=0
        j=0
        k=0
        while i< len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                arr[k] = lefthalf[i]
                i+=1
            else:
                arr[k] = righthalf[j]
                j+=1

            k+=1
        while i<len(lefthalf):
            arr[k]= lefthalf[i]
            i+=1
            k+=1

        while j< len(righthalf):
            arr[k]=righthalf[j]
            j+=1
            k+=1
    return arr

arr = [11,2,5,4,7,6,8,1,23]
print(mergeSort(arr))


#!/usr/bin/python
# -*- coding: utf8 -*-
from django.contrib import admin
from mainapp.models import *
# Register your models here.
class KeyWordAdmin(admin.ModelAdmin):
	fieldsets = [
		('Словосочетание', {'fields': ['Name']}),
		('Услуга или сырье', {'fields': ['Unit']})
	]

class ArticleAdmin(admin.ModelAdmin):
	fieldsets = [
		('Текст', {'fields': ['Text']}),
		('Словосочетание', {'fields': ['KeyWord']}),
		('Источник', {'fields': ['OwnerUrl']})
	]

class ParagraphAdmin(admin.ModelAdmin):
	fieldsets = [
		('Наименование', {'fields': ['Name']}),
		('картинка', {'fields': ['Image']}),
		('Признак большая картинка', {'fields': ['Large']}),
		('Порядковый номер', {'fields': ['No']}),
		('Ориентация по левому краю', {'fields': ['AlignLeft']}),
		('В алфавитном порядке', {'fields': ['AlphabetOrder']}),
		('Флаг перевозки грузов да/нет', {'fields': ['TransportFlag']})
	]

class UnitAdmin(admin.ModelAdmin):
	fieldsets = [
		('Наименование', {'fields': ['Name']}),
		('Описание', {'fields': ['Description']}),
		('Параграф', {'fields': ['Paragraph']}),
		('Транслит английского', {'fields': ['Eng']}),
		('Закупка кубовыми ёмкостями, бочками', {'fields': ['CanBuyInCubes']}),
		('Доставка в регионы', {'fields': ['DeliveryInRegion']}),
		('Услуги по разгрузке/погрузке', {'fields': ['CanLoadUnload']})
	]

class CustomerAdmin(admin.ModelAdmin):
	fieldsets = [
		('Тип заказчика', {'fields': ['Type']})
	]
class GetInTouchAdmin(admin.ModelAdmin):
	fieldsets = [
		('Имя', {'fields': ['Name']}),
		('Номер телефона', {'fields': ['TelNo']}),
		('э.почта', {'fields': ['Email']}),
		('Текст', {'fields': ['Text']}),
		('Количество (кг)', {'fields': ['Quantity']}),
		('Дата', {'fields': ['DateTime']}),
		('Сырье', {'fields': ['Unit']}),
		('Заказчик', {'fields': ['Customer']}),
		('Дата доставки', {'fields': ['DeliveryDate']})
	]
admin.site.register(Article, ArticleAdmin)
admin.site.register(KeyWord, KeyWordAdmin)
admin.site.register(GetInTouch, GetInTouchAdmin)
admin.site.register(Customer, CustomerAdmin)
admin.site.register(Paragraph, ParagraphAdmin)
admin.site.register(Unit, UnitAdmin)


# uses python3

class Heap:
    def __init__(self, threads):
        self.values = [(0, i) for i in range(threads)]
        self.size = threads

    def sift_down(self):
        """Push element to the leafs of the tree"""

        min_index = index = 0
        while 2 * index + 1 < self.size:

            l_child = 2 * index + 1
            r_child = 2 * index + 2

            if l_child < self.size and self.values[l_child] < self.values[min_index]:
                min_index = l_child

            if r_child < self.size and self.values[r_child] < self.values[min_index]:
                min_index = r_child

            if index != min_index:
                self.values[index], self.values[min_index] = self.values[min_index], self.values[index]
                index = min_index
            else:
                break

    def get_free_thread(self):
        """Get the root of the tree based on time execution"""

        return self.values[0][1], self.values[0][0]

    def update_process(self, job_time):
        time, index = self.values[0]
        self.values[0] = (time + job_time, index)
        self.sift_down()

if __name__ == '__main__':
    threads, num_jobs = [int(i) for i in input().split()]
    heap = Heap(threads)
    jobs = [int(i) for i in input().split()]

    for job in jobs:
        index, time = heap.get_free_thread()
        print(index, time)
        heap.update_process(job)


from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import DetailView, TemplateView

from drchrono.endpoints import AllergyEndpoint, MedicationEndpoint
from drchrono.models import Doctor, Patient

class PatientListView(LoginRequiredMixin, TemplateView):

    template_name = "patient_list.html"

    def get_context_data(self, **kwargs):
        kwargs = super(PatientListView, self).get_context_data(**kwargs)
        doctor = Doctor.objects.first()
        patients = Patient.objects.filter(doctor_id=doctor.api_id).order_by("last_name")
        kwargs["doctor"] = doctor
        kwargs["patients"] = patients
        return kwargs

class PatientDetailView(LoginRequiredMixin, DetailView):

    model = Patient
    template_name = "patient.html"

    def get_context_data(self, **kwargs):
        kwargs = super(PatientDetailView, self).get_context_data(**kwargs)
        allergies_api = AllergyEndpoint(self.request.session["access_token"])
        allergies = allergies_api.list(params={"patient": kwargs["patient"].api_id})
        medications_api = MedicationEndpoint(self.request.session["access_token"])
        medications = medications_api.list(
            params={
                "patient": kwargs["patient"].api_id,
                "status": "active"
            }
        )
        kwargs["allergies"] = allergies
        kwargs["medications"] = medications
        return kwargs


import time

from community import community_louvain
import torch
from parsor import parameter_parser
from clustering import ClusteringMachine
from clustergcn import ClusterGCNTrainer
from utils import tab_printer, graph_reader, feature_reader, target_reader
import deepdish as dd
import networkx as nx
import numpy as np

def main():
    """
    Parsing command line parameters, reading data, graph decomposition, fitting a ClusterGCN and scoring the model.
    """
    # 载入参数
    args = parameter_parser()
    # 为PyTorch生成随机数设定种子
    torch.manual_seed(args.seed)
    # 将参数以列表格式输出
    tab_printer(args)
    # # 读入图G
    # graph = graph_reader(args.edge_path)
    # # 读入特征矩阵X
    # features = feature_reader(args.features_path)
    # # 读入目标矩阵Y
    # target = target_reader(args.target_path)
    start_time = time.time()
    print('Start load data...')
    train_data = dd.io.load('data/botnet/processed/c2_train.hdf5')['0']
    edge_idx = train_data["edge_index"]
    print(f'Data loaded({time.time()-start_time:.2f} s), start preprocessing...')
    start_time = time.time()
    edges = [[edge_idx[0][i], edge_idx[1][i]] for i, _ in enumerate(edge_idx[0])]
    # # Metis不支持自连接
    # edges = [[edge_idx[0][i], edge_idx[1][i]] for i, _ in enumerate(edge_idx[0]) if
    #          not edge_idx[0][i] == edge_idx[1][i]]
    graph = nx.Graph(edges)
    #print(f'Graph build finished({time.time()-start_time:.2f} s), start partition...')
    #start_time = time.time()
    #groups = community_louvain.best_partition(graph)
    #print(f'Partition finished({time.time() - start_time:.2f} s), start calculating modularity...')
    #start_time = time.time()
    #print(f'num_clusters={len(set(groups.values()))}, modularity={community_louvain.modularity(groups, graph)}, {time.time()-start_time:.2f} s')

    adj_view = graph.adj
    full_adj = [np.array([i[0] for i in adj_view[idx].items()], dtype=int) for idx in range(len(adj_view))]
    print(full_adj[0])
    graph = nx.MultiGraph(edges)

    exit(0)
    num_edges = 0
    for i in range(len(full_adj)):
        num_edges += len(full_adj[i])
    print(graph)
    print(f'num_edges={num_edges}, len(full_adj)={len(full_adj)}, len(full_adj[0])={len(full_adj[0])}')
    features = train_data["x"]
    target = np.reshape(train_data["y"], (-1, 1))
    # 图分解，划分特征和目标
    clustering_machine = ClusteringMachine(args, graph, features, target)
    clustering_machine.decompose()
    # 训练模型
    gcn_trainer = ClusterGCNTrainer(args, clustering_machine)

    gcn_trainer.train()
    # 预测
    gcn_trainer.test()

if __name__ == "__main__":
    main()


# qlearningAgents.py
# ------------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

from game import *
from learningAgents import ReinforcementAgent
from featureExtractors import *

import random,util,math

class QLearningAgent(ReinforcementAgent):
    """
      Q-Learning Agent

      Functions you should fill in:
        - computeValueFromQValues
        - computeActionFromQValues
        - getQValue
        - getAction
        - update

      Instance variables you have access to
        - self.epsilon (exploration prob)
        - self.alpha (learning rate)
        - self.discount (discount rate)

      Functions you should use
        - self.getLegalActions(state)
          which returns legal actions for a state
    """
    def __init__(self, **args):
        "You can initialize Q-values here..."
        ReinforcementAgent.__init__(self, **args)

        "*** YOUR CODE HERE ***"
        # Figure I'll initialize the states to hold qvals like we did in the
        # valueIterationAgents.py
        self.qvalues = util.Counter()

    def getQValue(self, state, action):
        """
          Returns Q(state,action)
          Should return 0.0 if we have never seen a state
          or the Q node value otherwise
        """
        "*** YOUR CODE HERE ***"
        # If we have seen this state and action pair, then let's return the
        # appropriate q value
        if (state,action) in self.qvalues:
            return self.qvalues[(state,action)]

        # Otherwise, let's return 0.0
        else:
            return 0.0

    def computeValueFromQValues(self, state):
        """
          Returns max_action Q(state,action)
          where the max is over legal actions.  Note that if
          there are no legal actions, which is the case at the
          terminal state, you should return a value of 0.0.
        """
        "*** YOUR CODE HERE ***"
        # Let's get the available actions at the current state, and then we can
        # loop through (s,a) for a in actions to find the correct pair
        actions = self.getLegalActions(state)

        # If we have no available actions, we must be at a terminal state, so
        # we'll return 0.0
        if len(actions) == 0:
            return 0.0

        # If we're not at a terminal state, the value may be something other
        # than 0.0, so let's figure it out and return it
        else:

            # We'll create a holder of all the qvalues based on each action
            qvalues = []

            # We'll loop through each action and keep track of the corresponding
            # qvalue
            for action in actions:
                qvalues.append(self.getQValue(state,action))

            # In accordance with the qvalue function, let's return the max
            # qvalue
            return max(qvalues)

    def computeActionFromQValues(self, state):
        """
          Compute the best action to take in a state.  Note that if there
          are no legal actions, which is the case at the terminal state,
          you should return None.
        """
        "*** YOUR CODE HERE ***"
        # We're importing random now so that we can use it later, as you'll see
        import random

        # Let's get our available actions so we can loop through each
        # (state, action) pair again
        actions = self.getLegalActions(state)

        # If there aren't any actions available, then we've reached a terminal
        # state, so there really isn't any appropriate action that we should
        # return lol
        if len(actions) == 0:
            return None

        # If we're not at a terminal state, then there is an appropriate action
        # to return, so let's find it
        else:

            # We'll initialize a list to keep track of our (action, qvalue)
            # pairs and another to keep track of the individual qvalues.
            allpairs = []
            allqvals = []

            # Now, we'll loop through each action and append said action and
            # the attached qvalue to allpairs, and append the qvalue to the
            # allqvals list.
            for action in actions:
                allpairs.append((action, self.getQValue(state,action)))
                allqvals.append(self.getQValue(state,action))

            # Let's find what the max qval is
            maxVal = max(allqvals)

            # There's a possibility that multiple actions hold the max qval, and
            # we should leave a chance to explore each one, so we'll initialize
            # a list of the maxactions and append the appropriate pairs
            maxactions = []
            for pair in allpairs:
                if pair[1] == maxVal:
                    maxactions.append(pair)

            # We'll use our imported random package so we can make a random
            # choice among which max action to return
            return random.choice(maxactions)[0]

    def getAction(self, state):
        """
          Compute the action to take in the current state.  With
          probability self.epsilon, we should take a random action and
          take the best policy action otherwise.  Note that if there are
          no legal actions, which is the case at the terminal state, you
          should choose None as the action.

          HINT: You might want to use util.flipCoin(prob)
          HINT: To pick randomly from a list, use random.choice(list)
        """
        # Pick Action
        legalActions = self.getLegalActions(state)
        action = None

        "*** YOUR CODE HERE ***"
        # We want to choose a random action for P(epsilon). We'll simulate
        # P(epsilon) using flipcoin(epsilon).
        if util.flipCoin(self.epsilon):
            return random.choice(legalActions)

        # flipcoin(epsilon) returns true for P(epsilon), so it returns false
        # the remaining amount of times. Thus, in accordance with the problem
        # prompt, we'll choose our known best action for P(not epsilon)
        else:
            return self.computeActionFromQValues(state)

    def update(self, state, action, nextState, reward):
        """
          The parent class calls this to observe a
          state = action => nextState and reward transition.
          You should do your Q-Value update here

          NOTE: You should never call this function,
          it will be called on your behalf
        """
        "*** YOUR CODE HERE ***"
        # We can just follow the equation established in the video lecture
        # slides

        # We use (1-alpha)*Q(s,a) to offer a lower priority to old data
        olddata = (1 - self.alpha) * self.getQValue(state, action)

        # We use alpha(reward + lambda * Q(s',a')) to offer more priority to new
        # data
        newdata = self.alpha * (reward + self.discount * self.computeValueFromQValues(nextState))

        # We sum the two to find our new qvalue
        self.qvalues[(state,action)] = olddata + newdata

    def getPolicy(self, state):
        return self.computeActionFromQValues(state)

    def getValue(self, state):
        return self.computeValueFromQValues(state)

class PacmanQAgent(QLearningAgent):
    "Exactly the same as QLearningAgent, but with different default parameters"

    def __init__(self, epsilon=0.05,gamma=0.8,alpha=0.2, numTraining=0, **args):
        """
        These default parameters can be changed from the pacman.py command line.
        For example, to change the exploration rate, try:
            python pacman.py -p PacmanQLearningAgent -a epsilon=0.1

        alpha    - learning rate
        epsilon  - exploration rate
        gamma    - discount factor
        numTraining - number of training episodes, i.e. no learning after these many episodes
        """
        args['epsilon'] = epsilon
        args['gamma'] = gamma
        args['alpha'] = alpha
        args['numTraining'] = numTraining
        self.index = 0  # This is always Pacman
        QLearningAgent.__init__(self, **args)

    def getAction(self, state):
        """
        Simply calls the getAction method of QLearningAgent and then
        informs parent of action for Pacman.  Do not change or remove this
        method.
        """
        action = QLearningAgent.getAction(self,state)
        self.doAction(state,action)
        return action

class ApproximateQAgent(PacmanQAgent):
    """
       ApproximateQLearningAgent

       You should only have to overwrite getQValue
       and update.  All other QLearningAgent functions
       should work as is.
    """
    def __init__(self, extractor='IdentityExtractor', **args):
        self.featExtractor = util.lookup(extractor, globals())()
        PacmanQAgent.__init__(self, **args)
        self.weights = util.Counter()

    def getWeights(self):
        return self.weights

    def getQValue(self, state, action):
        """
          Should return Q(state,action) = w * featureVector
          where * is the dotProduct operator
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()

    def update(self, state, action, nextState, reward):
        """
           Should update your weights based on transition
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()

    def final(self, state):
        "Called at the end of each game."
        # call the super-class final method
        PacmanQAgent.final(self, state)

        # did we finish training?
        if self.episodesSoFar == self.numTraining:
            # you might want to print your weights here for debugging
            "*** YOUR CODE HERE ***"
            pass


import numpy as np
from delira.data_loading.dataset import AbstractDataset, DictDataset, \
    IterableDataset
from collections import Iterable, defaultdict

class DataLoader:
    """
    Basic Dataloader class, that returns data for a given set of indices and
    combines it as batches
    """

    def __init__(self, data):
        """
        Parameters
        ----------
        data : Any
            the data to use; Ideally this either is a dataset, an iterable or
            a dict, but in general, this must only be indexable, have a length
            and return a dict of arrays if indexed
        """
        self._process_id = None
        if isinstance(data, AbstractDataset):
            dataset = data

        else:
            # wrap it into dataset depending on datatype
            if isinstance(data, dict):
                dataset = DictDataset(data)
            elif isinstance(data, Iterable):
                dataset = IterableDataset(data)
            else:
                raise TypeError("Invalid dataset type: %s"
                                % type(data).__name__)

        self.dataset = dataset

    def __call__(self, indices):
        """
        Loads data for given indices and combines them to batches
        Parameters
        ----------
        indices : list
            a list of integers specifying the data indices
        Returns
        -------
        dict
            a dict of numpy arrays (specifying the batches)
        """

        # get data for all indices
        data = [self.dataset[idx] for idx in indices]

        data_dict = defaultdict(list)

        # concatenate dict entities by keys
        for _result_dict in data:
            for key, val in _result_dict.items():
                data_dict[key].append(val)

        # convert list to numpy arrays
        for key, val_list in data_dict.items():
            data_dict[key] = np.asarray(val_list)

        return data_dict

    @property
    def process_id(self):
        """
        A Property to access the process id
        Returns
        -------
        int
            the process id
        """
        if self._process_id is None:
            return 0
        return self._process_id

    @process_id.setter
    def process_id(self, new_id):
        """
        Setter for the :attr:`process_id`; Makes sure, that the process id is
        only set once
        Parameters
        ----------
        new_id : int
        Raises
        ------
        AttributeError
            if the process id has already been set once
        """
        if self._process_id is not None:
            raise AttributeError("Attribute 'process_id' can be set only once")

        self._process_id = new_id


from django.contrib import admin

# Register your models here.
from .models import EmployeeDetail

class EmployeeAdmin(admin.ModelAdmin):
    list_display = ["user_id" , "created" , "updated"]

    class Meta:
        model = EmployeeDetail

admin.site.register(EmployeeDetail,EmployeeAdmin)


import pygame as pg
from pygame.locals import *

tela = pg.display.set_mode((1080,720),pg.RESIZABLE)

perso = pg.image.load('Projetos/proj_turmaA/sprites.png').conve
perso_ani = []
rec_perso = perso.get_rect()
rec_perso.x = 50
rec_perso.y = 500

vila = pg.Surface((300,300))
vila.fill((165,42,42))
rec_vila = vila.get_rect()
rec_vila.x = 600
rec_vila.y = 200

time = pg.time.Clock()

spt_x = 32
spt_y = 32

for line in range(perso.get_height()//spt_y):
    for col in range(perso.get_width()//spt_x):
        x = col * spt_x
        y = line * spt_y
        trans = perso.subsurface(pg.Rect(x, y, spt_x, spt_y))
        perso_ani.append(trans)

while True:

    time.tick(30)

    for event in pg.event.get():
        if event.type == QUIT:
            pg.quit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pg.quit()
        if pg.key.get_pressed()[K_w]:
            rec_perso.y -= 25

        if pg.key.get_pressed()[K_s]:
            rec_perso.y += 25

        if pg.key.get_pressed()[K_a]:
            rec_perso.x -= 25

        if pg.key.get_pressed()[K_d]:
            rec_perso.x += 25
            for i in range(8,12):
                tela.blit(perso_ani[i])

        if rec_perso.colliderect(rec_vila):
            print('colidiu')

        tela.fill((0,0,0))
        tela.blit(vila,rec_vila)
        tela.blit(perso_ani[0],rec_perso)

    pg.display.update()


import pandas as pd
import numpy as np

dict1 = {'name':['Arul','Jeya','Arul','Rekha', 'Rahim','John'],
         'lname':['Arul','Arul','Bright','Nair','Ulla','Peter'],
         'age':[51,47,np.nan,43,32,28],
         'sex':['M','F','M','F','M','M']}

dict2 = {'name':['a','b','c','d','e','f','g','h'],
         'state':['tn','ka','ts','tn','ts','tn','ka','tn'],
         'city':['vnr','blr','hyd','mdu','hyd','vnr','mys','vnr'],
         'salary':[2000,3000,2500,2200,3500,np.nan,2800,1800]}

dict3 = {'name':['a','b','c','d','e','f','g','h'],
         'bonus':[100,200,150,400,250,300,500,180]}

df1 = pd.DataFrame(dict1)
mean_age = df1['age'].mean()
df1['age'].fillna(mean_age,inplace=True)
# GroupBy
print("Groupby Examples ")
df2 = df1.groupby(by=['name','sex'],axis=0).mean('age')
print(df2)
df3 = pd.DataFrame(dict2)
mean_salary = df3['salary'].mean()
df3['salary'].fillna(mean_salary,inplace=True)

df4 = df3.groupby(['state','city']).count()
print(df4)
df4 = df3.groupby(['state','city']).mean('salary')
print(df4)

# Merge
df4 = pd.DataFrame(dict3)
df5 = df3.merge(df4,on='name')
print("Merge Example ")
print(df5)

# Conditions
print(df1.eq(['Arul','Jeya','Arul','Jeya','Rahim','John'],axis='index'))
print(df1.eq(['','Bright',46,'M']))

# Transformations
df2 = df1.groupby('sex')['age'].transform('mean')
print(df2)

# Most used Pandas methods
print(df1.head())
print(df1.describe())
print(df1.memory_usage())
print(df1.loc[1:3,['name','sex']])
print(df1['sex'].value_counts())
print(df1['name'].drop_duplicates())


from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

maslahat_olish = ReplyKeyboardMarkup(keyboard=[
    [KeyboardButton(text="✍ Maslahat olish")],
    [KeyboardButton("🔙 Orqaga qaytish")]
], resize_keyboard=True)

phone = KeyboardButton(text="📞 Telefon raqam yuborish", request_contact=True)
back_button = KeyboardButton(text="🔙 Orqaga qaytish")
back_main_page = KeyboardButton("🏘 Bosh menyu")

advice_phone = ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
advice_phone.add(phone)
advice_phone.add(back_main_page)


import numpy as np # linear algebra
#import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from tflite_runtime.interpreter import Interpreter
#import tensorflow as tf

# Load the TFLite model and allocate tensors.
#interpreter = tf.lite.Interpreter(model_path="rw_seq_model.tflite")
interpreter = Interpreter(model_path="rw_seq_model.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test the model on random input data.
input_shape = input_details[0]['shape']
print(input_shape)

input_data = np.array([[0.6028,-1.0966,-0.3046,0.1674,-0.5065,1.0156 ]], dtype=np.float32)
print(input_data.shape)

interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print("Walk status:" + str(output_data[0][0]))

input_data_run = np.array([[-1.0739,0.0033,0.1052,2.1021,-0.9863,0.2939]],dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data_run)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print("Run status:"+ str(output_data[0][0]))

#print("Predict for run [{:.6%}]".(output_data))


"""

Analysis of titanic.xml (originally from
https://pythonprogramming.net/static/downloads/machine-learning-data/titanic.xls), which is a spreadsheet of all of the
known people on the HMS Titanic. The spreadsheet is formatted out like this:

pclass - Passenger Class (1 = 1st; 2 = 2nd; 3 = 3rd)
survival - Survival (0 = No; 1 = Yes)
name - Name
sex - Sex
age - Age
sibsp - Number of Siblings/Spouses Aboard
parch - Number of Parents/Children Aboard
ticket - Ticket Number
fare - Passenger Fare (British pound)
cabin - Cabin
embarked - Port of Embarkation (C = Cherbourg; Q = Queenstown; S = Southampton)
boat - Lifeboat number (if they got onto one)
body - Body Identification Number
home.dest - Home/Destination

This program attempts to determine whether a person would live or die given the above traits (minus survival). As well,
which of these traits are most decisive of a person surviving.

"""

import os
import numpy as np
from sklearn.cluster import KMeans
from sklearn import preprocessing
import pandas as pd

df = pd.read_excel(os.getcwd() + "/titanic.xls")
df.drop(["body", "name"], 1, inplace=True)
df.convert_objects(convert_numeric=True)
df.fillna(0, inplace=True)

def handle_non_numerical_data(df):
    columns = df.columns.values

    for column in columns:
        text_digit_vals = {}
        def convert_to_int(val):
            return text_digit_vals[val]

        if df[column].dtype != np.int64 and df[column].dtype != np.float64:
            column_contents = df[column].values.tolist()
            unique_elements = set(column_contents)
            x = 0
            for unique in unique_elements:
                if unique not in text_digit_vals:
                    text_digit_vals[unique] = x
                    x += 1

            df[column] = list(map(convert_to_int, df[column]))

    return df

df = handle_non_numerical_data(df)

X = np.array(df.drop(["survived"], 1).astype(float))
X = preprocessing.scale(X)
y = np.array(df["survived"])

clf = KMeans(n_clusters=2)
clf.fit(X)

correct = 0
for i in range(len(X)):
    predict_me = np.array(X[i].astype(float))
    predict_me = predict_me.reshape(-1, len(predict_me))
    prediction = clf.predict(predict_me)
    if prediction[0] == y[i]:
        correct += 1

print(correct / len(X))


import os

# List of scripts to run in order
scripts = ['ngramcounter.py', 'analyze.py', 'finalsort.py']

# Construct the full path to the scripts directory
scripts_dir = os.path.join(os.getcwd(), "scripts")

# Run the scripts in the order specified
for script in scripts:
    # Construct the full path to the script
    script_path = os.path.join(scripts_dir, script)
    # Run the script
    os.system(f"python3 {script_path}")

# Remove the output files
os.remove("output.txt")
os.remove("ngramoutput.txt")

# Print the first 10 lines of FinalResults.txt
with open("FinalResults.txt") as f:
    for i in range(10):
        print(f.readline())


from pythautomata.abstract.probabilistic_model import ProbabilisticModel
from pythautomata.base_types.sequence import Sequence
from pythautomata.utilities import pdfa_utils
import math
from sklearn.metrics import ndcg_score
import numpy as np
epsilon = Sequence()

def ndcg_score_avg(target_model: ProbabilisticModel, learned_model: ProbabilisticModel, test_sequences: list[Sequence]):
    suffixes = list()
    suffixes.append(Sequence() + learned_model.terminal_symbol)
    ndcg = list()
    k = math.ceil(len(learned_model.alphabet) / 2)

    for symbol in learned_model.alphabet.symbols:
        suffixes.append(Sequence((symbol,)))

    all_obs1 = target_model.last_token_probabilities_batch(
        test_sequences, suffixes)
    all_obs2 = learned_model.last_token_probabilities_batch(
        test_sequences, suffixes)

    for i in range(len(all_obs1)):
        obs1 = np.asarray([all_obs1[i]])
        obs2 = np.asarray([all_obs2[i]])
        ndcg_word_score = ndcg_score(obs1, obs2, k=k)
        ndcg.append(ndcg_word_score)

    return np.mean(np.array(ndcg))

def wer_avg(target_model: ProbabilisticModel, learned_model: ProbabilisticModel, test_sequences: list[Sequence]):
    suffixes = list()
    suffixes.append(Sequence() + learned_model.terminal_symbol)
    wer = 0

    for symbol in learned_model.alphabet.symbols:
        suffixes.append(Sequence((symbol,)))

    all_obs1 = target_model.last_token_probabilities_batch(
        test_sequences, suffixes)
    all_obs2 = learned_model.last_token_probabilities_batch(
        test_sequences, suffixes)

    for i in range(len(all_obs1)):
        obs1 = np.asarray(all_obs1[i])
        obs2 = np.asarray(all_obs2[i])
        max1 = np.argmax(obs1)
        max2 = np.argmax(obs2)
        if max1 != max2:
            wer += 1

    return wer / len(test_sequences)

def log_probability_error(target_model: ProbabilisticModel, learned_model: ProbabilisticModel, test_sequences: list[Sequence]):
    errors = list()
    for seq in test_sequences:
        errors.append(abs(target_model.log_sequence_weight(seq) -
                      learned_model.log_sequence_weight(seq)))
    return np.mean(np.array(errors))

def out_of_tolerance_elements(target_model: ProbabilisticModel, learned_model: ProbabilisticModel, test_sequences: list[Sequence], tolerance):
    suffixes = list()
    errorCount = 0
    suffixes.append(Sequence() + learned_model.terminal_symbol)
    for symbol in learned_model.alphabet.symbols:
        suffixes.append(Sequence((symbol,)))

    all_obs1 = target_model.last_token_probabilities_batch(
        test_sequences, suffixes)
    all_obs2 = learned_model.last_token_probabilities_batch(
        test_sequences, suffixes)

    for i in range(len(all_obs1)):
        obs1 = np.asarray(all_obs1[i])
        obs2 = np.asarray(all_obs2[i])
        if not pdfa_utils.are_within_tolerance_limit(obs1, obs2, tolerance):
            errorCount += 1

    return errorCount

def out_of_partition_elements(target_model: ProbabilisticModel, learned_model: ProbabilisticModel, test_sequences: list[Sequence], partitions: int):
    suffixes = list()
    errorCount = 0
    suffixes.append(Sequence() + learned_model.terminal_symbol)
    for symbol in learned_model.alphabet.symbols:
        suffixes.append(Sequence((symbol,)))

    all_obs1 = target_model.last_token_probabilities_batch(
        test_sequences, suffixes)
    all_obs2 = learned_model.last_token_probabilities_batch(
        test_sequences, suffixes)

    for i in range(len(all_obs1)):
        obs1 = np.asarray(all_obs1[i])
        obs2 = np.asarray(all_obs2[i])
        p1 = pdfa_utils.get_quantized_interval_partitions(obs1, partitions)
        p2 = pdfa_utils.get_quantized_interval_partitions(obs2, partitions)
        result = pdfa_utils.compare_quantized_interval_partition(p1, p2)
        if not result:
            errorCount += 1

    return errorCount

def absolute_error_avg(target_model: ProbabilisticModel, learned_model: ProbabilisticModel, test_sequences: list[Sequence]):
    suffixes = list()
    suffixes.append(Sequence() + learned_model.terminal_symbol)

    for symbol in learned_model.alphabet.symbols:
        suffixes.append(Sequence((symbol,)))

    all_obs1 = target_model.last_token_probabilities_batch(
        test_sequences, suffixes)
    all_obs2 = learned_model.last_token_probabilities_batch(
        test_sequences, suffixes)

    absolute_error_sum = 0
    for i in range(len(all_obs1)):
        obs1 = np.asarray(all_obs1[i])
        obs2 = np.asarray(all_obs2[i])
        absolute_error_sum += np.sum(np.abs(obs1-obs2))

    return absolute_error_sum / len(test_sequences)

def cross_entropy(target_distribution, learned_distribution):
    # Categorical Cross Entropy Metric implemented following Keras implementation
    y_true = target_distribution
    y_pred = learned_distribution

    mask_0 = y_pred == 0
    y_true = y_true + mask_0*1e-7
    y_pred = y_pred + mask_0*1e-7

    mask_1 = y_pred == 1
    y_true = y_true - mask_1*1e-7
    y_pred = y_pred - mask_1*1e-7

    y_pred = y_pred/np.sum(y_pred)
    cross_entropy = - np.sum(y_true*np.log(y_pred))
    return cross_entropy

def mean_cross_entropy(target_model: ProbabilisticModel, learned_model: ProbabilisticModel, test_sequences: list[Sequence]):
    suffixes = list()
    suffixes.append(Sequence() + learned_model.terminal_symbol)
    for symbol in learned_model.alphabet.symbols:
        suffixes.append(Sequence((symbol,)))

    target_obs = target_model.last_token_probabilities_batch(
        test_sequences, suffixes)
    learned_obs = learned_model.last_token_probabilities_batch(
        test_sequences, suffixes)

    ce_sum = 0
    for i in range(len(target_obs)):
        obs1 = np.asarray(target_obs[i])
        obs2 = np.asarray(learned_obs[i])
        ce_sum += cross_entropy(obs1, obs2)

    return ce_sum / len(test_sequences)


import argparse
from pathlib import Path

import torch
from transformers import (
    AutoTokenizer,
    GenerationConfig,
    PreTrainedModel,
    PreTrainedTokenizer,
)
from utils import FileStreamer

@torch.no_grad()
def endless_generate(
    model: PreTrainedModel,
    tokenizer: PreTrainedTokenizer,
    text: str,
    log_file: str,
    min_new_tokens: int = 1000,
    max_new_tokens: int = 10000,
) -> str:
    streamer = FileStreamer(tokenizer, log_file)
    input_ids = tokenizer.encode(text, return_tensors="pt").to(model.device)
    generated_tokens = model.generate(
        input_ids,
        generation_config=GenerationConfig(
            # use_cache=True is required, the rest can be changed up.
            use_cache=True,
            min_new_tokens=min_new_tokens,
            max_new_tokens=max_new_tokens,
            penalty_alpha=0.6,
            top_k=4,
            pad_token_id=tokenizer.pad_token_id,
            eos_token_id=tokenizer.eos_token_id,
        ),
        streamer=streamer,
    )
    # Decode the final generated text
    return tokenizer.decode(generated_tokens[0], skip_special_tokens=True)

def main():
    parser = argparse.ArgumentParser()

    # Which experiment to run?
    parser.add_argument(
        "--experiment", choices=["attention_sinks", "transformers", "windowed"], default="attention_sinks"
    )

    # Model args
    parser.add_argument("--model_name_or_path", type=str, default="meta-llama/Llama-2-7b-hf")
    parser.add_argument("--revision", type=str, default="main")
    parser.add_argument("--trust_remote_code", action="store_true")

    # Input text
    parser.add_argument("--text", type=str, default="Vaswani et al. (2017) introduced the Transformers")

    # Generation args
    parser.add_argument("--min_new_tokens", type=int, default=1000)
    parser.add_argument("--max_new_tokens", type=int, default=10000)

    # Where to log
    parser.add_argument("--log_file", type=str, default=None)

    # Window size for windowed and attention_sinks
    parser.add_argument("--window_size", type=int, default=512)

    # Attention Sinks-only settings
    # Attention Sink window size is calculated with args.window_size - args.attention_sink_size
    parser.add_argument("--attention_sink_size", type=int, default=4)

    args = parser.parse_args()

    # Initialize the model, either via transformers or via attention_sinks
    if args.experiment == "transformers":
        from transformers import AutoModelForCausalLM
    else:
        from attention_sinks import AutoModelForCausalLM
    kwargs = {}
    if args.experiment == "attention_sinks":
        kwargs = {
            "attention_sink_size": args.attention_sink_size,
            "attention_sink_window_size": args.window_size - args.attention_sink_size,  # default: 1020
        }
    elif args.experiment == "windowed":
        kwargs = {
            "attention_sink_size": 0,
            "attention_sink_window_size": args.window_size,
        }
    model = AutoModelForCausalLM.from_pretrained(
        args.model_name_or_path,
        revision=args.revision,
        trust_remote_code=bool(args.trust_remote_code),
        torch_dtype=torch.float16,
        device_map="auto",
        **kwargs,
    )
    model.eval()
    tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, trust_remote_code=bool(args.trust_remote_code))
    tokenizer.pad_token_id = tokenizer.eos_token_id

    log_file = args.log_file or Path("demo") / "endless_logs" / args.experiment / f"{args.model_name_or_path}.txt"
    endless_generate(
        model,
        tokenizer,
        args.text,
        log_file=log_file,
        min_new_tokens=args.min_new_tokens,
        max_new_tokens=args.max_new_tokens,
    )

if __name__ == "__main__":
    main()


#!/usr/bin/env python
from fdfgen import forge_fdf
from pathlib import Path

service_months = ["September", "October", "November", "December", "January", "February", "March", "April", "May", "June", "July", "August"]

fields = {
  "Name": "Jhovana Gutiérrez",
  "Date of birth": "Fecha de nacimiento (programa)",
  "Date immersed": "Fecha de bautismo (programa)",

  "Check Box1": True, # Man
  "Check Box2": True, # Female
  "Check Box3": True, # Other Sheep
  "Check Box4": True, # Anointed
  "Check Box5": True, # Elder
  "Check Box6": True, # Ministerial Servant
  "Check Box7": True, # Regular Pioneer
}

first_year = 2025
for year_index in range(2):
  year_num = year_index + 1
  year_num_underscore = "_2" if year_num == 2 else ""
  fields[f"Service Year{year_num_underscore}"] = first_year + year_index
  for service_month_index in range(12):
    service_month = service_months[service_month_index]
    service_month_num = service_month_index + 1
    fields[f"{year_num}-Place_{service_month_num}"] = year_index * 60 + service_month_index * 5 + 1
    fields[f"{year_num}-Video_{service_month_num}"] = year_index * 60 + service_month_index * 5 + 2
    fields[f"{year_num}-Hours_{service_month_num}"] = year_index * 60 + service_month_index * 5 + 3
    fields[f"{year_num}-RV_{service_month_num}"] = year_index * 60 + service_month_index * 5 + 4
    fields[f"{year_num}-Studies_{service_month_num}"] = year_index * 60 + service_month_index * 5 + 5
    fields[f"Remarks{service_months[service_month_index]}{year_num_underscore}"] = f"Notas para {service_months[service_month_index]} de {first_year + year_index}"

fdf = forge_fdf("",[*fields.items()],[],[],[])

Path("PublisherCard.es.fdf").write_bytes(fdf)


from ravendb import SessionOptions, GetIndexesOperation, AbstractIndexCreationTask, IndexDefinition
from ravendb.infrastructure.orders import Company
from ravendb.tests.test_base import TestBase

class Companies_ByUnknown(AbstractIndexCreationTask):
    def __init__(self):
        super(Companies_ByUnknown, self).__init__()

    def create_index_definition(self) -> IndexDefinition:
        index_definition = IndexDefinition()
        index_definition.name = "Companies/ByUnknown"
        index_definition.maps = {"from c in docs.Companies select new { unknown = c.unknown };"}
        return index_definition

class Companies_ByUnknown_WithIndexMissingFieldsAsNull(AbstractIndexCreationTask):
    def __init__(self):
        super(Companies_ByUnknown_WithIndexMissingFieldsAsNull, self).__init__()

    def create_index_definition(self) -> IndexDefinition:
        index_definition = IndexDefinition()
        index_definition.name = "Companies/ByUnknown/WithIndexMissingFieldsAsNull"
        index_definition.maps = {"from c in docs.Companies select new { unknown = c.unknown };"}
        index_definition.configuration["Indexing.IndexMissingFieldsAsNull"] = "true"
        return index_definition

class TestRavenDB14084(TestBase):
    def setUp(self):
        super(TestRavenDB14084, self).setUp()

    def test_can_index_missing_fields_an_null_static(self):
        Companies_ByUnknown().execute(self.store)
        Companies_ByUnknown_WithIndexMissingFieldsAsNull().execute(self.store)

        with self.store.open_session() as session:
            company = Company()
            company.name = "HR"
            session.store(company)

            session.save_changes()

        self.wait_for_indexing(self.store)

        session_options = SessionOptions()
        session_options.no_caching = True

        with self.store.open_session(session_options=session_options) as session:
            companies = list(
                session.advanced.document_query_from_index_type(
                    Companies_ByUnknown_WithIndexMissingFieldsAsNull, Company
                ).where_equals("unknown", None)
            )

            self.assertEqual(1, len(companies))

        index_definitions = self.store.maintenance.send(GetIndexesOperation(0, 10))
        self.assertEqual(2, len(index_definitions))

        configuration = (
            list(filter(lambda x: x.name == "Companies/ByUnknown/WithIndexMissingFieldsAsNull", index_definitions))
            .pop()
            .configuration
        )

        self.assertEqual(1, len(configuration))
        self.assertIn("Indexing.IndexMissingFieldsAsNull", configuration)
        self.assertEqual("true", configuration["Indexing.IndexMissingFieldsAsNull"])


from cs1graphics import *
from time import *
import math
import random

# rotate(n) 시계 방향으로 n도 회전 시킴
# scale(n) n배 커짐
# flip(n) 축을  n도 회전시켜서 기준으로 접힘
paper = Canvas()

paper.setBackgroundColor('powderBlue')
paper.setWidth(500)
paper.setHeight(200)
paper.setTitle('draw')

def animate_sunrise(sun):
    w = paper.getWidth()
    h = paper.getHeight()
    r = sun.getRadius()
    x0 = w / 2.0
    y0 = h + r
    xradius = w / 2.0 - r
    yradius = h
    for angle in range(181):  # 0 ~ 180
        rad = (angle/180.0) * math.pi
        x = x0 - xradius * math.cos(rad)
        y = y0 - yradius * math.sin(rad)
        sun.moveTo(x, y)

ground = Ellipse(700, 100, Point(300, 200))
ground.setFillColor('green')
paper.add(ground)

sun = Circle(50, Point(400, 100))
sun.setFillColor('orange')
sun.setDepth(60)
paper.add(sun)

roof = Polygon(Point(105, 105), Point(175, 105),
               Point(170, 85), Point(110, 85))
roof.setFillColor('black')
paper.add(roof)

facade = Square(60, Point(140, 130))
facade.setFillColor('gray')
paper.add(facade)

cat = Layer()
leg1 = Rectangle(10, 10, Point(-20, -10))
leg1.setFillColor('brown')
cat.add(leg1)

leg2 = Rectangle(10, 10, Point(20, -10))
leg2.setFillColor('brown')
cat.add(leg2)

body = Rectangle(60, 30, Point(0, -30))
body.setFillColor('brown')
cat.add(body)

head = Circle(20, Point(-30, -50))
head.setFillColor('brown')
cat.add(head)

eyes1 = Circle(3, Point(-21, -53))
eyes1.setFillColor('black')
cat.add(eyes1)

eyes2 = Circle(3, Point(-41, -53))
eyes2.setFillColor('black')
cat.add(eyes2)

nose = Ellipse(10, 5, Point(-30, -43))
nose.setFillColor('black')
cat.add(nose)

ear1 = Polygon(Point(-15, -80), Point(-25, -65), Point(-15, -60))
ear1.setFillColor('brown')
cat.add(ear1)

ear2 = Polygon(Point(-45, -80), Point(-35, -65), Point(-45, -60))
ear2.setFillColor('brown')
cat.add(ear2)

giraffe = Layer()

leg1 = Rectangle(10, 70, Point(400, 150))
leg1.setFillColor('yellow')
giraffe.add(leg1)

leg2 = Rectangle(10, 70, Point(320, 150))
leg2.setFillColor('yellow')
giraffe.add(leg2)

body = Rectangle(100, 30, Point(360, 130))
body.setFillColor('yellow')
giraffe.add(body)
neck = Rectangle(20, 70, Point(400, 100))
neck.setFillColor('yellow')
giraffe.add(neck)

head = Polygon(Point(400, 50), Point(450, 110), Point(400, 100))
head.setFillColor('yellow')
giraffe.add(head)

ear1 = Rectangle(8, 15, Point(410, 50))
ear1.setFillColor('brown')
giraffe.add(ear1)
ear2 = Rectangle(8, 15, Point(400, 50))
ear2.setFillColor('brown')
giraffe.add(ear2)

eyes2 = Circle(10, Point(415, 70))
eyes2.setFillColor('white')
giraffe.add(eyes2)

eyes1 = Circle(3, Point(415, 70))
eyes1.setFillColor('black')
giraffe.add(eyes1)

pattern = [None for _ in range(8)]

for i in range(8):
    num1 = random.randrange(320, 400)
    num2 = random.randrange(120, 140)
    pattern[i] = Square(6, Point(num1, num2))
    pattern[i].setFillColor('brown')
    giraffe.add(pattern[i])

giraffe.setDepth(10)
paper.add(giraffe)

cat.moveTo(110, 180)
cat.setDepth(10)
paper.add(cat)

timeDelay = 0.1

for i in range(10):
    cat.move(-10 - i*10, 0)

    sun.move(10+i*15, 5*i)
    sleep(timeDelay*2)

    giraffe.move(10+i*5, +5*i)
    sleep(timeDelay)


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index),
    url(r'^register$', views.register),
    url(r'^welcome$', views.welcome),
    url(r'^login$', views.login),
    url(r'^logout$', views.logout),
    url(r'^add_a_book$', views.add_a_book),
    url(r'^books/(?P<id>\d+)$', views.book_parser),
    url(r'^favorite/(?P<id>\d+)$', views.favorite),
]


# class Node(object):
#     """单向链接节点类"""

#     def __init__(self, data, next=None):
#         """实例化一个节点, 默认后继节点为None"""
#         self.data = data
#         self.next = next

# class TwoWayNode(Node):
#     """双向链接节点类"""

#     def __init__(self, data, previous=None, next=None):
#         """实例化一个节点, 默认前序节点尾None, 默认后继节点为None"""
#         Node.__init__(self, data, next)
#         self.previous = previous

# class LinkedList:
#     """单向和双向链接结构"""

#     def __init__(self, node):
#         # 初始化头节点
#         self.head = node
#         # 属性size保存链接结构的逻辑大小，通常指的是链表所包含的元素的数量，初始化链接结构大小为0
#         self.size = 0

#     def insert_from_list(self, data_list, twoway=False):
#         """
#         把一个列表（已有的数据结构）转换为链接结构是一种比较常见实用的方式。这种做法可以通过控制代码，方便地从已有的集合类（如列表，数组等）中导入元素，并构建需要的的链接结构。
#         在一些简单场景下，比如已知待添加的元素数量很少，或者有其他约束使得用列表不方便时，可以通过手动方式向链接结构添加元素。但如果元素很多，或者有未知数量的元素需要添加，用列表可以方便地一次性导入所有元素。
#         """
#         if twoway:  # 检查是否要创建双向链表
#             for data in data_list:  # 对于数据列表中的每个数据创建一个新的双向链接节点
#                 node = TwoWayNode(data)

#                 if self.head is None:  # 如果链表为空把新节点设置为头节点
#                     self.head = node
#                 else:  # 如果链表不为空
#                     tail = self.head  # 从头节点开始
#                     while tail.next is not None:  # 通过遍历链表查找尾节点
#                         tail = tail.next
#                     tail.next = node  # 把新节点插入到尾节点
#                     node.previous = tail  # 设置新节点的前一个节点指向尾节点
#         else:  # 创建单向链表
#             for data in reversed(data_list):  # 对于列表中的每个元素，反向迭代使得插入的节点与原数据顺序相同
#                 self.head = Node(data, self.head)  # 创建一个新的单向链接节点并插入到头节点
#         self.size += len(data_list)  # 更新链表大小

#     def get_size(self):
#         """获取链表大小（节点数量）"""
#         return self.size

#     def search(self, target):
#         """在链接结构中搜索指定元素"""
#         current = self.head  # 从头节点开始
#         while current:  # 当当前节点非None时继续遍历
#             if current.data == target:  # 如果当前节点的数据等于目标数据
#                 return True  # 返回真值
#             current = current.next  # 移动到下一节点
#         return False  # 如果整个链表遍历完毕还找不到目标数据，返回假值

#     def locate(self, index):
#         """返回链接结构中第index个元素, 0 <= index < n"""
#         if index >= self.get_size() or index < 0:   # 如果索引超出范围，立即抛出错误
#             raise IndexError("链表索引超出范围")

#         probe = self.head  # 确定起始点为头节点
#         while index > 0:  # 当索引大于0时，进入循环
#             probe = probe.next  # 将探针（probe）移动到下一个节点
#             index -= 1  # 将索引值减1
#         return probe.data  # 返回当前位置（index对应位置）的节点数据

#     def replace(self, old, new):
#         """替换链表中所有等于old的元素为new"""
#         current = self.head  # 从链表的头节点开始遍历
#         while current:  # 只要还有节点，就继续遍历
#             if current.data == old:  # 检查当前节点的数据是否等于old
#                 current.data = new  # 如果等于old，将当前节点的数据替换为new
#             current = current.next  # 继续检查下一个节点

#     def print_list(self):
#         """打印输出链接结构内容"""
#         current = self.head
#         while current:
#             print(current.data, end=' ')
#             current = current.next
#         print()

# def main():
#     # 创建测试数据
#     test_data = [1, 2, 3, 4, 5]

#     # 单向链表测试
#     print("单向链表测试:")
#     single_linked_list = LinkedList(None)
#     print("插入数据")
#     single_linked_list.insert_from_list(test_data)  # 插入测试数据
#     single_linked_list.print_list()  # 打印链接结构内容
#     print("链表大小：", single_linked_list.get_size())  # 显示链接结构大小
#     print("搜索元素3: ", single_linked_list.search(3))  # 搜索链接结构中是否存在元素3
#     print("查找第2个元素: ", single_linked_list.locate(2))  # 查找链接结构中第2个元素
#     print("把元素1替换为10")
#     single_linked_list.replace(1, 10)  # 替换元素1为10
#     single_linked_list.print_list()

#     print()

#     # 双向链表测试
#     print("双向链表测试:")
#     double_linked_list = LinkedList(None)
#     print("插入数据")
#     double_linked_list.insert_from_list(test_data, twoway=True)
#     double_linked_list.print_list()
#     print("链表大小：", double_linked_list.get_size())
#     print("搜索元素3：", double_linked_list.search(3))
#     print("查找第2个元素：", double_linked_list.locate(2))
#     print("替换元素1为10")
#     double_linked_list.replace(1, 10)
#     double_linked_list.print_list()

# if __name__ == "__main__":
#     main()

# # 运行结果
# # 单向链表测试:
# # 插入数据
# # 1 2 3 4 5
# # 链表大小： 5
# # 搜索元素3： True
# # 查找第2个元素： 3
# # 替换元素1为10
# # 10 2 3 4 5

# # 双向链表测试:
# # 插入数据
# # 1 2 3 4 5
# # 链表大小： 5
# # 搜索元素3： True
# # 查找第2个元素： 3
# # 替换元素1为10
# # 10 2 3 4 5

# =============================================
# =============================================
# =============================================
# =============================================
class Node(object):
    """单向链接节点类"""

    def __init__(self, data, next=None):
        """
        实例化一个节点, 默认后继节点为None

        Args:
            data: 节点存储的数据
            next: 指向下一个节点的指针，默认为None
        """
        self.data = data  # 定义节点的数据部分
        self.next = next  # 定义节点的指针部分，初始值为None表示没有下一个节点

def insert_at_beginning(head, data):
    """
    在链表开始处插入新节点

    Args:
        head: 当前链表的头节点
        data: 新节点的数据

    Returns:
        Node: 新的头节点
    """
    new_node = Node(data)  # 创建新的节点对象
    new_node.next = head  # 将新节点的next指针指向当前头节点
    return new_node  # 返回新的头节点

def insert_at_end(head, data):
    """
    在链表末尾插入新节点

    Args:
        head: 当前链表的头节点
        data: 新节点的数据

    Returns:
        Node: 头节点
    """
    new_node = Node(data)  # 创建新的节点对象
    if head is None:  # 如果链表为空，将新节点设置为头节点
        head = new_node
    else:
        probe = head  # 创建一个指针，从头节点开始遍历链表
        while probe.next is not None:  # 当指针所指节点有下一个节点时
            probe = probe.next  # 移动指针到下一个节点
        probe.next = new_node  # 将新节点连接到当前指针所指节点的下一个位置，完成节点的插入
    return head  # 返回头节点

def delete_at_beginning(head):
    """
    从链表开始处删除节点

    Args:
        head: 当前链表的头节点

    Returns:
        Node: 新的头节点
    """
    if head is None:  # 如果链表为空，打印消息并返回空链表
        print("Linked list is empty.")
    else:
        head = head.next  # 将头节点指向下一个节点，即删除第一个节点
    return head  # 返回新的头节点

def delete_at_end(head):
    """
    从链表末尾删除节点

    Args:
        head: 当前链表的头节点

    Returns:
        Node: 头节点
    """
    if head is None:  # 如果链表为空，返回None
        return None
    if head.next is None:  # 如果链表只有一个节点，将头节点置为None
        return None
    current = head
    while current.next.next:  # 移动到倒数第二个节点
        current = current.next
    current.next = None  # 将倒数第二个节点的next置为None，即删除了最后一个节点
    return head  # 返回头节点

def insert_at_position(head, data, position):
    """
    在链表的任意位置插入新节点

    Args:
        head: 当前链表的头节点
        data: 新节点的数据
        position: 插入的位置

    Returns:
        Node: 头节点
    """
    new_node = Node(data)  # 创建新的节点对象
    if position == 0:  # 如果插入位置为0，即在头部插入
        new_node.next = head  # 新节点的next指向当前头节点
        return new_node  # 返回新的头节点
    probe = head  # 创建一个指针，从头节点开始遍历链表
    count = 0
    while probe.next is not None and count < position - 1:  # 找到插入位置的前一个节点
        probe = probe.next
        count += 1
    new_node.next = probe.next  # 新节点的next指向插入位置的节点
    probe.next = new_node  # 插入位置的前一个节点的next指向新节点
    return head  # 返回头节点

def delete_at_position(head, position):
    """
    从链表的任意位置删除节点

    Args:
        head: 当前链表的头节点
        position: 删除的位置

    Returns:
        Node: 头节点
    """
    if head is None:  # 如果链表为空，返回None
        return None
    if position == 0:  # 如果删除位置为0，即删除头部节点
        return head.next  # 返回头节点的下一个节点
    probe = head  # 创建一个指针，从头节点开始遍历链表
    count = 0
    while probe.next is not None and count < position - 1:  # 找到删除位置的前一个节点
        probe = probe.next
        count += 1
    if probe.next is None:  # 如果删除位置超过链表长度，不做操作
        return head
    probe.next = probe.next.next  # 删除位置的前一个节点的next指向删除位置的后一个节点
    return head  # 返回头节点

def print_linked_list(head):
    """
    打印链表中的所有节点

    Args:
        head: 当前链表的头节点
    """
    probe = head
    while probe is not None:
        print(probe.data, end=" -> ")  # 打印当前节点的数据
        probe = probe.next  # 移动到下一个节点
    print("None")  # 打印链表结束的标志

def main():
    head = None  # 创建一个空链表，初始时头节点为None

    # 从尾部插入节点
    for count in range(1, 6):  # 从1到5遍历
        head = insert_at_end(head, count)  # 在尾部插入节点

    print("初始链表:")
    print_linked_list(head)  # 打印原始链表

    # 验证从头部处插入节点
    new_data_at_beginning = 0
    head = insert_at_beginning(head, new_data_at_beginning)  # 在链表头部插入新节点
    print(f"\n在头部插入 {new_data_at_beginning} 后的链表:")
    print_linked_list(head)  # 打印插入新节点后的链表状态

    # 验证从末尾处插入节点
    new_data = 10
    head = insert_at_end(head, new_data)  # 在链表末尾插入新节点
    print(f"\n在尾部插入 {new_data} 后的链表:")
    print_linked_list(head)  # 打印插入新节点后的链表状态

    # 验证从头部删除节点
    head = delete_at_beginning(head)  # 删除第一个节点
    print("\n从头部删除节点后的链表:")
    print_linked_list(head)  # 打印删除节点后的链表状态

    # 验证从尾部删除节点
    head = delete_at_end(head)  # 从链表末尾删除节点
    print("\n从尾部删除节点后的链表:")
    print_linked_list(head)  # 打印删除节点后的链表状态

    # 验证从任意位置插入节点
    position = 3
    new_data = 99
    head = insert_at_position(head, new_data, position)  # 在第3个位置插入节点
    print(f"\n在位置 {position} 插入 {new_data} 后的链表:")
    print_linked_list(head)

    # 验证从任意位置删除节点
    position = 2
    head = delete_at_position(head, position)  # 删除第2个位置的节点
    print(f"\n在位置 {position} 插入 {new_data} 后的链表:")
    print_linked_list(head)

if __name__ == "__main__":
    main()

# 运行结果
# 初始链表:
# 1 -> 2 -> 3 -> 4 -> 5 -> None

# 在头部插入 0 后的链表:
# 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> None

# 在尾部插入 10 后的链表:
# 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 10 -> None

# 从头部删除节点后的链表:
# 1 -> 2 -> 3 -> 4 -> 5 -> 10 -> None

# 从尾部删除节点后的链表:
# 1 -> 2 -> 3 -> 4 -> 5 -> None

# 在位置 3 插入 99 后的链表:
# 1 -> 2 -> 3 -> 99 -> 4 -> 5 -> None

# 在位置 2 插入 99 后的链表:
# 1 -> 2 -> 99 -> 4 -> 5 -> None